From steve at pearwood.info  Tue Dec  1 01:15:55 2015
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 1 Dec 2015 17:15:55 +1100
Subject: [Tutor] Python 3.5 console logging
In-Reply-To: <CAMy-Wb5+Fou8_S5_+EU6-JYmeV+ZshC0rMW32COuJBbb=Ma5vA@mail.gmail.com>
References: <CAMy-Wb5+Fou8_S5_+EU6-JYmeV+ZshC0rMW32COuJBbb=Ma5vA@mail.gmail.com>
Message-ID: <20151201061555.GA18779@ando.pearwood.info>

Hi Tyler, and welcome,

On Mon, Nov 30, 2015 at 04:50:35PM -0500, Tyler Smithers wrote:

> I am doing a project for my school and i am trying to find out how to make
> a event log. But every where i look all it has is just making a text
> document and it having in their what they put in their script. But i cant
> find out how to code python into recording everything that happens when i
> run the program. And can you please help me soon because i don't have much
> time. Thank you!

I'm not sure I understand what you want. Do you mean you want to use the 
interactive interpreter, and every time you enter a line, that line gets 
saved in a log file?

That's normally called "history", and Python 3.5 will have history 
automatically turned on. If you hit the UP or DOWN arrows, the prompt 
will go through the history, showing each line. Is that what you mean?

Otherwise, perhaps you could look at sys.__interactivehook__ and 
sys.__displayhook__. I'm not sure how advanced you are with Python 
programming, so if you need more help, please ask.


-- 
Steve

From cs at zip.com.au  Tue Dec  1 02:33:34 2015
From: cs at zip.com.au (Cameron Simpson)
Date: Tue, 1 Dec 2015 18:33:34 +1100
Subject: [Tutor] Python 3.5 console logging
In-Reply-To: <CAMy-Wb5+Fou8_S5_+EU6-JYmeV+ZshC0rMW32COuJBbb=Ma5vA@mail.gmail.com>
References: <CAMy-Wb5+Fou8_S5_+EU6-JYmeV+ZshC0rMW32COuJBbb=Ma5vA@mail.gmail.com>
Message-ID: <20151201073334.GA9247@cskk.homeip.net>

On 30Nov2015 16:50, Tyler Smithers <tsmithers731 at gmail.com> wrote:
>I am doing a project for my school and i am trying to find out how to make
>a event log. But every where i look all it has is just making a text
>document and it having in their what they put in their script.

That is normally what an event log it; a text file recording significant 
events. This can be done simply with print() calls or more elaborately via the 
logging module.

>But i cant
>find out how to code python into recording everything that happens when i
>run the program. And can you please help me soon because i don't have much
>time. Thank you!

When you say everything, what do you mean? Normally people don't want that 
("everything" might mean every python code line traversed, or every internal 
python opcode executed, etc). Normally that is an insane amount of details, and 
people normally just want to know significant events (user logged in, did this, 
was refused that, files opened/closed or stuff like that).

You'll need to elaborate a bit more on what you're trying to achieve here.

Cheers,
Cameron Simpson <cs at zip.com.au>

From turtle at 64.hu  Tue Dec  1 02:33:18 2015
From: turtle at 64.hu (=?UTF-8?B?VsOhbGFzIFDDqXRlcg==?=)
Date: Tue, 1 Dec 2015 08:33:18 +0100
Subject: [Tutor] Python 3.5 console logging
In-Reply-To: <CAMy-Wb5+Fou8_S5_+EU6-JYmeV+ZshC0rMW32COuJBbb=Ma5vA@mail.gmail.com>
References: <CAMy-Wb5+Fou8_S5_+EU6-JYmeV+ZshC0rMW32COuJBbb=Ma5vA@mail.gmail.com>
Message-ID: <CALx55K9gNROoWqnnSQT5qePERjxtACGmvpv-a5F5d79yTiXHHA@mail.gmail.com>

2015-11-30 22:50 GMT+01:00 Tyler Smithers <tsmithers731 at gmail.com>:

> I am doing a project for my school and i am trying to find out how to make
> a event log. But every where i look all it has is just making a text
> document and it having in their what they put in their script. But i cant
> find out how to code python into recording everything that happens when i
> run the program. And can you please help me soon because i don't have much
> time. Thank you!
>

I don't reaaly understand what you mean by "everything" (do you want a
keylogger or a complete memory dump?).
But the folks at Python.org wrote a nice howto:
https://docs.python.org/3/howto/logging.html
Does this help?

From badwolfwitch at yahoo.com  Tue Dec  1 00:04:15 2015
From: badwolfwitch at yahoo.com (jo stone)
Date: Tue, 1 Dec 2015 05:04:15 +0000 (UTC)
Subject: [Tutor] assignment sign definition
References: <319559754.13222113.1448946255094.JavaMail.yahoo.ref@mail.yahoo.com>
Message-ID: <319559754.13222113.1448946255094.JavaMail.yahoo@mail.yahoo.com>

Hello,
I am trying to teach myself Python, and got hung up on the definition of Assignment signs...The explination I have is:
"A good way to understand the statement userAge = 0 is to think of it as userAge <- 0."

I read this as "userAge is less than minus 0"? ? which make absolutely NO sense to me...
Could someone please put this into terms I can understand?

Thanks! 

From alan.gauld at btinternet.com  Tue Dec  1 04:58:29 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 1 Dec 2015 09:58:29 +0000
Subject: [Tutor] assignment sign definition
In-Reply-To: <319559754.13222113.1448946255094.JavaMail.yahoo@mail.yahoo.com>
References: <319559754.13222113.1448946255094.JavaMail.yahoo.ref@mail.yahoo.com>
 <319559754.13222113.1448946255094.JavaMail.yahoo@mail.yahoo.com>
Message-ID: <n3jr05$6tf$1@ger.gmane.org>

On 01/12/15 05:04, jo stone via Tutor wrote:
> Hello,
> I am trying to teach myself Python, and got hung up on the definition of Assignment signs...

This is usually only a big problem for those who are strong in
mathematics where = means that two things are equal in value and does
not mean that either of them is changing value., In programming (in
Python and many other languages) it means that the left hand side
takes on the value of the right hand side. (For expressing equality
we use a double == instead)

> The explination I have is:
> "A good way to understand the statement userAge = 0 is to think of it as userAge <- 0."
> 
> I read this as "userAge is less than minus 0"    which make absolutely NO sense to me...

This looks like a classic case of somebody confusing things
by trying to explain it :-) The <- is intended to be seen
as an arrow pointing from the 0 to the userAge name. It
indicates that userAge takes on the value 0.

Another way of thinking about it is to read assignments in
code as the word "becomes" so you read

userAge = 0

as

userAge becomes zero.

For a different (and slightly more technically correct)
explanation of assignment in Python try reading the section
on variables in my tutor(see below) in the "Raw Materials"
topic.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at btinternet.com  Tue Dec  1 05:06:22 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 1 Dec 2015 10:06:22 +0000
Subject: [Tutor] Python 3.5 console logging
In-Reply-To: <CAMy-Wb5+Fou8_S5_+EU6-JYmeV+ZshC0rMW32COuJBbb=Ma5vA@mail.gmail.com>
References: <CAMy-Wb5+Fou8_S5_+EU6-JYmeV+ZshC0rMW32COuJBbb=Ma5vA@mail.gmail.com>
Message-ID: <n3jreu$efs$1@ger.gmane.org>

On 30/11/15 21:50, Tyler Smithers wrote:

> find out how to code python into recording everything that happens when i
> run the program. And can you please help me soon because i don't have much
> time. Thank you!

You need to be a bit more precise about how you define an "event".
Everything that happens on your computer even during a few seconds
is a vast amount of information(every mouse movement, keystroke, network
data arriving/leaving, disk activity, monitor updates
etc etc). Even recording everything that your code does is
still quite a lot.

Normally in an event log you set some values to determine
exactly what things you want to record (eg opening a file,
reading input from users, changing key variables etc)

If you can clarify exactly what you want this event log to
look like it will help both you and us figure out how to
create it. Try mocking up the expected output and showing
us what you'd like to see

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at btinternet.com  Tue Dec  1 05:16:50 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 1 Dec 2015 10:16:50 +0000
Subject: [Tutor] Countdown Clock Programming Question
In-Reply-To: <CAPNRz83Va1M4uESEqURKFJgnb=K-cE0p9pn23OuukYWg4Weq=A@mail.gmail.com>
References: <CAPNRz83ooFrYkqq6E7SvOeJW6aaWQoO0H-OXh7nrCrU-XQ9+MQ@mail.gmail.com>
 <CAPNRz83Va1M4uESEqURKFJgnb=K-cE0p9pn23OuukYWg4Weq=A@mail.gmail.com>
Message-ID: <n3js2j$o74$1@ger.gmane.org>

On 30/11/15 19:23, Evan Sommer wrote:
> Hello again Alan!
> 
>  Do you think you could write a revised code with the modifications that
> you suggested? I tried changing the code with your recommendations and I
> keep getting syntax errors.

My code was just an approximation known as 'pseudo code' you
need to translate it into real Python.

>> import time
>> def count_down():
>>     # start with 4 minutes --> 240 seconds
>>     for t in range(240, 120, -1):
>>         # format as 2 digit integers, fills with zero to the left
>>         # divmod() gives minutes, seconds
>>         sf = "{:01d}:{:02d}".format(*divmod(t, 60))
>>         #print(sf)  # test
>>         time_str.set(sf)
>>         root.update()
>>         # delay one second
>>         time.sleep(1)# create root/main window

Don't use time.sleep() in a Tkinter program use the after
method instead. In this case it will look like

root.after(1000, count_down)

Also instead of hard coding the 240 and 120 make them
parameters of the function like

def count_down(start, end):

and put those names into your loop:

for t in range(start,stop,-1)

That way you can call it multiple times with the
different values you need and avoid duplicating
the for loop below

Try those fixes initially and see how you go.

>> root = tk.Tk()
>> time_str = tk.StringVar()
>> # create the time display label, give it a large font
>> # label auto-adjusts to the font
>> label_font = ('helvetica', 100)
>> tk.Label(root, textvariable=time_str, font=label_font, bg='green',
>>          fg='white', relief='raised', bd=3).pack(fill='x', padx=5, pady=5)
>>  # start with 2 minutes --> 119 seconds
>> for t in range(240, 120, -1):

call count_down(240,120) here

>>         # format as 2 digit integers, fills with zero to the left
>>         # divmod() gives minutes, seconds
>>         sf = "{:01d}:{:02d}".format(*divmod(t, 60))
>>         #print(sf)  # test
>>         time_str.set(sf)
>>         root.update()
>>         # delay one second
>>         time.sleep(1)
>> # create the time display label, give it a large font
>> # label auto-adjusts to the font
>> label_font = ('helvetica', 100)
>> tk.Label(root, textvariable=time_str, font=label_font, bg='yellow',
>>          fg='white', relief='raised', bd=3).pack(fill='x', padx=5, pady=5)
>>  # start with 1 minutes --> 59 seconds
>> for t in range(120,60, -1):

call count_down(120,60) here

>>         # format as 2 digit integers, fills with zero to the left
>>         # divmod() gives minutes, seconds
>>         sf = "{:01d}:{:02d}".format(*divmod(t, 60))
>>         #print(sf)  # test
>>         time_str.set(sf)
>>         root.update()
>>         # delay one second
>>         time.sleep(1)
>> # create the time display label, give it a large font
>> # label auto-adjusts to the font
>> label_font = ('helvetica', 100)
>> tk.Label(root, textvariable=time_str, font=label_font, bg='red',
>>          fg='white', relief='raised', bd=3).pack(fill='x', padx=5, pady=5)
>>  # start with 4 minutes --> 240 seconds
>> for t in range(60,-1, -1):

call count_down(60,-1) here

>>         # format as 2 digit integers, fills with zero to the left
>>         # divmod() gives minutes, seconds
>>         sf = "{:01d}:{:02d}".format(*divmod(t, 60))
>>         #print(sf)  # test
>>         time_str.set(sf)
>>         root.update()
>>         # delay one second
>>         time.sleep(1)
>> # start the GUI event loop
>> root.mainloop()
>>

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From lac at openend.se  Tue Dec  1 05:27:02 2015
From: lac at openend.se (Laura Creighton)
Date: Tue, 01 Dec 2015 11:27:02 +0100
Subject: [Tutor] assignment sign definition
In-Reply-To: <319559754.13222113.1448946255094.JavaMail.yahoo@mail.yahoo.com>
References: <319559754.13222113.1448946255094.JavaMail.yahoo.ref@mail.yahoo.com>
 <319559754.13222113.1448946255094.JavaMail.yahoo@mail.yahoo.com>
Message-ID: <201512011027.tB1AR2s2032465@fido.openend.se>

In a message of Tue, 01 Dec 2015 05:04:15 +0000, jo stone via Tutor writes:
>Hello,
>I am trying to teach myself Python, and got hung up on the definition of Assignment signs...The explination I have is:
>"A good way to understand the statement userAge = 0 is to think of it as userAge <- 0."
>
>I read this as "userAge is less than minus 0"? ? which make absolutely NO sense to me...
>Could someone please put this into terms I can understand?
>
>Thanks! 

The author of that tutorial does not want you to think using thoughts
like the word equal.  He or she thinks that if you see a line like
'a = 0' you will think 'a is equal to 0' and that is exactly what he
or she does not want you to do.  'You had the thought 'equal'.  Bad
thought.  Don't have it!' 

So he or she thinks that the language would be better if, in using
assigments, there was some other symbol to use.

He or she would like "a ? 0" instead.  That is the unicode symbol U21e6
in there, between the a and the 0.  It looks like an arrow that points 
to the left.

But, since the author doesn't have access to unicode for some reason
he or she decided to fake an arrow by '<-'  which sort of liiks like
an arrow in some fonts.  

Make sense?

Laura

From lac at openend.se  Tue Dec  1 05:31:37 2015
From: lac at openend.se (Laura Creighton)
Date: Tue, 01 Dec 2015 11:31:37 +0100
Subject: [Tutor] Python 3.5 console logging
In-Reply-To: <n3jreu$efs$1@ger.gmane.org>
References: <CAMy-Wb5+Fou8_S5_+EU6-JYmeV+ZshC0rMW32COuJBbb=Ma5vA@mail.gmail.com>
 <n3jreu$efs$1@ger.gmane.org>
Message-ID: <201512011031.tB1AVbM3032636@fido.openend.se>

He may be looking for something like the logging facility of Gnu screen.
'Please capture all the output of my python program and show it to me
later'.  Of course this will be of little or no use if his program
has a GUI.

Laura

From alan.gauld at btinternet.com  Tue Dec  1 12:33:47 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 1 Dec 2015 17:33:47 +0000
Subject: [Tutor] Countdown Clock Programming Question
In-Reply-To: <n3js2j$o74$1@ger.gmane.org>
References: <CAPNRz83ooFrYkqq6E7SvOeJW6aaWQoO0H-OXh7nrCrU-XQ9+MQ@mail.gmail.com>
 <CAPNRz83Va1M4uESEqURKFJgnb=K-cE0p9pn23OuukYWg4Weq=A@mail.gmail.com>
 <n3js2j$o74$1@ger.gmane.org>
Message-ID: <n3kllr$d8c$1@ger.gmane.org>

On 01/12/15 10:16, Alan Gauld wrote:

>>> def count_down():
>>>     # start with 4 minutes --> 240 seconds
>>>     for t in range(240, 120, -1):
>>>         # format as 2 digit integers, fills with zero to the left
>>>         # divmod() gives minutes, seconds
>>>         sf = "{:01d}:{:02d}".format(*divmod(t, 60))
>>>         #print(sf)  # test
>>>         time_str.set(sf)
>>>         root.update()
>>>         # delay one second
>>>         time.sleep(1)# create root/main window
> 
> Don't use time.sleep() in a Tkinter program use the after
> method instead. In this case it will look like
> 
> root.after(1000, count_down)

I just realized my advice is slightly contradictory.
If you add parameters to count_down you can't pass
it to after() directly. Instead you need to rewrite
count_down and use a little trick in after() like this:

def count_down(start, stop)
    sf = "{:01d}:{:02d}".format(*divmod(start, 60))
    time_str.set(sf)
    root.update()
    if start > stop:
       root.after(1000, lambda: count_down(start-1,stop) )

Notice it has no loop, instead after() subtracts 1 second
from the start value each time it calls count_down.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From cs at zip.com.au  Thu Dec  3 20:03:46 2015
From: cs at zip.com.au (Cameron Simpson)
Date: Fri, 4 Dec 2015 12:03:46 +1100
Subject: [Tutor] Python 3.5 console logging
In-Reply-To: <201512011031.tB1AVbM3032636@fido.openend.se>
References: <201512011031.tB1AVbM3032636@fido.openend.se>
Message-ID: <20151204010346.GA11157@cskk.homeip.net>

On 01Dec2015 11:31, Laura Creighton <lac at openend.se> wrote:
>He may be looking for something like the logging facility of Gnu screen.

Or the venerable "script" command. But I suspect he wants something else.

Cheers,
Cameron Simpson <cs at zip.com.au>

The worst tyrannies were the ones where a governance required its own logic on
every embedded node. - Vernor Vinge

From deepaknedumpilly at gmail.com  Sat Dec  5 13:48:46 2015
From: deepaknedumpilly at gmail.com (Deepak Nn)
Date: Sun, 6 Dec 2015 00:18:46 +0530
Subject: [Tutor] Please sent me the output of this code .Please include both
 cases if input correct and if input wrong .
Message-ID: <CAGSR2fG7sF7GsypDnER3UK9XAOW+__Qhn22Y4Jd+B6qQT21ENg@mail.gmail.com>

# Embedded file name: re4.py
import time
flag = [102,
 108,
 97,
 103,
 123,
 112,
 121,
 116,
 104,
 111,
 110,
 95,
 114,
 111,
 99,
 107,
 115,
 125]
password = raw_input('Enter secret code to get secret password: ')
sleep_hours = 10000
print 'Going to sleep. Will check password after %d hours' % sleep_hours
print 'If you want to check password faster, find a way to prevent this
sleep'
time.sleep(sleep_hours * 60 * 60)
if password == 'strongpassword':
    print 'Correct! The secret password is %s' % ''.join(map(chr, flag))
else:
    print 'Booo wrong code! No secret password for you'

From marc_eymard at hotmail.com  Sat Dec  5 08:21:19 2015
From: marc_eymard at hotmail.com (Marc Eymard)
Date: Sat, 5 Dec 2015 13:21:19 +0000
Subject: [Tutor] Beginner: Socket object and packets
Message-ID: <BLU436-SMTP9943795C34F1D0E4AD3F4A8B0B0@phx.gbl>

Hi tutor,

I am trying to locate the first blank line in the first received packet 
when pinging an internet server using a socket object.

My assumption is there will be a mandatory blank line right after the 
http headers in accordance with the http protocol.

Consider the following:

import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect( ('www.py4inf.com/code/', 80) )
mysock.send('GET http://www.py4inf.com/code/' + ' HTTP/1.0\n\n')
data_str = mysock.recv(700)

My question:

Why is the following statement False when there is an actual blank line 
in the received packet:
     '\n\n' in data

The statement 'any_string in data' works fine with any character except 
the double line drop i.e. '\n\n'.

Attached full script for your consideration.

Thanks in advance for your guidance,
Marc



From alan.gauld at btinternet.com  Sat Dec  5 17:47:36 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 5 Dec 2015 22:47:36 +0000
Subject: [Tutor] Please sent me the output of this code .Please include
 both cases if input correct and if input wrong .
In-Reply-To: <CAGSR2fG7sF7GsypDnER3UK9XAOW+__Qhn22Y4Jd+B6qQT21ENg@mail.gmail.com>
References: <CAGSR2fG7sF7GsypDnER3UK9XAOW+__Qhn22Y4Jd+B6qQT21ENg@mail.gmail.com>
Message-ID: <n3vpi8$j6v$1@ger.gmane.org>

On 05/12/15 18:48, Deepak Nn wrote:
> # Embedded file name: re4.py

If you want to know the output run it.
If the output you get is not what you expect tell us what you input,
what you got out, what you expec6ed.
Also tell us which OS and Python versions you are using.

Otherwise all I can tell you is that the output will be some combination
of the various print statements depending on
what input you provide(assuming there are no code errors).

> import time
> flag = [102,
>  108,
>  97,
>  103,
>  123,
>  112,
>  121,
>  116,
>  104,
>  111,
>  110,
>  95,
>  114,
>  111,
>  99,
>  107,
>  115,
>  125]
> password = raw_input('Enter secret code to get secret password: ')
> sleep_hours = 10000
> print 'Going to sleep. Will check password after %d hours' % sleep_hours
> print 'If you want to check password faster, find a way to prevent this
> sleep'
> time.sleep(sleep_hours * 60 * 60)
> if password == 'strongpassword':
>     print 'Correct! The secret password is %s' % ''.join(map(chr, flag))
> else:
>     print 'Booo wrong code! No secret password for you'

I suspect the question you really want to ask is about how the map()
function works? It will apply the chr() function to each number in flags.

>>> chr(102),chr(108),chr(97)
('f', 'l', 'a')

And so on.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at btinternet.com  Sat Dec  5 17:56:21 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 5 Dec 2015 22:56:21 +0000
Subject: [Tutor] Beginner: Socket object and packets
In-Reply-To: <BLU436-SMTP9943795C34F1D0E4AD3F4A8B0B0@phx.gbl>
References: <BLU436-SMTP9943795C34F1D0E4AD3F4A8B0B0@phx.gbl>
Message-ID: <n3vq2l$rda$1@ger.gmane.org>

On 05/12/15 13:21, Marc Eymard wrote:
> Hi tutor,
> 
> I am trying to locate the first blank line in the first received packet 
> when pinging an internet server using a socket object.

You need to be careful with your descriptions. ping is a very
specific message and uses ICMP echo rather than TCP/IP and looks
nothing like http. In another context it would be OK but when
dealing with sockets you need to be precise about what you are
actually sending.

> My assumption is there will be a mandatory blank line right after the 
> http headers in accordance with the http protocol.
> 
> Consider the following:
> 
> import socket
> mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> mysock.connect( ('www.py4inf.com/code/', 80) )
> mysock.send('GET http://www.py4inf.com/code/' + ' HTTP/1.0\n\n')
> data_str = mysock.recv(700)


Is there any reason why you are using raw sockets rather than
the httplib module which does most of this stuff for you
(and probably has useful code you code study if you do want
to do it this way)?

> My question:
> 
> Why is the following statement False when there is an actual blank line 
> in the received packet:
>      '\n\n' in data

It looks like you are using Python v3. Remember that most
system level IO in v3 uses bytes not strings. You probably
need to convert the bytes to a string before looking for
blank lines. But that's just a guess.

Also did you try using find() or index() rather than in?

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From cs at zip.com.au  Sat Dec  5 20:47:15 2015
From: cs at zip.com.au (Cameron Simpson)
Date: Sun, 6 Dec 2015 12:47:15 +1100
Subject: [Tutor] Beginner: Socket object and packets
In-Reply-To: <BLU436-SMTP9943795C34F1D0E4AD3F4A8B0B0@phx.gbl>
References: <BLU436-SMTP9943795C34F1D0E4AD3F4A8B0B0@phx.gbl>
Message-ID: <20151206014715.GA9609@cskk.homeip.net>

On 05Dec2015 13:21, Marc Eymard <marc_eymard at hotmail.com> wrote:
>Hi tutor,
>I am trying to locate the first blank line in the first received packet when 
>pinging an internet server using a socket object.

First up: everything ALan already said.

Next:

Note that the HTTP response need not all be in a single packet, though that is 
not your problem.

>My assumption is there will be a mandatory blank line right after the 
>http headers in accordance with the http protocol.

There certainly should be.

>Consider the following:
>import socket
>mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>mysock.connect( ('www.py4inf.com/code/', 80) )
>mysock.send('GET http://www.py4inf.com/code/' + ' HTTP/1.0\n\n')
>data_str = mysock.recv(700)
>
>My question:
>
>Why is the following statement False when there is an actual blank 
>line in the received packet:
>    '\n\n' in data

1: You will be getting bytes backup from the server (obviously so in Python 3 
and implicitly in Python 2).

2: The HTTP protocol, like most internet text protocols, ends lines with the 
bytes '\r\n', not just '\n'.

Therefore you should expect the bytes '\r\n\r\n' in the response data.

However, you should have discovered this already by doing some debugging. Since 
you're clearly not getting the response you expected, the very first step on 
your part should be to print our the received data, for example by adding:

  print(repr(data_str))

after your recv() call. Then you could inspect the received data and probably 
have seen the '\r' characters.

Cheers,
Cameron Simpson <cs at zip.com.au>

From huyuehua1106 at sina.com  Mon Dec  7 08:12:04 2015
From: huyuehua1106 at sina.com (Yuehua HU)
Date: Mon, 7 Dec 2015 21:12:04 +0800
Subject: [Tutor] Tkinter_Entry_tip words
Message-ID: <61F8D0F9-17E0-49E3-8243-22979AB12A9D@sina.com>


Hi,

I want to realise the function below use python, but can?t find the right way.

Function description:
User input strings in Entry(Tkinter) widget, there are tip words displayed in this Entry widget, 
when the Entry widget is selected, the tip words are faded,
when user begin to entering words into this Entry, the tip words are disappeared.

Does anybody know the method to implement it with Entry and Label widget? Or any other method in python?

Thank you.

Best Regards,
Yuehua

From alan.gauld at btinternet.com  Mon Dec  7 09:23:04 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 7 Dec 2015 14:23:04 +0000
Subject: [Tutor] Tkinter_Entry_tip words
In-Reply-To: <61F8D0F9-17E0-49E3-8243-22979AB12A9D@sina.com>
References: <61F8D0F9-17E0-49E3-8243-22979AB12A9D@sina.com>
Message-ID: <n444o8$8ja$1@ger.gmane.org>

On 07/12/15 13:12, Yuehua HU wrote:

> Function description:
> User input strings in Entry(Tkinter) widget, there are tip words displayed in this Entry widget, 
> when the Entry widget is selected, the tip words are faded,
> when user begin to entering words into this Entry, the tip words are disappeared.
> 
> Does anybody know the method to implement it with Entry and Label widget? Or any other method in python?

I'm hoping this is not a homework...

Try something like this for Python 2:

######################
import Tkinter as tk

top = tk.Tk()
e = tk.Entry(top)
e.pack()

def greyText(ev):
   e.config(foreground='grey')

def startEntry(ev):
   e.delete(0,tk.END)
   e.config(foreground='black')
   e.unbind('<Key>')

e.insert(tk.END,"Help text")

e.bind('<ButtonRelease-1>', greyText)
e.bind('<Key>', startEntry)

top.mainloop()
##########################

You'll need some tweaks to cater for the user changing
their mind and just blanking the field. In that case you
probably need to reinstate the hint and the key binding.
I leave that as an exercise...

By coincidence I was doing something very similar
to this yesterday! :-)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From wiseilesha at gmail.com  Tue Dec  8 02:39:41 2015
From: wiseilesha at gmail.com (Ilesha Wise)
Date: Tue, 8 Dec 2015 02:39:41 -0500
Subject: [Tutor] Image MAnipulation Help
Message-ID: <CAD=BxKg_CUV7+jSPNL0PCBOavf=fCKDdUR4ev7=ywJFUOxGJ=w@mail.gmail.com>

Hello, I wasnt sure if this is the email address I should be sending this
to.

I really need help creating codes that will do the following:

? Scanned photos and slides often have dust specs, water marks, scratches
etc. Automate their removal as much as possible and/or provide a simple way
for the viewer to direct the program as to where to make corrections.
 ? Images often have a high contrast (bright sky, dark horizon). Help the
image by making the sky more blue (with any detectable clouds, birds, etc.
remaining) and improve the contrast of the other portion of the image.

Additional grading basis:

? The user interface for solving these issues.
 ? A decent (note, not perfect) improvement in the images.
? Your management of color, averaging, etc.


Thank you.

From alan.gauld at btinternet.com  Tue Dec  8 05:40:07 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 8 Dec 2015 10:40:07 +0000
Subject: [Tutor] Image MAnipulation Help
In-Reply-To: <CAD=BxKg_CUV7+jSPNL0PCBOavf=fCKDdUR4ev7=ywJFUOxGJ=w@mail.gmail.com>
References: <CAD=BxKg_CUV7+jSPNL0PCBOavf=fCKDdUR4ev7=ywJFUOxGJ=w@mail.gmail.com>
Message-ID: <n46c27$3fu$1@ger.gmane.org>

On 08/12/15 07:39, Ilesha Wise wrote:
> Hello, I wasnt sure if this is the email address I should be sending this
> to.

Its a fair starting point but you will probably get more detailed
answers on the PIL/PILLOW forums since those are the packages
you will likely be using for this kind of work. (Pillow is
for v2/v3, The original PIL for v2 only.)

There are some image manipulation packages in the SciPy/Kit bundles too.

And of course the venerable ImageMagick modules may help too.

Finally the psd-tools package will be useful if you are using
Photoshop files.

> ? Scanned photos and slides often have dust specs, water marks, scratches
> etc. Automate their removal as much as possible and/or provide a simple way
> for the viewer to direct the program as to where to make corrections.
>  ? Images often have a high contrast (bright sky, dark horizon). Help the
> image by making the sky more blue (with any detectable clouds, birds, etc.
> remaining) and improve the contrast of the other portion of the image.

I assume you already have a graphics background and know the theory
behind doing all this? ie You are not just a raw beginner?
If so then the libraries mentioned above should get you started.

> Additional grading basis:
> 
> ? The user interface for solving these issues.

Pick a UI framework (there are many) and build it.

>  ? A decent (note, not perfect) improvement in the images.
> ? Your management of color, averaging, etc.

You are pretty much on your own for these I suspect
("decent improvement" is of course entirely subjective)

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From lac at openend.se  Tue Dec  8 06:24:09 2015
From: lac at openend.se (Laura Creighton)
Date: Tue, 08 Dec 2015 12:24:09 +0100
Subject: [Tutor] Image MAnipulation Help
In-Reply-To: <CAD=BxKg_CUV7+jSPNL0PCBOavf=fCKDdUR4ev7=ywJFUOxGJ=w@mail.gmail.com>
References: <CAD=BxKg_CUV7+jSPNL0PCBOavf=fCKDdUR4ev7=ywJFUOxGJ=w@mail.gmail.com>
Message-ID: <201512081124.tB8BO9nc019665@fido.openend.se>

In a message of Tue, 08 Dec 2015 02:39:41 -0500, Ilesha Wise writes:
>Hello, I wasnt sure if this is the email address I should be sending this
>to.
>
>I really need help creating codes that will do the following:
>
>? Scanned photos and slides often have dust specs, water marks, scratches
>etc. Automate their removal as much as possible and/or provide a simple way
>for the viewer to direct the program as to where to make corrections.
> ? Images often have a high contrast (bright sky, dark horizon). Help the
>image by making the sky more blue (with any detectable clouds, birds, etc.
>remaining) and improve the contrast of the other portion of the image.
>
>Additional grading basis:
>
>? The user interface for solving these issues.
> ? A decent (note, not perfect) improvement in the images.
>? Your management of color, averaging, etc.
>
>
>Thank you.
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>To unsubscribe or change subscription options:
>https://mail.python.org/mailman/listinfo/tutor

You can do this with the GIMP.
http://howto.nicubunu.ro/gimp-remove-watermark/
(actually searching for "GIMP remove watermark" gets you lots of
hits.)  It is possible to script the GIMP using python, so you could
automate some of this.  Warning, scripting the GIMP is not a pleasant
task, and the python code they use is decidedly weird in places.
But it can be done.

Laura

From alan.gauld at btinternet.com  Tue Dec  8 07:54:21 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 8 Dec 2015 12:54:21 +0000
Subject: [Tutor] Image MAnipulation Help
In-Reply-To: <201512081124.tB8BO9nc019665@fido.openend.se>
References: <CAD=BxKg_CUV7+jSPNL0PCBOavf=fCKDdUR4ev7=ywJFUOxGJ=w@mail.gmail.com>
 <201512081124.tB8BO9nc019665@fido.openend.se>
Message-ID: <n46jtt$31f$1@ger.gmane.org>

On 08/12/15 11:24, Laura Creighton wrote:

> You can do this with the GIMP.
> http://howto.nicubunu.ro/gimp-remove-watermark/
> (actually searching for "GIMP remove watermark" gets you lots of
> hits.)  

But removing watermarks could get you in lots of legal trouble.
The whole point of watermarks is normally to stop you using
a commercial image that you should be paying for. Make sure
you are not breaking copyright before you start.

However, you do say 'water marks' (with a space), which is a
different thing entirely and the GIMP could be used for that.

> It is possible to script the GIMP using python, so you could
> automate some of this.  Warning, scripting the GIMP is not a pleasant

An understatement IMHO!
But that's more to do with scripting GIMP in general than
with the Python scripting implementation.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From huyuehua1106 at sina.com  Tue Dec  8 10:08:44 2015
From: huyuehua1106 at sina.com (Yuehua HU)
Date: Tue, 8 Dec 2015 23:08:44 +0800
Subject: [Tutor] Tkinter_Entry_tip words
In-Reply-To: <n444o8$8ja$1@ger.gmane.org>
References: <61F8D0F9-17E0-49E3-8243-22979AB12A9D@sina.com>
 <n444o8$8ja$1@ger.gmane.org>
Message-ID: <6B9F776A-4DA3-43D5-B313-1A8A077FBB90@sina.com>


Hi Alan,

Thank you for your answer, it is really helpful.
and it is not a homework :)

I?ve tried to write 'user changing their mind and blanking the field? case, but it seems not working?
Did I use '<KeyPress-Delete>? wrong?
and another question: Why should we use a parameter in the function 'greyText(e)? ? Here the parameter is ?e?.

#######################
import Tkinter

def checkEnterStrLen(e):
    if len(var.get())==0:
        entry.config(fg= 'grey')
        entry.insert(0, 'help text')

def greyText(e):
    entry.config(fg = 'grey')

def startEntry(e):
    entry.delete(0,Tkinter.END)
    entry.config(fg = 'black')
    entry.unbind('<Key>')

top = Tkinter.Tk()

var = Tkinter.StringVar()
entry = Tkinter.Entry(top, textvariable = var)
entry.insert(0,'help text')

entry.bind('<Button-1>', greyText)
entry.bind('<KeyPress-Delete>',checkEnterStrLen)
entry.bind('<Key>',startEntry)

entry.pack()

top.mainloop()
#######################

Thank you.

B.R.
Yuehua


> On Dec 7, 2015, at 22:23, Alan Gauld <alan.gauld at btinternet.com> wrote:
> 
> 
> On 07/12/15 13:12, Yuehua HU wrote:
> 
>> Function description:
>> User input strings in Entry(Tkinter) widget, there are tip words displayed in this Entry widget, 
>> when the Entry widget is selected, the tip words are faded,
>> when user begin to entering words into this Entry, the tip words are disappeared.
>> 
>> Does anybody know the method to implement it with Entry and Label widget? Or any other method in python?
> 
> I'm hoping this is not a homework...
> 
> Try something like this for Python 2:
> 
> ######################
> import Tkinter as tk
> 
> top = tk.Tk()
> e = tk.Entry(top)
> e.pack()
> 
> def greyText(ev):
>   e.config(foreground='grey')
> 
> def startEntry(ev):
>   e.delete(0,tk.END)
>   e.config(foreground='black')
>   e.unbind('<Key>')
> 
> e.insert(tk.END,"Help text")
> 
> e.bind('<ButtonRelease-1>', greyText)
> e.bind('<Key>', startEntry)
> 
> top.mainloop()
> ##########################
> 
> You'll need some tweaks to cater for the user changing
> their mind and just blanking the field. In that case you
> probably need to reinstate the hint and the key binding.
> I leave that as an exercise...
> 
> By coincidence I was doing something very similar
> to this yesterday! :-)
> 
> -- 
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
> 
> 



From alan.gauld at btinternet.com  Tue Dec  8 14:54:32 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 8 Dec 2015 19:54:32 +0000
Subject: [Tutor] Tkinter_Entry_tip words
In-Reply-To: <6B9F776A-4DA3-43D5-B313-1A8A077FBB90@sina.com>
References: <61F8D0F9-17E0-49E3-8243-22979AB12A9D@sina.com>
 <n444o8$8ja$1@ger.gmane.org> <6B9F776A-4DA3-43D5-B313-1A8A077FBB90@sina.com>
Message-ID: <n47chn$g3r$1@ger.gmane.org>

On 08/12/15 15:08, Yuehua HU wrote:

> I?ve tried to write 'user changing their mind and blanking the field? case, but it seems not working?
> Did I use '<KeyPress-Delete>? wrong?

Delete is the key that deletes the character to the right of cursor.
Did you maybe mean to use <'Keypress-BackSpace'>? Or even both of them?

> ...Why should we use a parameter in the function 'greyText(e)? ? 

Because the bind mechanism passes the event object as an argument
and expects the function to accept it even if its not used.
[Aside: This is annoying since the command attribute of widgets expects
a function with no arguments! To get round that set a default value of None:

def aCallBack(event=None):...

then you can use aCallBack() in either scenario.
]

HTH

> #######################
> import Tkinter
> 
> def checkEnterStrLen(e):
>     if len(var.get())==0:
>         entry.config(fg= 'grey')
>         entry.insert(0, 'help text')
> 
> def greyText(e):
>     entry.config(fg = 'grey')
> 
> def startEntry(e):
>     entry.delete(0,Tkinter.END)
>     entry.config(fg = 'black')
>     entry.unbind('<Key>')
> 
> top = Tkinter.Tk()
> 
> var = Tkinter.StringVar()
> entry = Tkinter.Entry(top, textvariable = var)
> entry.insert(0,'help text')
> 
> entry.bind('<Button-1>', greyText)
> entry.bind('<KeyPress-Delete>',checkEnterStrLen)
> entry.bind('<Key>',startEntry)
> 
> entry.pack()
> 
> top.mainloop()

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From crusier at gmail.com  Tue Dec  8 21:01:59 2015
From: crusier at gmail.com (Crusier)
Date: Wed, 9 Dec 2015 10:01:59 +0800
Subject: [Tutor] Beautifulsoup Queries
Message-ID: <CAC7HCj-kCk+KeO-iHYs1k3a+VpuY5yz5aPZuuk5PLFPm24assQ@mail.gmail.com>

Dear All,

I am using Python 3.4, I tried to scrap the web and eventually put
those data into a database for analysis. While I am using
Beautifulsoup to scrap the web, I encountered 2 problems:

1. Using Beautiful Soup, the webmaster on the other end is using the
same class, so I got a whole list of information (High, Low Previous
Close, Shares Traded, Turnover.....etc) and I really want to divide
that up into separate categories.

2. If I input  " print(data.string) " for line 27, I will get an error
('ResultSet' object has no attribute 'string'). However, if I input  "
print(data) ", they print out in span class..... etc...

from bs4 import BeautifulSoup
import requests
import os


tryout = ['0001', '0002', '0003', '0004', '0005', '0006', '0007',
'0008', '0009', '0010', '0011', '0012', '0014', '0015', '0016',
'0017', '0018', '0019', '0020']

url = "https://www.etnet.com.hk/www/eng/stocks/realtime/quote.php?code="



def web_scraper(url):
    for n in tryout:
        URL = url + n
        response = requests.get(URL)
        html = response.content
        soup = BeautifulSoup(html,"html.parser")
        # print (soup.prettify())

        Title = soup.find("div", attrs = {"id": "StkQuoteHeader"})
        RT_down = soup.find("span", attrs = {"class": "Price down2"})
        RT_up = soup.find("span", attrs = {"class": "Price up2"})
        RT_unchange =  soup.find("span",attrs = {"class" :"Price unchange2"})
        change_percent = soup.find("span", attrs = {"class" :"Change"})
        Day_High = soup.findAll("span", attrs = {"class" :"Number"})
        for data in [Title, RT_down, RT_up, RT_unchange,
change_percent, Day_High]:
            if data:
                print(data)


web_scraper(url)

From huyuehua1106 at sina.com  Wed Dec  9 06:03:54 2015
From: huyuehua1106 at sina.com (Yuehua HU)
Date: Wed, 9 Dec 2015 19:03:54 +0800
Subject: [Tutor] Tkinter_Entry_tip words
In-Reply-To: <n47chn$g3r$1@ger.gmane.org>
References: <61F8D0F9-17E0-49E3-8243-22979AB12A9D@sina.com>
 <n444o8$8ja$1@ger.gmane.org> <6B9F776A-4DA3-43D5-B313-1A8A077FBB90@sina.com>
 <n47chn$g3r$1@ger.gmane.org>
Message-ID: <B294E5A2-72CE-426C-9627-38D39287B2C8@sina.com>


Hi Alan,

it works using ?BackSpace? and ?Delete?!
There is no ?BackSpace? key on Mac, so I didn?t come up with this key before, thanks for your advise and answer :)

B.R.
Yuehua


> On Dec 9, 2015, at 03:54, Alan Gauld <alan.gauld at btinternet.com> wrote:
> 
> On 08/12/15 15:08, Yuehua HU wrote:
> 
>> I?ve tried to write 'user changing their mind and blanking the field? case, but it seems not working?
>> Did I use '<KeyPress-Delete>? wrong?
> 
> Delete is the key that deletes the character to the right of cursor.
> Did you maybe mean to use <'Keypress-BackSpace'>? Or even both of them?
> 
>> ...Why should we use a parameter in the function 'greyText(e)? ? 
> 
> Because the bind mechanism passes the event object as an argument
> and expects the function to accept it even if its not used.
> [Aside: This is annoying since the command attribute of widgets expects
> a function with no arguments! To get round that set a default value of None:
> 
> def aCallBack(event=None):...
> 
> then you can use aCallBack() in either scenario.
> ]
> 
> HTH
> 
>> #######################
>> import Tkinter
>> 
>> def checkEnterStrLen(e):
>>    if len(var.get())==0:
>>        entry.config(fg= 'grey')
>>        entry.insert(0, 'help text')
>> 
>> def greyText(e):
>>    entry.config(fg = 'grey')
>> 
>> def startEntry(e):
>>    entry.delete(0,Tkinter.END)
>>    entry.config(fg = 'black')
>>    entry.unbind('<Key>')
>> 
>> top = Tkinter.Tk()
>> 
>> var = Tkinter.StringVar()
>> entry = Tkinter.Entry(top, textvariable = var)
>> entry.insert(0,'help text')
>> 
>> entry.bind('<Button-1>', greyText)
>> entry.bind('<KeyPress-Delete>',checkEnterStrLen)
>> entry.bind('<Key>',startEntry)
>> 
>> entry.pack()
>> 
>> top.mainloop()
> 
> -- 
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor



From s.charonis at gmail.com  Thu Dec 10 07:38:46 2015
From: s.charonis at gmail.com (Spyros Charonis)
Date: Thu, 10 Dec 2015 12:38:46 +0000
Subject: [Tutor] Understanding a linear runtime implementation of anagram
 detection
Message-ID: <CADe=Ya8NTU-G-fivFJEd2u5WDQH-sXUEDiWTRdDOsHkKi=T2vw@mail.gmail.com>

Dear All,

I am learning about analysis of algorithms (python 2.7.6). I am reading a
book (Problem solving with Algorithms and Data Structures) where Python is
the language used for implementations. The author introduces algorithm
analysis in a clear and understandable way, and uses an anagram detection
program as a template to compare different runtime implementations
(quadratic, log linear, linear). In the linear, and most efficient
implementation, the code is as follows (comments added by me):

def anagram_test2(s1,s2):""" Checks if two strings are anagrams of each other
    Runs with O(n) linear complexity """
if (not s1) or (not s2):
    raise TypeError, "Invalid input: input must be string"
    return None
# Initialize two lists of counters
c1 = [0] * 26
c2 = [0] * 26
# Iterate over each string# When a char is encountered, # increment
the counter at # its correspoding position   for i in range(len(s1)):
    pos = ord(s1[i]) - ord("a")
    c1[pos] += 1
for i in range(len(s2)):
    pos = ord(s2[i]) - ord("a")
    c2[pos] += 1

j = 0
hit = Truewhile j < 26 and hit:
    if c1[j] == c2[j]:
        j += 1
    else:
        hit = False
return hit


My questions are:

1)
Is it computationally more/less/equally efficient to use an explicit while
loop as it is to just do "return c1 === c2" (replacing the final code block
following the two for loops). I realize that this single line of code
performs an implicit for loop over each index to test for equality. My
guess is that because in other languages you may not be able to do this
simple test, the author wanted to present an example that could be adapted
for other languages, unless the explicit while loop is less expensive
computationally.

2)
How could I go about adapting this algorithm for multiple strings (say I
had 20 strings and wanted to check if they are anagrams of one another).

    def are_anagrams(*args):

    """ Accepts a tuple of strings and checks if

         they are anagrams of each other """


     # Check that neither of strings are null

     for i in args:

     if not i:

         raise TypeError, "Invalid input"

         return None



     # Initialize a list of counters for each string

     c = ( [] for i in range(len(args) ) ???

Many thanks in advance!

From __peter__ at web.de  Thu Dec 10 08:45:13 2015
From: __peter__ at web.de (Peter Otten)
Date: Thu, 10 Dec 2015 14:45:13 +0100
Subject: [Tutor] Understanding a linear runtime implementation of
 anagram detection
References: <CADe=Ya8NTU-G-fivFJEd2u5WDQH-sXUEDiWTRdDOsHkKi=T2vw@mail.gmail.com>
Message-ID: <n4bvla$ffh$1@ger.gmane.org>

Spyros Charonis wrote:

> Dear All,
> 
> I am learning about analysis of algorithms (python 2.7.6). I am reading a
> book (Problem solving with Algorithms and Data Structures) where Python is
> the language used for implementations. The author introduces algorithm
> analysis in a clear and understandable way, and uses an anagram detection
> program as a template to compare different runtime implementations
> (quadratic, log linear, linear). In the linear, and most efficient
> implementation, the code is as follows (comments added by me):
> 
> def anagram_test2(s1,s2):""" Checks if two strings are anagrams of each
> other
>     Runs with O(n) linear complexity """
> if (not s1) or (not s2):
>     raise TypeError, "Invalid input: input must be string"
>     return None
> # Initialize two lists of counters
> c1 = [0] * 26
> c2 = [0] * 26
> # Iterate over each string# When a char is encountered, # increment
> the counter at # its correspoding position   for i in range(len(s1)):
>     pos = ord(s1[i]) - ord("a")
>     c1[pos] += 1
> for i in range(len(s2)):
>     pos = ord(s2[i]) - ord("a")
>     c2[pos] += 1
> 
> j = 0
> hit = Truewhile j < 26 and hit:
>     if c1[j] == c2[j]:
>         j += 1
>     else:
>         hit = False
> return hit

The code above will make any Python programmer who is past the absolute 
beginner level cry. Here's a somewhat cleaned-up version:

OFFSET = ord("a")

def anagram_test3(s1, s2):
    if len(s1) != len(s2):
           return False
    freq1 = [0] * 26
    for c in s1:
        freq1[ord(c) - OFFSET] += 1
    freq2 = [0] * 26
    for c in s2:
        freq2[ord(c) - OFFSET] += 1
    return freq1 == freq2

When you look a the code you see that almost that the same code appears 
twice. Let's move it into a separate function:

OFFSET = ord("a")

def freq(s):
    freq_table = [0] * 26
    for c in s:
        freq_table[ord(c) - OFFSET] += 1
    return freq_table

def anagram_test3(s, t):
    if len(s) != len(t):
           return False
    return freq(s) == freq(t)

> My questions are:
> 
> 1)
> Is it computationally more/less/equally efficient to use an explicit while
> loop as it is to just do "return c1 === c2" (replacing the final code
> block following the two for loops). I realize that this single line of
> code performs an implicit for loop over each index to test for equality.
> My guess is that because in other languages you may not be able to do this
> simple test, the author wanted to present an example that could be adapted
> for other languages, unless the explicit while loop is less expensive
> computationally.

Yes, while the simple c1 == c2 has the same complexity it should be 
significantly faster than the loop. The equality check is also easy to read 
and understand. 
 
> 2)
> How could I go about adapting this algorithm for multiple strings (say I
> had 20 strings and wanted to check if they are anagrams of one another).

With the above freq() function you can calculate the frequency table for the 
first string and then loop over the rest and stop when you encounter one 
that produces a different frequency table.

Somewhat more involved: You might calculate frequency tables for every 
string and then collect them in a dict. For that to work you have to convert 
the lists into something hashable -- a tuple will be the obvious choice. The 
final table will look like this

{
(1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 
0): ['jeans'], 
(1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 
0): ['stingray', 'straying'], 
(1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 
0): ['parleys', 'parsley', 'players', 'replays', 'sparely']}

and to find the anagrams you have to pick the lists containing more than one 
word.



From jcgallaher78 at gmail.com  Sat Dec 12 02:03:05 2015
From: jcgallaher78 at gmail.com (Jim Gallaher)
Date: Sat, 12 Dec 2015 01:03:05 -0600
Subject: [Tutor] Calculation error with a simple program
Message-ID: <566BC6A9.6090206@gmail.com>

Hi everyone. I'm reading through a beginners Python book and came up 
with a super simple program. I'm not getting any errors and everything 
runs through, but there's a logical calculation error. What the program 
does is take an amount and calculate a couple percentages and add a 
couple fees.

For example, if I put in a value of 1, it will output 752.12 as the sub 
total and 753.12 as the grand total. It's off by 1 on sub total and 2 on 
grand total.

Thanks in advance! Jim Gallaher

# Car Salesman Calculator

# User enters the base price of the car and the program adds tax, 
license, dealer prep, and destination charge.

print("Car Sales Calculator")
basePrice = int(input("Please enter in the price of the car: "))

# Misc charges to be added to the total cost of the car
tax = basePrice * .07
license = basePrice * .05
dealerPrep = basePrice + 500
destinationCharge = basePrice + 250

# Add the total misc charges together
subTotal = float(tax + license + dealerPrep + destinationCharge)

# Add all the misic charges and include the base price
grandTotal = float(subTotal + basePrice)

# Display the results
print("\nThe sub total is", subTotal)
print("\nYour grand Total is", grandTotal)

input("\nPress the enter key to close the program.")

From alan.gauld at btinternet.com  Sat Dec 12 03:04:52 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 12 Dec 2015 08:04:52 +0000
Subject: [Tutor] Calculation error with a simple program
In-Reply-To: <566BC6A9.6090206@gmail.com>
References: <566BC6A9.6090206@gmail.com>
Message-ID: <n4gkf4$e99$1@ger.gmane.org>

On 12/12/15 07:03, Jim Gallaher wrote:

> For example, if I put in a value of 1, it will output 752.12 as the sub 
> total and 753.12 as the grand total. It's off by 1 on sub total and 2 on 
> grand total.

Are you sure? Lets check the values...

> basePrice = int(input("Please enter in the price of the car: "))

=> 1

> tax = basePrice * .07

=> 0.07

> license = basePrice * .05

=> 0.05
> dealerPrep = basePrice + 500

=> 501

> destinationCharge = basePrice + 250

=> 251

> # Add the total misc charges together
> subTotal = float(tax + license + dealerPrep + destinationCharge)

=> 0.07 + 0.05 + 501 + 251 => 752.12

> # Add all the misic charges and include the base price
> grandTotal = float(subTotal + basePrice)

=> 752.12 + 1 => 753.12

Looks like Python got it right to me?


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From lac at openend.se  Sat Dec 12 10:07:10 2015
From: lac at openend.se (Laura Creighton)
Date: Sat, 12 Dec 2015 16:07:10 +0100
Subject: [Tutor] Calculation error with a simple program
In-Reply-To: <566BC6A9.6090206@gmail.com>
References: <566BC6A9.6090206@gmail.com>
Message-ID: <201512121507.tBCF7AIh011747@fido.openend.se>

I haven't verified this, but you are probably up against some
problem caused by using floating point to store money.

The problem is that, when people see something like the floating
point number, 3.15 they think, aha, this is a decimal number just
like I learned in school when I was 10 years old.  This is 3 plus
one-tenth, plus 5 one hundreths. exactly.  I know everything about this
sort of thing, I learned it when I was 10.

In particular, you probably learned this properly of numbers in
general.

(a + b) + c  = a + (b + c)  (associative properly of addition)

And while you probably had not thought about this property, you
definitely exepected it to work with your 3.15 when you want to add
it to 2.17

And, herein lies the rub.
floating point numbers, despite looking exactly the same as what you
learned in school (A terrible design decision, I think that if we
wrote them 3_15 or 3#15 we would have many fewer problems now, but
it got made before I was born, so .... ) ARE NOT the things you
learned in school.

Not all decimal numbers are exactly representable in floating point.
As a result the law of association fails.  The correct result can 
indeed depend on the order in which you do your operations.

You can read more about this here:
https://docs.python.org/3.5/faq/design.html#why-are-floating-point-calculations-so-inaccurate

and in the tutorial:

https://docs.python.org/3.5/tutorial/floatingpoint.html#tut-fp-issues

This is also good.
http://floating-point-gui.de/

And if you want a more serious, mathematical approach, this ACM reprint is
_really good_, but not to everybody's taste.
https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

Most of the time, this does not matter, because most of the people
using floating point are scientists.  Scientists, contrary to popular
belief, are not all that concerned with exact accuracy.  Their results
always come with an error estimate.  'the distance is such and such 
+/- 10%' or +/- 0.005%  or what have you.  So, as long as you do
your calculations in such a way that the floating point error is
covered in the % of uncertainty that you have anyway, your answer
is perfectly correct enough for science.

And floating calculations are much, much faster than fixed point
decimal calculations, which in the old days meant the difference
between getting a result for your calculations in a week or in
more than a month.  No wonder the scientists were happy to trade
accuracy which they couldn't use for speed, which they had immediate
need for.

But once you get to calculations with money, you are suddenly out of
the realm of science.  (Even if some economists might want to tell
you different. :) )  Money is exact.   Nobody is willing to accept
10 pounds +/- 10% for a pizza, and allow people to pay anything between
9 pounds and 11 pounds as an ok price.

In python we have a fix for this, called the Decimal object.
Decimals behave the way you want them to -- i.e. the principle of
associaton holds.

https://docs.python.org/3.5/library/decimal.html

So, if you are just noodling around, playing with things, using floats
to store money is ok.  It teaches bad habits, but that battle was 
fought and lost a long time ago.  However, if you want to do something
serious, like keep track of your own financial affairs with python,
***Don't Use Float For Money***.  Please save yourself grief and
use the Decimal type instead.

Laura

From steve at pearwood.info  Sat Dec 12 12:00:25 2015
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 13 Dec 2015 04:00:25 +1100
Subject: [Tutor] Calculation error with a simple program
In-Reply-To: <566BC6A9.6090206@gmail.com>
References: <566BC6A9.6090206@gmail.com>
Message-ID: <20151212170025.GK3821@ando.pearwood.info>

On Sat, Dec 12, 2015 at 01:03:05AM -0600, Jim Gallaher wrote:
> Hi everyone. I'm reading through a beginners Python book and came up 
> with a super simple program. I'm not getting any errors and everything 
> runs through, but there's a logical calculation error. What the program 
> does is take an amount and calculate a couple percentages and add a 
> couple fees.
> 
> For example, if I put in a value of 1, it will output 752.12 as the sub 
> total and 753.12 as the grand total. It's off by 1 on sub total and 2 on 
> grand total.

Check your arithmetic -- with a base price of $1, the sub total is 
$752.12 and the grand total is $753.12, exactly as Python calculates.


But I wonder whether you have made a logic mistake in your code. You 
say:

dealerPrep = basePrice + 500
destinationCharge = basePrice + 250

This means that the car will cost more than TRIPLE the base price. 
Instead of $1, enter a base price of $40,000 and you will see what I 
mean: now the dealer prep is $40500 and the destination charge is 
$40250, which added to the base price gives $120750 (plus tax and 
licence). Surely that's not right, the deal charges more than the cost 
of the car for preparation? I think what you want is:

dealerPrep = 500
destinationCharge = 250



-- 
Steve

From jcgallaher78 at gmail.com  Sat Dec 12 12:34:27 2015
From: jcgallaher78 at gmail.com (Jim Gallaher)
Date: Sat, 12 Dec 2015 11:34:27 -0600
Subject: [Tutor] Calculation error with a simple program
Message-ID: <8774A398-4A0F-41DF-BBD2-941B49A3CC90@gmail.com>

Hi Alan,

I'm 100 percent sure I'm wrong. :-) I verified it when I fixed the mistake. The problem was it was adding in the basePrice and the fixed rates/percentages each time. So I figured it out when Ian said something about that.

Thanks for everyone's help! :-)

From todd_purple at yahoo.com  Sat Dec 12 08:13:23 2015
From: todd_purple at yahoo.com (Todd Purple)
Date: Sat, 12 Dec 2015 08:13:23 -0500
Subject: [Tutor] Calculation error with a simple program
In-Reply-To: <566BC6A9.6090206@gmail.com>
References: <566BC6A9.6090206@gmail.com>
Message-ID: <6EC6D759-3C19-4A6D-8DD7-6EFAE1958CCD@yahoo.com>



> On Dec 12, 2015, at 2:03 AM, Jim Gallaher <jcgallaher78 at gmail.com> wrote:
> 
> Hi everyone. I'm reading through a beginners Python book and came up with a super simple program. I'm not getting any errors and everything runs through, but there's a logical calculation error. What the program does is take an amount and calculate a couple percentages and add a couple fees.
> 
> For example, if I put in a value of 1, it will output 752.12 as the sub total and 753.12 as the grand total. It's off by 1 on sub total and 2 on grand total.
> 
> Thanks in advance! Jim Gallaher
> 
> # Car Salesman Calculator
> 
> # User enters the base price of the car and the program adds tax, license, dealer prep, and destination charge.
> 
> print("Car Sales Calculator")
> basePrice = int(input("Please enter in the price of the car: "))
> 
> # Misc charges to be added to the total cost of the car
> tax = basePrice * .07
> license = basePrice * .05
> dealerPrep = basePrice + 500
> destinationCharge = basePrice + 250
> 

I think your main problem is right here. Why do dealerPrep and destinationCharge include the basePrice in their equation? This will add the basePrice in multiple times. I would simply set it like this:

dealerPrep = 500
destinationCharge = 250

If these charges ever change, you can put in some sort of equation. However, it looks like these are meant to be a flat fee. 

> # Add the total misc charges together
> subTotal = float(tax + license + dealerPrep + destinationCharge)
> 
> # Add all the misic charges and include the base pricem
> grandTotal = float(subTotal + basePrice)
> 
> # Display the results
> print("\nThe sub total is", subTotal)
> print("\nYour grand Total is", grandTotal)
> 
> input("\nPress the enter key to close the program.")
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

From kfh777 at earthlink.net  Sat Dec 12 12:23:32 2015
From: kfh777 at earthlink.net (Ken Hammer)
Date: Sat, 12 Dec 2015 12:23:32 -0500
Subject: [Tutor] Tutor Digest, Vol 142, Issue 10
In-Reply-To: <mailman.13.1449939602.12987.tutor@python.org>
Message-ID: <E1a7ntK-0001EN-U8@elasmtp-mealy.atl.sa.earthlink.net>


I have a more simple-minded solution.  The error appears to occur in testing without revealing the problem by use of $1 base price in the test.  Using $10,000 as the base price in the test reveals absurd numbers.  I think the real problem lies in the inclusion of base price inappropriately, twice as in:

>dealerPrep = basePrice + 500
>destinationCharge = basePrice + 250

"basePrice" has no place in those two lines.  500 and 250 alone express the definition of the challenge.

Ken



In <mailman.13.1449939602.12987.tutor at python.org>, on 12/12/15 
   at 12:00 PM, tutor-request at python.org said:



>Send Tutor mailing list submissions to
>	tutor at python.org

>To subscribe or unsubscribe via the World Wide Web, visit
>	https://mail.python.org/mailman/listinfo/tutor
>or, via email, send a message with subject or body 'help' to
>	tutor-request at python.org

>You can reach the person managing the list at
>	tutor-owner at python.org

>When replying, please edit your Subject line so it is more specific than
>"Re: Contents of Tutor digest..."


>Today's Topics:

>   1. Calculation error with a simple program (Jim Gallaher)
>   2. Re: Calculation error with a simple program (Alan Gauld)
>   3. Re: Calculation error with a simple program (Laura Creighton)


>----------------------------------------------------------------------

>Message: 1
>Date: Sat, 12 Dec 2015 01:03:05 -0600
>From: Jim Gallaher <jcgallaher78 at gmail.com>
>To: tutor at python.org
>Subject: [Tutor] Calculation error with a simple program
>Message-ID: <566BC6A9.6090206 at gmail.com>
>Content-Type: text/plain; charset=utf-8; format=flowed

>Hi everyone. I'm reading through a beginners Python book and came up  with
>a super simple program. I'm not getting any errors and everything  runs
>through, but there's a logical calculation error. What the program  does is
>take an amount and calculate a couple percentages and add a  couple fees.

>For example, if I put in a value of 1, it will output 752.12 as the sub 
>total and 753.12 as the grand total. It's off by 1 on sub total and 2 on 
>grand total.

>Thanks in advance! Jim Gallaher

># Car Salesman Calculator

># User enters the base price of the car and the program adds tax,  license,
>dealer prep, and destination charge.

>print("Car Sales Calculator")
>basePrice = int(input("Please enter in the price of the car: "))

># Misc charges to be added to the total cost of the car
>tax = basePrice * .07
>license = basePrice * .05
>dealerPrep = basePrice + 500
>destinationCharge = basePrice + 250

># Add the total misc charges together
>subTotal = float(tax + license + dealerPrep + destinationCharge)

># Add all the misic charges and include the base price
>grandTotal = float(subTotal + basePrice)

># Display the results
>print("\nThe sub total is", subTotal)
>print("\nYour grand Total is", grandTotal)

>input("\nPress the enter key to close the program.")


>------------------------------

>Message: 2
>Date: Sat, 12 Dec 2015 08:04:52 +0000
>From: Alan Gauld <alan.gauld at btinternet.com>
>To: tutor at python.org
>Subject: Re: [Tutor] Calculation error with a simple program
>Message-ID: <n4gkf4$e99$1 at ger.gmane.org>
>Content-Type: text/plain; charset=utf-8

>On 12/12/15 07:03, Jim Gallaher wrote:

>> For example, if I put in a value of 1, it will output 752.12 as the sub 
>> total and 753.12 as the grand total. It's off by 1 on sub total and 2 on 
>> grand total.

>Are you sure? Lets check the values...

>> basePrice = int(input("Please enter in the price of the car: "))

>=> 1

>> tax = basePrice * .07

>=> 0.07

>> license = basePrice * .05

>=> 0.05
>> dealerPrep = basePrice + 500

>=> 501

>> destinationCharge = basePrice + 250

>=> 251

>> # Add the total misc charges together
>> subTotal = float(tax + license + dealerPrep + destinationCharge)

>=> 0.07 + 0.05 + 501 + 251 => 752.12

>> # Add all the misic charges and include the base price
>> grandTotal = float(subTotal + basePrice)

>=> 752.12 + 1 => 753.12

>Looks like Python got it right to me?




-- 
-----------------------------------------------------------
K.F.Hammer Associates                                         Ken Hammer
management consultations                      Saint Johnsbury, VT  05819
-----------------------------------------------------------


From crusier at gmail.com  Sun Dec 13 02:44:33 2015
From: crusier at gmail.com (Crusier)
Date: Sun, 13 Dec 2015 15:44:33 +0800
Subject: [Tutor] Beautiful Soup
Message-ID: <CAC7HCj_dtvm6tb7S2RrM4ktPwUTbYv+wWHDJ7sdcQqsM8_8kww@mail.gmail.com>

Dear All,

I am trying to scrap the following website, however, I have
encountered some problems. As you can see, I am not really familiar
with regex and I hope you can give me some pointers to how to solve
this problem.

I hope I can download all the transaction data into the database.
However, I need to retrieve it first. The data which I hope to
retrieve it is as follows:

"
15:59:59     A     500     6.790     3,395
15:59:53     B     500     6.780     3,390................

Thank you

Below is my quote:

from bs4 import BeautifulSoup
import requests
import re

url = 'https://bochk.etnet.com.hk/content/bochkweb/eng/quote_transaction_daily_history.php?code=6881&time=F&timeFrom=090000&timeTo=160000&turnover=S&sessionId=44c99b61679e019666f0570db51ad932&volMin=0&turnoverMin=0'

def turnover_detail(url):
    response = requests.get(url)
    html = response.content
    soup = BeautifulSoup(html,"html.parser")
    data = soup.find_all("script")
    for json in data:
        print(json)

turnover_detail(url)

Best Regards,
Henry

From alan.gauld at btinternet.com  Sun Dec 13 04:10:57 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 13 Dec 2015 09:10:57 +0000
Subject: [Tutor] Beautiful Soup
In-Reply-To: <CAC7HCj_dtvm6tb7S2RrM4ktPwUTbYv+wWHDJ7sdcQqsM8_8kww@mail.gmail.com>
References: <CAC7HCj_dtvm6tb7S2RrM4ktPwUTbYv+wWHDJ7sdcQqsM8_8kww@mail.gmail.com>
Message-ID: <n4jcn1$qrm$1@ger.gmane.org>

On 13/12/15 07:44, Crusier wrote:
> Dear All,
> 
> I am trying to scrap the following website, however, I have
> encountered some problems. As you can see, I am not really familiar
> with regex and I hope you can give me some pointers to how to solve
> this problem.

I'm not sure why you mention regex because your script doesn't
use regex. And for html that's a good thing.

> I hope I can download all the transaction data into the database.
> However, I need to retrieve it first. The data which I hope to
> retrieve it is as follows:
> 
> "
> 15:59:59     A     500     6.790     3,395
> 15:59:53     B     500     6.780     3,390................
> 

Part of your problem is that the data is not in html format but
is in fact part of the Javascript code on the page. And
BeautifulSoup is not so good at parsing Javascript.

The page code looks like

<script type="text/javascript"
src="../js/jquery.js?verID=20150826_153700"></script>
<script type="text/javascript"
src="../js/common_eng.js?verID=20150826_153700"></script>
<script type="text/javascript"
src="../js/corsrequest.js?verID=20150826_153700"></script>
<script type="text/javascript"
src="../js/wholedaytran.js?verID=20150826_153700"></script>
<script type="text/javascript">
var json_result =
{"content":{"0":{"code":"6,881","timestamp":"15:59:59","order":"1175","transaction_type":"","bidask":"...{"code":"6,881","timestamp":"15:59:53","order":"1174","transaction_type":"",...{"code":"6,881","timestamp":"15:59:53","order":"1173",...

followed by a bunch of function definitions and other stuff.


> def turnover_detail(url):
>     response = requests.get(url)
>     html = response.content
>     soup = BeautifulSoup(html,"html.parser")
>     data = soup.find_all("script")
>     for json in data:
>         print(json)

The name json here is misleading because it's not really
json data at this point but javascript code. You will
need to further filter the code lines down to the ones
containing data and then convert them into pure json.

You don't show us the output but I'm assuming it's
the full javascript program? If so you need a second
level of parsing to extract the data from that.

It shouldn't be too difficult since the data you want
all starts with the string {"code": apart from the
first line which will need a little bit extra work.
But I don't think you really need any regex to do
this, regular string methods should suffice.

I suggest you should write a helper function to do
the data extraction and experiment in the interpreter
using some cut n pasted sample data till you get it right!

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From badouglas at gmail.com  Sun Dec 13 15:48:09 2015
From: badouglas at gmail.com (bruce)
Date: Sun, 13 Dec 2015 15:48:09 -0500
Subject: [Tutor] Beautiful Soup
In-Reply-To: <CAC7HCj_dtvm6tb7S2RrM4ktPwUTbYv+wWHDJ7sdcQqsM8_8kww@mail.gmail.com>
References: <CAC7HCj_dtvm6tb7S2RrM4ktPwUTbYv+wWHDJ7sdcQqsM8_8kww@mail.gmail.com>
Message-ID: <CAP16ngpDtcVfZOEe2BKkxy3KNu5ac5ZG-Hr7cMfc0qQX6twesQ@mail.gmail.com>

Hey Crusier/ (And Others...)

For your site...

As Alan mentioned, its a mix of html/jscript/etc..

So, you're going (or perhaps should) need to extract just the
json/struct that you need, and then go from there. I speak of
experience, as I've had to hande a number of sites that are
essentially just what you have.

Here's a basic guide to start:
--I use libxml, simplejson

fetch the page

in the page, do a split, to get the exact json (string) that you want.
-you'll do to splits, 1st gets rid of extra pre json stuff
 2nd gets rid of extra post json stuf that you don't need
--at this point, you should have the json string you need, or you
should be pretty close..

-now, you might need to "pretty" up what you have as py/json only
accepts key/value in certain format single/double quotes, etc..

once you've gotten this far, you might actually have the json string,
in which case, you can load it directly into the json, and proceed as
you wish.

you might also find that what you have, is really a py dictionary, and
you can handle that as well!

Have fun, let us know if you have issues...



On Sun, Dec 13, 2015 at 2:44 AM, Crusier <crusier at gmail.com> wrote:
> Dear All,
>
> I am trying to scrap the following website, however, I have
> encountered some problems. As you can see, I am not really familiar
> with regex and I hope you can give me some pointers to how to solve
> this problem.
>
> I hope I can download all the transaction data into the database.
> However, I need to retrieve it first. The data which I hope to
> retrieve it is as follows:
>
> "
> 15:59:59     A     500     6.790     3,395
> 15:59:53     B     500     6.780     3,390................
>
> Thank you
>
> Below is my quote:
>
> from bs4 import BeautifulSoup
> import requests
> import re
>
> url = 'https://bochk.etnet.com.hk/content/bochkweb/eng/quote_transaction_daily_history.php?code=6881&time=F&timeFrom=090000&timeTo=160000&turnover=S&sessionId=44c99b61679e019666f0570db51ad932&volMin=0&turnoverMin=0'
>
> def turnover_detail(url):
>     response = requests.get(url)
>     html = response.content
>     soup = BeautifulSoup(html,"html.parser")
>     data = soup.find_all("script")
>     for json in data:
>         print(json)
>
> turnover_detail(url)
>
> Best Regards,
> Henry
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

From oscar.j.benjamin at gmail.com  Mon Dec 14 07:10:22 2015
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Mon, 14 Dec 2015 12:10:22 +0000
Subject: [Tutor] Understanding a linear runtime implementation of
 anagram detection
In-Reply-To: <CADe=Ya8NTU-G-fivFJEd2u5WDQH-sXUEDiWTRdDOsHkKi=T2vw@mail.gmail.com>
References: <CADe=Ya8NTU-G-fivFJEd2u5WDQH-sXUEDiWTRdDOsHkKi=T2vw@mail.gmail.com>
Message-ID: <CAHVvXxTrV6C+wq3yYEMb8UCVGBC7wAjrWnFzvOAgm_CtTwALfQ@mail.gmail.com>

On 10 December 2015 at 12:38, Spyros Charonis <s.charonis at gmail.com> wrote:
> Dear All,
>
> I am learning about analysis of algorithms (python 2.7.6). I am reading a
> book (Problem solving with Algorithms and Data Structures) where Python is
> the language used for implementations. The author introduces algorithm
> analysis in a clear and understandable way, and uses an anagram detection
> program as a template to compare different runtime implementations
> (quadratic, log linear, linear). In the linear, and most efficient
> implementation, the code is as follows (comments added by me):

This is a good example problem for demonstrating the idea of
computational complexity but having actually wanted to write a program
that used anagram detection recently I concluded that a quadratic
performance can be acceptable or maybe even preferable for this. Here
is my own anagram function:

def anagram(s1, s2):
    seen = [False] * len(s2)
    for c1 in s1:
        for n2, c2 in enumerate(s2):
            if c1 == c2 and not seen[n2]:
                seen[n2] = TrueI would do this by using a dict
                break
        else:
            return False
    else:
        return all(seen)

This has O(N**2) complexity with N the string lengths. However the
real average complexity depends on the distribution of strings. The
loops in the above only run to completion if the two strings are
anagrams. Most of the time if you need to check whether two strings
are anagrams the probability that they are is small. When two strings
are not anagrams then the chances are typically high that the first
character of s1 is not in s2 at all. What that means is that the most
common runtime behaviour is to take the first character c1 from s1
then loop once through s2 verifying that none of the characters in s2
is equal to c1. So in the most common case we have a single iteration
through each character of one of the strings, whereas the "linear"
complexity algorithm you showed will always loop through both strings
fully. There are other differences such as not assuming lower-case
ascii characters etc. but these are not so important to this point.

If course in practice in Python the above code is inefficient because
it is implemented by the interpreter. The following is O(N*log(N)) but
will probably out-compete any of the examples shown:

def anagram(s1, s2):
    return sorted(s1) == sorted(s2)

The sorted function in Python is very efficient so it will be hard to
beat the performance of that unless the strings really are long. This
is why anagrams are also a poor example of algorithmic performance: in
most contexts where we might practically want to check for anagrams
the strings involved are likely to be very short meaning that the
big-O type analysis is useless.


> My questions are:
...
>
> 2)
> How could I go about adapting this algorithm for multiple strings (say I
> had 20 strings and wanted to check if they are anagrams of one another).
>
>     def are_anagrams(*args):
>
>     """ Accepts a tuple of strings and checks if
>
>          they are anagrams of each other """
>
>
>      # Check that neither of strings are null
>
>      for i in args:
>
>      if not i:
>
>          raise TypeError, "Invalid input"
>
>          return None
>
>
>
>      # Initialize a list of counters for each string
>
>      c = ( [] for i in range(len(args) ) ???

The complexity problem here is that you want to avoid comparing all N
strings against each other. If you do then your comparing N*(N-1)/2
(quadratic) strings for anagram-ness. Peter suggested using tuples of
counts so that a dict can check them. I would use sorted string keys:

def anagrams(*words):
    bykey = {}
    for word in words:
        key = ''.join(sorted(word))
        if key not in bykey:
            bykey[key] = [word]
        else:
            bykey[key].append(word)
    return bykey.values()

--
Oscar

From crusier at gmail.com  Mon Dec 14 11:16:39 2015
From: crusier at gmail.com (Crusier)
Date: Tue, 15 Dec 2015 00:16:39 +0800
Subject: [Tutor] Tutor Digest, Vol 142, Issue 11
In-Reply-To: <mailman.1747.1449997874.12404.tutor@python.org>
References: <mailman.1747.1449997874.12404.tutor@python.org>
Message-ID: <CAC7HCj_QXKP7UG0-AiYzjyWNNzCu7mOyk_a3HqRseeHb-sjwRg@mail.gmail.com>

Dear Alan,

Thank you very much for answering the question. If you don't mind,
please kindly let me know which library I should focus on among
beautifulsoup, selenium + PhantomJS, and dryscrape.

Have a good day

regards,
Hank

On Sun, Dec 13, 2015 at 5:11 PM,  <tutor-request at python.org> wrote:
> Send Tutor mailing list submissions to
>         tutor at python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
>         https://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
>         tutor-request at python.org
>
> You can reach the person managing the list at
>         tutor-owner at python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
>
>
> Today's Topics:
>
>    1. Re: Calculation error with a simple program (Steven D'Aprano)
>    2. Re: Calculation error with a simple program (Jim Gallaher)
>    3. Re: Calculation error with a simple program (Todd Purple)
>    4. Re: Tutor Digest, Vol 142, Issue 10 (Ken Hammer)
>    5. Beautiful Soup (Crusier)
>    6. Re: Beautiful Soup (Alan Gauld)
>
>
> ----------------------------------------------------------------------
>
> Message: 1
> Date: Sun, 13 Dec 2015 04:00:25 +1100
> From: Steven D'Aprano <steve at pearwood.info>
> To: tutor at python.org
> Subject: Re: [Tutor] Calculation error with a simple program
> Message-ID: <20151212170025.GK3821 at ando.pearwood.info>
> Content-Type: text/plain; charset=us-ascii
>
> On Sat, Dec 12, 2015 at 01:03:05AM -0600, Jim Gallaher wrote:
>> Hi everyone. I'm reading through a beginners Python book and came up
>> with a super simple program. I'm not getting any errors and everything
>> runs through, but there's a logical calculation error. What the program
>> does is take an amount and calculate a couple percentages and add a
>> couple fees.
>>
>> For example, if I put in a value of 1, it will output 752.12 as the sub
>> total and 753.12 as the grand total. It's off by 1 on sub total and 2 on
>> grand total.
>
> Check your arithmetic -- with a base price of $1, the sub total is
> $752.12 and the grand total is $753.12, exactly as Python calculates.
>
>
> But I wonder whether you have made a logic mistake in your code. You
> say:
>
> dealerPrep = basePrice + 500
> destinationCharge = basePrice + 250
>
> This means that the car will cost more than TRIPLE the base price.
> Instead of $1, enter a base price of $40,000 and you will see what I
> mean: now the dealer prep is $40500 and the destination charge is
> $40250, which added to the base price gives $120750 (plus tax and
> licence). Surely that's not right, the deal charges more than the cost
> of the car for preparation? I think what you want is:
>
> dealerPrep = 500
> destinationCharge = 250
>
>
>
> --
> Steve
>
>
> ------------------------------
>
> Message: 2
> Date: Sat, 12 Dec 2015 11:34:27 -0600
> From: Jim Gallaher <jcgallaher78 at gmail.com>
> To: tutor at python.org
> Subject: Re: [Tutor] Calculation error with a simple program
> Message-ID: <8774A398-4A0F-41DF-BBD2-941B49A3CC90 at gmail.com>
> Content-Type: text/plain;       charset=us-ascii
>
> Hi Alan,
>
> I'm 100 percent sure I'm wrong. :-) I verified it when I fixed the mistake. The problem was it was adding in the basePrice and the fixed rates/percentages each time. So I figured it out when Ian said something about that.
>
> Thanks for everyone's help! :-)
>
> ------------------------------
>
> Message: 3
> Date: Sat, 12 Dec 2015 08:13:23 -0500
> From: Todd Purple <todd_purple at yahoo.com>
> To: Jim Gallaher <jcgallaher78 at gmail.com>
> Cc: tutor at python.org
> Subject: Re: [Tutor] Calculation error with a simple program
> Message-ID: <6EC6D759-3C19-4A6D-8DD7-6EFAE1958CCD at yahoo.com>
> Content-Type: text/plain;       charset=us-ascii
>
>
>
>> On Dec 12, 2015, at 2:03 AM, Jim Gallaher <jcgallaher78 at gmail.com> wrote:
>>
>> Hi everyone. I'm reading through a beginners Python book and came up with a super simple program. I'm not getting any errors and everything runs through, but there's a logical calculation error. What the program does is take an amount and calculate a couple percentages and add a couple fees.
>>
>> For example, if I put in a value of 1, it will output 752.12 as the sub total and 753.12 as the grand total. It's off by 1 on sub total and 2 on grand total.
>>
>> Thanks in advance! Jim Gallaher
>>
>> # Car Salesman Calculator
>>
>> # User enters the base price of the car and the program adds tax, license, dealer prep, and destination charge.
>>
>> print("Car Sales Calculator")
>> basePrice = int(input("Please enter in the price of the car: "))
>>
>> # Misc charges to be added to the total cost of the car
>> tax = basePrice * .07
>> license = basePrice * .05
>> dealerPrep = basePrice + 500
>> destinationCharge = basePrice + 250
>>
>
> I think your main problem is right here. Why do dealerPrep and destinationCharge include the basePrice in their equation? This will add the basePrice in multiple times. I would simply set it like this:
>
> dealerPrep = 500
> destinationCharge = 250
>
> If these charges ever change, you can put in some sort of equation. However, it looks like these are meant to be a flat fee.
>
>> # Add the total misc charges together
>> subTotal = float(tax + license + dealerPrep + destinationCharge)
>>
>> # Add all the misic charges and include the base pricem
>> grandTotal = float(subTotal + basePrice)
>>
>> # Display the results
>> print("\nThe sub total is", subTotal)
>> print("\nYour grand Total is", grandTotal)
>>
>> input("\nPress the enter key to close the program.")
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>
>
> ------------------------------
>
> Message: 4
> Date: Sat, 12 Dec 2015 12:23:32 -0500
> From: "Ken Hammer"<kfh777 at earthlink.net>
> To: tutor at python.org
> Subject: Re: [Tutor] Tutor Digest, Vol 142, Issue 10
> Message-ID: <E1a7ntK-0001EN-U8 at elasmtp-mealy.atl.sa.earthlink.net>
>
>
> I have a more simple-minded solution.  The error appears to occur in testing without revealing the problem by use of $1 base price in the test.  Using $10,000 as the base price in the test reveals absurd numbers.  I think the real problem lies in the inclusion of base price inappropriately, twice as in:
>
>>dealerPrep = basePrice + 500
>>destinationCharge = basePrice + 250
>
> "basePrice" has no place in those two lines.  500 and 250 alone express the definition of the challenge.
>
> Ken
>
>
>
> In <mailman.13.1449939602.12987.tutor at python.org>, on 12/12/15
>    at 12:00 PM, tutor-request at python.org said:
>
>
>
>>Send Tutor mailing list submissions to
>>       tutor at python.org
>
>>To subscribe or unsubscribe via the World Wide Web, visit
>>       https://mail.python.org/mailman/listinfo/tutor
>>or, via email, send a message with subject or body 'help' to
>>       tutor-request at python.org
>
>>You can reach the person managing the list at
>>       tutor-owner at python.org
>
>>When replying, please edit your Subject line so it is more specific than
>>"Re: Contents of Tutor digest..."
>
>
>>Today's Topics:
>
>>   1. Calculation error with a simple program (Jim Gallaher)
>>   2. Re: Calculation error with a simple program (Alan Gauld)
>>   3. Re: Calculation error with a simple program (Laura Creighton)
>
>
>>----------------------------------------------------------------------
>
>>Message: 1
>>Date: Sat, 12 Dec 2015 01:03:05 -0600
>>From: Jim Gallaher <jcgallaher78 at gmail.com>
>>To: tutor at python.org
>>Subject: [Tutor] Calculation error with a simple program
>>Message-ID: <566BC6A9.6090206 at gmail.com>
>>Content-Type: text/plain; charset=utf-8; format=flowed
>
>>Hi everyone. I'm reading through a beginners Python book and came up  with
>>a super simple program. I'm not getting any errors and everything  runs
>>through, but there's a logical calculation error. What the program  does is
>>take an amount and calculate a couple percentages and add a  couple fees.
>
>>For example, if I put in a value of 1, it will output 752.12 as the sub
>>total and 753.12 as the grand total. It's off by 1 on sub total and 2 on
>>grand total.
>
>>Thanks in advance! Jim Gallaher
>
>># Car Salesman Calculator
>
>># User enters the base price of the car and the program adds tax,  license,
>>dealer prep, and destination charge.
>
>>print("Car Sales Calculator")
>>basePrice = int(input("Please enter in the price of the car: "))
>
>># Misc charges to be added to the total cost of the car
>>tax = basePrice * .07
>>license = basePrice * .05
>>dealerPrep = basePrice + 500
>>destinationCharge = basePrice + 250
>
>># Add the total misc charges together
>>subTotal = float(tax + license + dealerPrep + destinationCharge)
>
>># Add all the misic charges and include the base price
>>grandTotal = float(subTotal + basePrice)
>
>># Display the results
>>print("\nThe sub total is", subTotal)
>>print("\nYour grand Total is", grandTotal)
>
>>input("\nPress the enter key to close the program.")
>
>
>>------------------------------
>
>>Message: 2
>>Date: Sat, 12 Dec 2015 08:04:52 +0000
>>From: Alan Gauld <alan.gauld at btinternet.com>
>>To: tutor at python.org
>>Subject: Re: [Tutor] Calculation error with a simple program
>>Message-ID: <n4gkf4$e99$1 at ger.gmane.org>
>>Content-Type: text/plain; charset=utf-8
>
>>On 12/12/15 07:03, Jim Gallaher wrote:
>
>>> For example, if I put in a value of 1, it will output 752.12 as the sub
>>> total and 753.12 as the grand total. It's off by 1 on sub total and 2 on
>>> grand total.
>
>>Are you sure? Lets check the values...
>
>>> basePrice = int(input("Please enter in the price of the car: "))
>
>>=> 1
>
>>> tax = basePrice * .07
>
>>=> 0.07
>
>>> license = basePrice * .05
>
>>=> 0.05
>>> dealerPrep = basePrice + 500
>
>>=> 501
>
>>> destinationCharge = basePrice + 250
>
>>=> 251
>
>>> # Add the total misc charges together
>>> subTotal = float(tax + license + dealerPrep + destinationCharge)
>
>>=> 0.07 + 0.05 + 501 + 251 => 752.12
>
>>> # Add all the misic charges and include the base price
>>> grandTotal = float(subTotal + basePrice)
>
>>=> 752.12 + 1 => 753.12
>
>>Looks like Python got it right to me?
>
>
>
>
> --
> -----------------------------------------------------------
> K.F.Hammer Associates                                         Ken Hammer
> management consultations                      Saint Johnsbury, VT  05819
> -----------------------------------------------------------
>
>
>
> ------------------------------
>
> Message: 5
> Date: Sun, 13 Dec 2015 15:44:33 +0800
> From: Crusier <crusier at gmail.com>
> To: tutor at python.org
> Subject: [Tutor] Beautiful Soup
> Message-ID:
>         <CAC7HCj_dtvm6tb7S2RrM4ktPwUTbYv+wWHDJ7sdcQqsM8_8kww at mail.gmail.com>
> Content-Type: text/plain; charset=UTF-8
>
> Dear All,
>
> I am trying to scrap the following website, however, I have
> encountered some problems. As you can see, I am not really familiar
> with regex and I hope you can give me some pointers to how to solve
> this problem.
>
> I hope I can download all the transaction data into the database.
> However, I need to retrieve it first. The data which I hope to
> retrieve it is as follows:
>
> "
> 15:59:59     A     500     6.790     3,395
> 15:59:53     B     500     6.780     3,390................
>
> Thank you
>
> Below is my quote:
>
> from bs4 import BeautifulSoup
> import requests
> import re
>
> url = 'https://bochk.etnet.com.hk/content/bochkweb/eng/quote_transaction_daily_history.php?code=6881&time=F&timeFrom=090000&timeTo=160000&turnover=S&sessionId=44c99b61679e019666f0570db51ad932&volMin=0&turnoverMin=0'
>
> def turnover_detail(url):
>     response = requests.get(url)
>     html = response.content
>     soup = BeautifulSoup(html,"html.parser")
>     data = soup.find_all("script")
>     for json in data:
>         print(json)
>
> turnover_detail(url)
>
> Best Regards,
> Henry
>
>
> ------------------------------
>
> Message: 6
> Date: Sun, 13 Dec 2015 09:10:57 +0000
> From: Alan Gauld <alan.gauld at btinternet.com>
> To: tutor at python.org
> Subject: Re: [Tutor] Beautiful Soup
> Message-ID: <n4jcn1$qrm$1 at ger.gmane.org>
> Content-Type: text/plain; charset=utf-8
>
> On 13/12/15 07:44, Crusier wrote:
>> Dear All,
>>
>> I am trying to scrap the following website, however, I have
>> encountered some problems. As you can see, I am not really familiar
>> with regex and I hope you can give me some pointers to how to solve
>> this problem.
>
> I'm not sure why you mention regex because your script doesn't
> use regex. And for html that's a good thing.
>
>> I hope I can download all the transaction data into the database.
>> However, I need to retrieve it first. The data which I hope to
>> retrieve it is as follows:
>>
>> "
>> 15:59:59     A     500     6.790     3,395
>> 15:59:53     B     500     6.780     3,390................
>>
>
> Part of your problem is that the data is not in html format but
> is in fact part of the Javascript code on the page. And
> BeautifulSoup is not so good at parsing Javascript.
>
> The page code looks like
>
> <script type="text/javascript"
> src="../js/jquery.js?verID=20150826_153700"></script>
> <script type="text/javascript"
> src="../js/common_eng.js?verID=20150826_153700"></script>
> <script type="text/javascript"
> src="../js/corsrequest.js?verID=20150826_153700"></script>
> <script type="text/javascript"
> src="../js/wholedaytran.js?verID=20150826_153700"></script>
> <script type="text/javascript">
> var json_result =
> {"content":{"0":{"code":"6,881","timestamp":"15:59:59","order":"1175","transaction_type":"","bidask":"...{"code":"6,881","timestamp":"15:59:53","order":"1174","transaction_type":"",...{"code":"6,881","timestamp":"15:59:53","order":"1173",...
>
> followed by a bunch of function definitions and other stuff.
>
>
>> def turnover_detail(url):
>>     response = requests.get(url)
>>     html = response.content
>>     soup = BeautifulSoup(html,"html.parser")
>>     data = soup.find_all("script")
>>     for json in data:
>>         print(json)
>
> The name json here is misleading because it's not really
> json data at this point but javascript code. You will
> need to further filter the code lines down to the ones
> containing data and then convert them into pure json.
>
> You don't show us the output but I'm assuming it's
> the full javascript program? If so you need a second
> level of parsing to extract the data from that.
>
> It shouldn't be too difficult since the data you want
> all starts with the string {"code": apart from the
> first line which will need a little bit extra work.
> But I don't think you really need any regex to do
> this, regular string methods should suffice.
>
> I suggest you should write a helper function to do
> the data extraction and experiment in the interpreter
> using some cut n pasted sample data till you get it right!
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
>
>
> ------------------------------
>
> Subject: Digest Footer
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> https://mail.python.org/mailman/listinfo/tutor
>
>
> ------------------------------
>
> End of Tutor Digest, Vol 142, Issue 11
> **************************************

From alan.gauld at btinternet.com  Mon Dec 14 14:56:26 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 14 Dec 2015 19:56:26 +0000
Subject: [Tutor] parser recommendations (was Re: Tutor Digest, Vol 142,
 Issue 11)
In-Reply-To: <CAC7HCj_QXKP7UG0-AiYzjyWNNzCu7mOyk_a3HqRseeHb-sjwRg@mail.gmail.com>
References: <mailman.1747.1449997874.12404.tutor@python.org>
 <CAC7HCj_QXKP7UG0-AiYzjyWNNzCu7mOyk_a3HqRseeHb-sjwRg@mail.gmail.com>
Message-ID: <n4n6t9$q18$1@ger.gmane.org>

On 14/12/15 16:16, Crusier wrote:

Please always supply a useful subject line when replying to the digest
and also delete all irrelevant text. Some people pay by the byte and we
have all received these messages already.

> Thank you very much for answering the question. If you don't mind,
> please kindly let me know which library I should focus on among
> beautifulsoup, selenium + PhantomJS, and dryscrape.

I don't know anything about the others but Beautiful soup
is good for html, especially badly written/generated html.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From akleider at sonic.net  Mon Dec 14 16:48:36 2015
From: akleider at sonic.net (Alex Kleider)
Date: Mon, 14 Dec 2015 13:48:36 -0800
Subject: [Tutor] interface
Message-ID: <41d908e5c2dd5cc68875549bcb4c6f1a@sonic.net>

So far all my python programming has been done using print for output 
and
(raw)input whenever user input is required.  I'd like to learn how to
provide a graphical interface.  There are several choices with pros and
cons to each but an alternative more general approach might be to use a
web based interface which I believe would make the code less platform
dependent.

I'd be interested in any comments regarding this idea and would be
grateful for any suggestions as to frameworks that might be helpful.
I've been looking at django but finding the learning curve to be steep
and it may not be the best solution.

Of late I've been using Python3; my platform is Ubuntu 14.4.

Thanks in advance for any guidance.

Alex

From breamoreboy at yahoo.co.uk  Mon Dec 14 17:25:29 2015
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Mon, 14 Dec 2015 22:25:29 +0000
Subject: [Tutor] interface
In-Reply-To: <41d908e5c2dd5cc68875549bcb4c6f1a@sonic.net>
References: <41d908e5c2dd5cc68875549bcb4c6f1a@sonic.net>
Message-ID: <n4nfl1$egn$1@ger.gmane.org>

On 14/12/2015 21:48, Alex Kleider wrote:
> So far all my python programming has been done using print for output and
> (raw)input whenever user input is required.  I'd like to learn how to
> provide a graphical interface.  There are several choices with pros and
> cons to each but an alternative more general approach might be to use a
> web based interface which I believe would make the code less platform
> dependent.

I'd say your belief is simply wrong, many Python desktop GUIs are cross 
platform.  I'd start with tkinter as it's available with Python, there 
are loads of tutorials available for it and you'll be able to get advice 
here or on the main Python mailing list.

>
> I'd be interested in any comments regarding this idea and would be
> grateful for any suggestions as to frameworks that might be helpful.
> I've been looking at django but finding the learning curve to be steep
> and it may not be the best solution.

Django strikes me as pure overkill for your needs.  If you must go down 
the web route I'd start here https://wiki.python.org/moin/WebFrameworks 
at the section headed "Popular Non Full-Stack Frameworks".

>
> Of late I've been using Python3; my platform is Ubuntu 14.4.
>
> Thanks in advance for any guidance.
>
> Alex

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

Mark Lawrence


From ben+python at benfinney.id.au  Mon Dec 14 17:39:32 2015
From: ben+python at benfinney.id.au (Ben Finney)
Date: Tue, 15 Dec 2015 09:39:32 +1100
Subject: [Tutor] interface
References: <41d908e5c2dd5cc68875549bcb4c6f1a@sonic.net>
Message-ID: <85k2og4puj.fsf@benfinney.id.au>

Alex Kleider <akleider at sonic.net> writes:

> I'd be interested in any comments regarding this idea and would be
> grateful for any suggestions as to frameworks that might be helpful.

The collected wisdom of the community includes this page at the Python
wiki <URL:https://wiki.python.org/moin/GuiProgramming>, and a brief
comparison of toolkits is at
<URL:https://wiki.python.org/moin/GUI%20Programming%20in%20Python>.

> I've been looking at django but finding the learning curve to be steep
> and it may not be the best solution.

That seems a reasonable assessment; if you just want a UI for a
not-particularly-website program, Django may be a poor fit.

> Of late I've been using Python3; my platform is Ubuntu 14.4.

I recommend you start with the default, heavily-documented Tkinter
<URL:https://docs.python.org/3/library/tkinter.html> and the Ttk
extension <URL:https://docs.python.org/3/library/tkinter.ttk.html>. Both
of these are part of the Python 3 system in Ubuntu.

You can find a good guide to Tk programming in Python as one stream of
the excellent <URL:http://www.tkdocs.com/>.

-- 
 \        ?If you have the facts on your side, pound the facts. If you |
  `\     have the law on your side, pound the law. If you have neither |
_o__)                       on your side, pound the table.? ?anonymous |
Ben Finney


From badouglas at gmail.com  Mon Dec 14 17:58:54 2015
From: badouglas at gmail.com (bruce)
Date: Mon, 14 Dec 2015 17:58:54 -0500
Subject: [Tutor] parser recommendations (was Re: Tutor Digest, Vol 142,
 Issue 11)
In-Reply-To: <n4n6t9$q18$1@ger.gmane.org>
References: <mailman.1747.1449997874.12404.tutor@python.org>
 <CAC7HCj_QXKP7UG0-AiYzjyWNNzCu7mOyk_a3HqRseeHb-sjwRg@mail.gmail.com>
 <n4n6t9$q18$1@ger.gmane.org>
Message-ID: <CAP16ngpsoW=AWvxBBEEj+aRFOBuGiLrDRyyTfLANHhyxwBUfXA@mail.gmail.com>

beautifulsoup, selenium + PhantomJS, and dryscrape

no knowledge of dryscape, never used it.

The other tools/apps are used to handle/parse html/websites.

Ssoup can handle xml/html as well as other input structs. Good for
being able to parse the resulting struct/dom to extract data, or to
change/modify the struct itself.

Selenium is a framework, acting as a browser env, allowing you to
'test' the site/html. It's good for certain uses regarding testing.

Phantomjs/casperjs are exxentially headless broswers, allow you to
also run/parse websites. While Soup is more for static, Phantom
because it's an actual headless browser, allows you to deal with
dynamic sites as well as static.




On Mon, Dec 14, 2015 at 2:56 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> On 14/12/15 16:16, Crusier wrote:
>
> Please always supply a useful subject line when replying to the digest
> and also delete all irrelevant text. Some people pay by the byte and we
> have all received these messages already.
>
>> Thank you very much for answering the question. If you don't mind,
>> please kindly let me know which library I should focus on among
>> beautifulsoup, selenium + PhantomJS, and dryscrape.
>
> I don't know anything about the others but Beautiful soup
> is good for html, especially badly written/generated html.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

From alan.gauld at btinternet.com  Mon Dec 14 19:52:58 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 15 Dec 2015 00:52:58 +0000
Subject: [Tutor] interface
In-Reply-To: <41d908e5c2dd5cc68875549bcb4c6f1a@sonic.net>
References: <41d908e5c2dd5cc68875549bcb4c6f1a@sonic.net>
Message-ID: <n4no99$lh4$1@ger.gmane.org>

On 14/12/15 21:48, Alex Kleider wrote:

> provide a graphical interface.  There are several choices with pros and
> cons to each but an alternative more general approach might be to use a
> web based interface which I believe would make the code less platform
> dependent.

Not necessarily since the web server end still needs to live on
a particular OS platform and any OS level operations will be
just as restrictive for a web app as for a GUI. But a web app
is able to be opened up to multiple platforms as clients so
it depends on how you intend to deploy  it. If its just for
you (or for any one user) then the web doesn't help much
and adds lots of extra learning.

A GUI will involve new concepts too and a lot more code than
a CLI like you have been using. But a web app will require
whole new languages(HTML/CSS/Javascript) as well as new
concepts. A much steeper learning curve unless you already
come from a web background.

The simplest GUI framework is Tkinter, but its also fairly
limiting longer term. For putting a quick form interface
on top of an existing app its great but for a full GUI
app its less effective. It also has virtually no GUI
builder tool support.

wxPython is slightly more complex but more powerful and
looks more like the native UI on each platform. (There
is also Dabo which is wxPython based but has an IDE with
GUI builder and is very good for database oriented apps.)

pyQt/Side and PyGTK are both much more complex but also
more powerful. IDES with GUI Builders exist for both
although none of them worked very well for me.

They are all cross platform and you more or less trade
power and flexibility for simplicity. Personally I'd start
with Tkinter  - its a good general intro to the concepts of
GUI programming and standard Python so portable to other
users without extra downloads. Then decide which of the
other three to migrate too if you need more power.
Personally I find Tkinter good enough for almost all
my GUI needs, but I'm not distributing them or selling
them.

All of the above is strictly my personal opinion of
course. Others may disagree.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at btinternet.com  Mon Dec 14 20:54:30 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 15 Dec 2015 01:54:30 +0000
Subject: [Tutor] is v == for small ints
Message-ID: <n4nrsm$7p6$1@ger.gmane.org>

Somebody posted a question about this today and I approved
it but it hasn't shown up. We have had about 6 or 7 such
problems in the last month. Mainly they have been thank-you
messages so I didn't make an issue of it but a couple
have been genuine questions, like this was.

So if you have posted recently and it hasn't got through,
my apologies, but I have no idea what is going wrong.

As to the content of this message, the gist was that he had
tried 'is' and == with both small and large ints. When using
small ints the results were the same for both operators but
for large ints they differed. He knew the conceptual difference
between 'is' and == but didn't understand why the results
were different for large/small ints.

The answer is of course that small ints are cached internally
as an optimisation so all references to 5, for example,
refer to the same object in memory and therefore both is
(object identity) and == (value equality) are true. Large
ints result in two separate objects each with the same
value so 'is' becomes False and == remains true.

This behaviour should never be relied on since the definition
of a "small int" is potentially implementation dependant and
could even change with Python version or platform. Always
use == to test integers.

Apologies again about the missing messages.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From steve at pearwood.info  Mon Dec 14 23:10:15 2015
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 15 Dec 2015 15:10:15 +1100
Subject: [Tutor] is v == for small ints
In-Reply-To: <n4nrsm$7p6$1@ger.gmane.org>
References: <n4nrsm$7p6$1@ger.gmane.org>
Message-ID: <20151215041015.GA16091@ando.pearwood.info>

On Tue, Dec 15, 2015 at 01:54:30AM +0000, Alan Gauld wrote:

> This behaviour should never be relied on since the definition
> of a "small int" is potentially implementation dependant and
> could even change with Python version or platform. Always
> use == to test integers.

It isn't just *potentially* implementation dependent, it certainly is 
implementation dependant.

Different versions of Python have used different rules for which small 
ints are cached, and the rules for when they will be re-used or cached. 
For example, this is with Python 2.7:


py> a = 100001
py> b = 100001
py> a is b
False
py> a = 100002; b = 100002
py> a is b
True


You CANNOT rely on this behaviour, it WILL change from version to 
version.



-- 
Steve

From akleider at sonic.net  Mon Dec 14 23:08:06 2015
From: akleider at sonic.net (Alex Kleider)
Date: Mon, 14 Dec 2015 20:08:06 -0800
Subject: [Tutor] interface
In-Reply-To: <n4no99$lh4$1@ger.gmane.org>
References: <41d908e5c2dd5cc68875549bcb4c6f1a@sonic.net>
 <n4no99$lh4$1@ger.gmane.org>
Message-ID: <fc616a945551ae356144a50e579d1e56@sonic.net>

Thank you, gentlemen (Alan, Ben, Mark,) for your advice.
The consensus seems to be in favour of tkinter
so I'll head in that direction.
Cheers,
Alex

From ben+python at benfinney.id.au  Mon Dec 14 23:55:35 2015
From: ben+python at benfinney.id.au (Ben Finney)
Date: Tue, 15 Dec 2015 15:55:35 +1100
Subject: [Tutor] interface
References: <41d908e5c2dd5cc68875549bcb4c6f1a@sonic.net>
 <n4no99$lh4$1@ger.gmane.org>
 <fc616a945551ae356144a50e579d1e56@sonic.net>
Message-ID: <858u4w48fs.fsf@benfinney.id.au>

Alex Kleider <akleider at sonic.net> writes:

> Thank you, gentlemen (Alan, Ben, Mark,) for your advice.
> The consensus seems to be in favour of tkinter
> so I'll head in that direction.

Keep in mind that Tkinter is the ?one obvious way to do it? for GUIs in
Python. It is the general-purpose toolkit included with the standard
library.

There are other ways (i.e. other GUI toolkits for Python) that may be
better suited to your specific case, but are not the obvious general
default ? and they impose a higher deployment burden because they are
third-party libraries.

So, start with Tkinter and get it working that way. Then, once you
better understand your specific case by making a working solution, you
can re-assess. Tkinter might be just fine, or you may want to try
others. But start with Tkinter, yes.

-- 
 \      ?It seems intuitively obvious to me, which means that it might |
  `\                                           be wrong.? ?Chris Torek |
_o__)                                                                  |
Ben Finney


From lac at openend.se  Tue Dec 15 03:05:13 2015
From: lac at openend.se (Laura Creighton)
Date: Tue, 15 Dec 2015 09:05:13 +0100
Subject: [Tutor] interface
In-Reply-To: <n4no99$lh4$1@ger.gmane.org>
References: <41d908e5c2dd5cc68875549bcb4c6f1a@sonic.net>
 <n4no99$lh4$1@ger.gmane.org>
Message-ID: <201512150805.tBF85DNl027443@fido.openend.se>

A question for Alex Kleider:
Do you want this thing to eventually run on mobile? -- android and IOS?

If so, tkinter isn't the place to start, but kivy (which also runs
on desktops) is. http://kivy.org/#home

re: full stack frameworks
The thing about full stack frameworks such as Django is that they
provide their own 'full ecosystem' --  if you are going to use Django,
you are going to have to learn -the Django way to do things-.  Now
Django, in particular, fits many people's brains quite nicely.  So 
they find doing things 'the Django way' fairly natural ... it works
the way they expected.

But there are a whole lot of other people who don't naturally think
in anything approaching -the Django way-.  They end up fighting the
framework every inch of the way, which makes for an extremely unpleasant
experience.  And this goes for every full stack Framework there is --
every one of them has arbitrary decision after arbitrary decision
after arbitrary decision --  we had to pick a way to do things, and
also force everybody to do it this way, and this is what we picked.

This doesn't bother many people at all.  They are very good at
accepting 'this is the way the world is' and it does not stress them
out that this is the case.  In contrast, many people find that this
accepting attitude cuts right across their own creativity -- not
accepting 'the world the way it is' in favour of 'the world, as I
shall make it better' is essential to their own creative process.
Unless the full stack framework happens to make the arbitrary
decisions pretty much the same way that they would, they will find
using such a thing a constant source of frustration.

So, full stack frameworks can save you a lot of work and effort, but
only if you are willing to do things the framework's way.  If, as
you explore using Django (or any other full stack framework) remember
this note -- if you find the whole thing tedious, arbitrary and
frustrating, it may be an indication that you have the wrong
framework, or that Full Stack frameworks are not for you, and you
would be happier with a much lighter one, such as bottle or flask.

Laura

From scampsd at hotmail.com  Tue Dec 15 04:14:36 2015
From: scampsd at hotmail.com (Dominique Descamps)
Date: Tue, 15 Dec 2015 09:14:36 +0000
Subject: [Tutor] Batchfile to Python conversion
Message-ID: <DUB125-W57974D76F4BCF4E771DB15B4EE0@phx.gbl>

Dear,
In my company we are working with Windows-7 batchfiles, but as you know, this is very limited, unreadable and time-consuming.
 
I have already some experience with Python and as I'm very satisfied with it, I would like to use Python instead of continuing using batchfiles.
Those batchfiles however need to be updated, and therefore I would like to convert those into Python scripts.
On the StackOverflow website, I have seen some issues of people who have done this manually.
As I'm dealing here with almost hundred batchfiles, some of them containing several hundreds of lines of code, I'm more interested in a tool, who can do this conversion automatically.
 
Can you confirm me whether or not such a conversion tool already exists?
Thanks
Dominique
 		 	   		  

From alan.gauld at btinternet.com  Tue Dec 15 04:48:21 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 15 Dec 2015 09:48:21 +0000
Subject: [Tutor] Batchfile to Python conversion
In-Reply-To: <DUB125-W57974D76F4BCF4E771DB15B4EE0@phx.gbl>
References: <DUB125-W57974D76F4BCF4E771DB15B4EE0@phx.gbl>
Message-ID: <n4onl5$s5o$1@ger.gmane.org>

On 15/12/15 09:14, Dominique Descamps wrote:

> As I'm dealing here with almost hundred batchfiles, some of them 
> containing several hundreds of lines of code, I'm more
> interested in a tool, who can do this conversion automatically.
>  
> Can you confirm me whether or not such a conversion tool already exists?

I certainly have never heard of such a thing.
Even if it did exist it would probably produce terrible Python code.

The reason I say that is that batch files (like Unix shell
scripts but more so) are essentially program launchers. They get the
work done by starting other programs. A Python conversion would
wind up being full of os.system() calls or Popen() calls.

Also the bat file control structures are very limited (much
worse than Unix shell) and a conversion script would be unable
to select more elegant structures. So while you might translate
the batch file code to Python it would probably be nearly as
unreadable and error prone as the original batch file was.

I would suggest your best bet is not to even try converting
all of the scripts but to tackle them one by one as you need
to work on them. This may mean that some of the scripts never
get converted, but those will be the ones that are stable and
working as intended. If they ain't broke, don't fix them...
The ones that need regular maintenance are the ones you most
want in Python.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From lintern121184 at gmail.com  Tue Dec 15 06:19:33 2015
From: lintern121184 at gmail.com (Matthew Lintern)
Date: Tue, 15 Dec 2015 11:19:33 +0000
Subject: [Tutor] functions
Message-ID: <CAFM44y8BBsoHP5rqki1_8xTnsdevFVz4TJ2ntqR-xJ_xvdSMKg@mail.gmail.com>

Hello,

I'm new to python and I've been following some youtube videos etc to learn
python. I'm using the spyder IDE.  Im having problems with the following
piece of code:

def myfun(x):
    y=x**2
    return y

print myfun(5)

the answer I should get is obviously 25, and this is the case in the video
(https://www.youtube.com/v/GT1UfkLIeZ4?version=3&vq=hd1080&autoplay=1)

However, Spyder tells me theres a syntax error with myfun(5).  However, the
videos shows no issue....?

Any help is greatly appreciated!

Thanks

Matt

From alan.gauld at btinternet.com  Tue Dec 15 07:55:19 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 15 Dec 2015 12:55:19 +0000
Subject: [Tutor] functions
In-Reply-To: <CAFM44y8BBsoHP5rqki1_8xTnsdevFVz4TJ2ntqR-xJ_xvdSMKg@mail.gmail.com>
References: <CAFM44y8BBsoHP5rqki1_8xTnsdevFVz4TJ2ntqR-xJ_xvdSMKg@mail.gmail.com>
Message-ID: <n4p2jm$h51$1@ger.gmane.org>

On 15/12/15 11:19, Matthew Lintern wrote:

> def myfun(x):
>     y=x**2
>     return y
> 
> print myfun(5)
> 
> However, Spyder tells me there's a syntax error with myfun(5).

I suspect that the video is for Python v2 and you are using
Python v3. v3 was a major change in the language and on of
the biggest was that print is now a function and therefore
needs parentheses around its arguments.
So your code should look like:

print( myfun(5) )

My recommendation is that you try to find a set of
python v3 videos. Alternatively download Python v2.7
and use that with the v2 videos, then when you are
ready to upgrade to v3 you can look at one of the
many resources on migrating from 2->3.


BTW One alternative source outside Youtube is
Showmedo.com. Some of them are paid for but many
are free.

http://showmedo.com/videotutorials/python

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From steve at pearwood.info  Tue Dec 15 08:00:17 2015
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 16 Dec 2015 00:00:17 +1100
Subject: [Tutor] functions
In-Reply-To: <CAFM44y8BBsoHP5rqki1_8xTnsdevFVz4TJ2ntqR-xJ_xvdSMKg@mail.gmail.com>
References: <CAFM44y8BBsoHP5rqki1_8xTnsdevFVz4TJ2ntqR-xJ_xvdSMKg@mail.gmail.com>
Message-ID: <20151215130017.GP3821@ando.pearwood.info>

On Tue, Dec 15, 2015 at 11:19:33AM +0000, Matthew Lintern wrote:
> Hello,
> 
> I'm new to python and I've been following some youtube videos etc to learn
> python. I'm using the spyder IDE.  Im having problems with the following
> piece of code:
> 
> def myfun(x):
>     y=x**2
>     return y
> 
> print myfun(5)
> 
> the answer I should get is obviously 25, and this is the case in the video
> (https://www.youtube.com/v/GT1UfkLIeZ4?version=3&vq=hd1080&autoplay=1)
> 
> However, Spyder tells me theres a syntax error with myfun(5).  However, the
> videos shows no issue....?

I'm not familiar with Spyder, but I expect it should actually show 
you where the error is, or at least, where it *notices* the error 
for the first time.

For instance, you might see something like this:

py> print func(5}
  File "<stdin>", line 1
    print func(5}
                ^
SyntaxError: invalid syntax

Look carefully, and you will see I mis-typed the closing bracket ) as } 
instead.

Or you might get something like this:

py>   print func(5)
  File "<stdin>", line 1
    print func(5)
    ^
IndentationError: unexpected indent

Spyder might treat that as a syntax error.


If you get this:

py> print func(5)
  File "<stdin>", line 1
    print func(5)
             ^
SyntaxError: invalid syntax

Notice the caret ^ pointing just after the first word following "print"? 
In that case, try running these twolines of code instead:

import sys
print(sys.version)


If the version starts with 3, then you have discovered a minor nuisance 
when programming in Python: a slight difference between Python version 3 
and older versions.

In Python 3, "print" is a normal function, and so it must be called with 
parentheses:

    print(func(5))

In Python 2, "print" is a special statement, which doesn't require 
parentheses, so you can write this:

    print func(5)

Many tutorials are written for Python 2, and so they will show print 
with a space, but that's a syntax error in Python 3. Just remember to 
always use an extra pair of brackets for printing, and you should be 
fine.



-- 
Steve

From evanlespaul at gmail.com  Tue Dec 15 09:18:47 2015
From: evanlespaul at gmail.com (Evan Sommer)
Date: Tue, 15 Dec 2015 09:18:47 -0500
Subject: [Tutor] Countdown Clock Programming Question
In-Reply-To: <CAPNRz83Va1M4uESEqURKFJgnb=K-cE0p9pn23OuukYWg4Weq=A@mail.gmail.com>
References: <CAPNRz83ooFrYkqq6E7SvOeJW6aaWQoO0H-OXh7nrCrU-XQ9+MQ@mail.gmail.com>
 <CAPNRz83Va1M4uESEqURKFJgnb=K-cE0p9pn23OuukYWg4Weq=A@mail.gmail.com>
Message-ID: <CAPNRz81Pq_nFTS4A0B9fuvt=WjX8WSjDLai8J3t_tWOCR4-OiA@mail.gmail.com>

Hey there Alan!

So I tried some of your modifications, and they seem to be doing some
pretty interesting things with the program. For some reason, now the
program runs extremely fast, and doesn't now count down in one second
intervals. I think this is a result of the root.after command. I still
get 3 different windows with 3 different colours as well.

I'm probably just doing something completely wrong, so if you could
show me where to edit the code, I would much appreciate it!

Thanks!

Here is the most recent code:

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk
import time
def count_down(start, end):
        root.after (1000, count_down)
root = tk.Tk()
time_str = tk.StringVar()
# create the time display label, give it a large font
# label auto-adjusts to the font
label_font = ('helvetica', 100)
tk.Label(root, textvariable=time_str, font=label_font, bg='forestgreen',
         fg='white', relief='raised', bd=3).pack(fill='x', padx=5, pady=5)
 # start with 2 minutes --> 119 seconds
for t in range(240, 120, -15):
        # format as 2 digit integers, fills with zero to the left
        # divmod() gives minutes, seconds
        sf = "{:01d}:{:02d}".format(*divmod(t, 60))
        #print(sf)  # test
        time_str.set(sf)
        root.update()
        # delay one second
        root.after (1, count_down)
# create the time display label, give it a large font
# label auto-adjusts to the font
label_font = ('helvetica', 100)
tk.Label(root, textvariable=time_str, font=label_font, bg='gold',
         fg='white', relief='raised', bd=3).pack(fill='x', padx=5, pady=5)
 # start with 1 minutes --> 59 seconds
for t in range(120,60, -15):
        # format as 2 digit integers, fills with zero to the left
        # divmod() gives minutes, seconds
        sf = "{:01d}:{:02d}".format(*divmod(t, 60))
        #print(sf)  # test
        time_str.set(sf)
        root.update()
        # delay one second
        root.after (1, count_down)
# create the time display label, give it a large font
# label auto-adjusts to the font
label_font = ('helvetica', 100)
tk.Label(root, textvariable=time_str, font=label_font, bg='firebrick',
         fg='white', relief='raised', bd=3).pack(fill='x', padx=5, pady=5)
 # start with 4 minutes --> 240 seconds
for t in range(60,-1, -15):
        # format as 2 digit integers, fills with zero to the left
        # divmod() gives minutes, seconds
        sf = "{:01d}:{:02d}".format(*divmod(t, 60))
        #print(sf)  # test
        time_str.set(sf)
        root.update()
        # delay one second
        root.after (1, count_down)
# start the GUI event loop
root.mainloop()


On 11/30/15, Evan Sommer <evanlespaul at gmail.com> wrote:
> Hello again Alan!
>
>  Do you think you could write a revised code with the modifications that
> you suggested? I tried changing the code with your recommendations and I
> keep getting syntax errors.
>
> If you could do that, I would greatly appreciate it!!
>
> Thank you for all your help!
>
> Evan Sommer
>
> On Tue, Nov 24, 2015 at 9:01 AM, Evan Sommer <evanlespaul at gmail.com> wrote:
>
>> Hello there!
>>
>> I am working on a project for an engineering class that I am in at my
>> high
>> school, and our task has been to create a clock that counts down the time
>> between periods, so that the students walking the hallways know how much
>> time they have to get to class. The timer will be displayed on multiple
>> monitors throughout the halls. However, the idea behind the countdown
>> clock
>> is for the background to change colours when it hits a certain time. The
>> goal is for the clock to change from green to yellow at 2 minutes, and
>> yellow to red at 1 minute. However, I have been having a hard time trying
>> to get the color change to display in one window. If you could give me
>> some
>> advice, I'd really appreciate it!
>>
>> Here's the code:
>>
>> try:
>>     # Python2
>>     import Tkinter as tk
>> except ImportError:
>>     # Python3
>>     import tkinter as tk
>> import time
>> def count_down():
>>     # start with 4 minutes --> 240 seconds
>>     for t in range(240, 120, -1):
>>         # format as 2 digit integers, fills with zero to the left
>>         # divmod() gives minutes, seconds
>>         sf = "{:01d}:{:02d}".format(*divmod(t, 60))
>>         #print(sf)  # test
>>         time_str.set(sf)
>>         root.update()
>>         # delay one second
>>         time.sleep(1)# create root/main window
>> root = tk.Tk()
>> time_str = tk.StringVar()
>> # create the time display label, give it a large font
>> # label auto-adjusts to the font
>> label_font = ('helvetica', 100)
>> tk.Label(root, textvariable=time_str, font=label_font, bg='green',
>>          fg='white', relief='raised', bd=3).pack(fill='x', padx=5,
>> pady=5)
>>  # start with 2 minutes --> 119 seconds
>> for t in range(240, 120, -1):
>>         # format as 2 digit integers, fills with zero to the left
>>         # divmod() gives minutes, seconds
>>         sf = "{:01d}:{:02d}".format(*divmod(t, 60))
>>         #print(sf)  # test
>>         time_str.set(sf)
>>         root.update()
>>         # delay one second
>>         time.sleep(1)
>> # create the time display label, give it a large font
>> # label auto-adjusts to the font
>> label_font = ('helvetica', 100)
>> tk.Label(root, textvariable=time_str, font=label_font, bg='yellow',
>>          fg='white', relief='raised', bd=3).pack(fill='x', padx=5,
>> pady=5)
>>  # start with 1 minutes --> 59 seconds
>> for t in range(120,60, -1):
>>         # format as 2 digit integers, fills with zero to the left
>>         # divmod() gives minutes, seconds
>>         sf = "{:01d}:{:02d}".format(*divmod(t, 60))
>>         #print(sf)  # test
>>         time_str.set(sf)
>>         root.update()
>>         # delay one second
>>         time.sleep(1)
>> # create the time display label, give it a large font
>> # label auto-adjusts to the font
>> label_font = ('helvetica', 100)
>> tk.Label(root, textvariable=time_str, font=label_font, bg='red',
>>          fg='white', relief='raised', bd=3).pack(fill='x', padx=5,
>> pady=5)
>>  # start with 4 minutes --> 240 seconds
>> for t in range(60,-1, -1):
>>         # format as 2 digit integers, fills with zero to the left
>>         # divmod() gives minutes, seconds
>>         sf = "{:01d}:{:02d}".format(*divmod(t, 60))
>>         #print(sf)  # test
>>         time_str.set(sf)
>>         root.update()
>>         # delay one second
>>         time.sleep(1)
>> # start the GUI event loop
>> root.mainloop()
>>
>> Thanks for the help!
>>
>> Sincerely,
>>
>> Evan Sommer
>>
>

From alan.gauld at btinternet.com  Tue Dec 15 12:10:43 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 15 Dec 2015 17:10:43 +0000
Subject: [Tutor] Countdown Clock Programming Question
In-Reply-To: <CAPNRz81Pq_nFTS4A0B9fuvt=WjX8WSjDLai8J3t_tWOCR4-OiA@mail.gmail.com>
References: <CAPNRz83ooFrYkqq6E7SvOeJW6aaWQoO0H-OXh7nrCrU-XQ9+MQ@mail.gmail.com>
 <CAPNRz83Va1M4uESEqURKFJgnb=K-cE0p9pn23OuukYWg4Weq=A@mail.gmail.com>
 <CAPNRz81Pq_nFTS4A0B9fuvt=WjX8WSjDLai8J3t_tWOCR4-OiA@mail.gmail.com>
Message-ID: <n4phii$n42$1@ger.gmane.org>

On 15/12/15 14:18, Evan Sommer wrote:
> Hey there Alan!
> 
> So I tried some of your modifications, and they seem to be doing some
> pretty interesting things with the program. For some reason, now the
> program runs extremely fast, and doesn't now count down in one second
> intervals. I think this is a result of the root.after command. 

Yes, you are using it wrongly.
The root.after() function removes the need for your for loops.
You just call root after until the time reaches the point you are
interested in.

> def count_down(start, end):
>         root.after (1000, count_down)

You should be updating your display inside the count_down function.
This function, if done right, will get called each second. So every
second it will update your display until it reaches the end. So start
will be the value to display. stop will be the end value. When start==
stop the function will terminate.

It should look something like this:

def count_down(start,end):
    update display to show start
    if start > end:
       root.after(1000, lambda : count_down(start-1, end))


That pattern will simply count from start to end. If you want to change
colours etc then you need some more worjk.
But for now just try to get the counter working.


> for t in range(240, 120, -15):
>         # format as 2 digit integers, fills with zero to the left
>         # divmod() gives minutes, seconds
>         sf = "{:01d}:{:02d}".format(*divmod(t, 60))
>         #print(sf)  # test
>         time_str.set(sf)
>         root.update()
>         # delay one second
>         root.after (1, count_down)

Replace the whole loop with a call to

root.after(1, lambda : count_down(240,0))

And put the display code into the count_down method.

Here is a very simple program that just counts down the seconds.
You can build on that to do all the other display tweaks you
want.

############################
import tkinter as tk

def count_down(start,stop):
   display['text'] = str(start)
   if start > stop:
        top.after(1000, lambda : count_down(start-1,stop))

top = tk.Tk()
display = tk.Button(top,text="Press",
                    command = lambda: count_down(10,0))
display.pack()
top.mainloop()
############################

Notice that there are no for loops involved.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at btinternet.com  Tue Dec 15 12:31:06 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 15 Dec 2015 17:31:06 +0000
Subject: [Tutor] Countdown Clock Programming Question
In-Reply-To: <n4phii$n42$1@ger.gmane.org>
References: <CAPNRz83ooFrYkqq6E7SvOeJW6aaWQoO0H-OXh7nrCrU-XQ9+MQ@mail.gmail.com>
 <CAPNRz83Va1M4uESEqURKFJgnb=K-cE0p9pn23OuukYWg4Weq=A@mail.gmail.com>
 <CAPNRz81Pq_nFTS4A0B9fuvt=WjX8WSjDLai8J3t_tWOCR4-OiA@mail.gmail.com>
 <n4phii$n42$1@ger.gmane.org>
Message-ID: <n4pioq$c7b$1@ger.gmane.org>

On 15/12/15 17:10, Alan Gauld wrote:

> ############################
> import tkinter as tk
> 
> def count_down(start,stop):
>    display['text'] = str(start)
>    if start > stop:
>         top.after(1000, lambda : count_down(start-1,stop))
> 
> top = tk.Tk()
> display = tk.Button(top,text="Press",
>                     command = lambda: count_down(10,0))
> display.pack()
> top.mainloop()
> ############################

In case lambda confuses things, here is a version
using globals and no lambdas:

############################
import tkinter as tk

start = 10
stop = 0

def count_down():
    global start
    display['text'] = str(start)
    if start > stop:
        start -= 1
        top.after(1000, count_down)

top = tk.Tk()
display = tk.Button(top,text="Press",command = count_down)
display.pack()
top.mainloop()
############################


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From breamoreboy at yahoo.co.uk  Tue Dec 15 17:13:08 2015
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 15 Dec 2015 22:13:08 +0000
Subject: [Tutor] interface
In-Reply-To: <n4no99$lh4$1@ger.gmane.org>
References: <41d908e5c2dd5cc68875549bcb4c6f1a@sonic.net>
 <n4no99$lh4$1@ger.gmane.org>
Message-ID: <n4q39s$qag$1@ger.gmane.org>

On 15/12/2015 00:52, Alan Gauld wrote:
> On 14/12/15 21:48, Alex Kleider wrote:
>
>
> wxPython is slightly more complex but more powerful and
> looks more like the native UI on each platform. (There
> is also Dabo which is wxPython based but has an IDE with
> GUI builder and is very good for database oriented apps.)
>

wxPython still does not support Python 3, and it doesn't look as if this 
will happen any time soon.  In fairness this is due to Robin Dunn being 
tied up on paid work.

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

Mark Lawrence


From alan.gauld at btinternet.com  Tue Dec 15 19:06:39 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 16 Dec 2015 00:06:39 +0000
Subject: [Tutor] interface
In-Reply-To: <n4q39s$qag$1@ger.gmane.org>
References: <41d908e5c2dd5cc68875549bcb4c6f1a@sonic.net>
 <n4no99$lh4$1@ger.gmane.org> <n4q39s$qag$1@ger.gmane.org>
Message-ID: <n4q9uf$suh$1@ger.gmane.org>

On 15/12/15 22:13, Mark Lawrence wrote:

> wxPython still does not support Python 3, and it doesn't look as if this 
> will happen any time soon.  In fairness this is due to Robin Dunn being 
> tied up on paid work.

That's a pity. Not least because it presumably means Dabo
is stuck on v2 too. Dabo is on my todo list of things to
investigate (aka play with :-).

Mind you I'm busy enough with Javascript/NodeJS and F# at
the moment!


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From kfh777 at earthlink.net  Wed Dec 16 14:37:18 2015
From: kfh777 at earthlink.net (Ken Hammer)
Date: Wed, 16 Dec 2015 14:37:18 -0500
Subject: [Tutor] Why does loop duplicate?
Message-ID: <E1a9Hsw-0002Sc-Cp@elasmtp-mealy.atl.sa.earthlink.net>

Intent is to print "Jack, Kack, ...." with "O" and "Q" delivering a longer suffix.  Instead, I get the printout shown with duplicates and a second deviation with "O" and "Q" as shown.
Why?  IDLE and Shell are Python 2.5.4 running on Windows 8.1.

prefixes = 'JKLMNOPQ'   ###FAILS WITH REPEATS
suffix = 'ack'
suffixb= 'uack'

for letter in prefixes:
    if letter == "O":
        print letter + suffixb
    if letter == "Q":
        print letter + suffixb
    else:
        print letter + suffix

>>> 
Jack
Jack
Kack
Kack
Lack
Lack
Mack
Mack
Nack
Nack
Ouack
Oack
Oack
Pack
Pack
Quack
Qack
>>> 

Thanks,  Ken Hammer


From breamoreboy at yahoo.co.uk  Wed Dec 16 16:50:16 2015
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Wed, 16 Dec 2015 21:50:16 +0000
Subject: [Tutor] Why does loop duplicate?
In-Reply-To: <E1a9Hsw-0002Sc-Cp@elasmtp-mealy.atl.sa.earthlink.net>
References: <E1a9Hsw-0002Sc-Cp@elasmtp-mealy.atl.sa.earthlink.net>
Message-ID: <n4smb0$1d7$1@ger.gmane.org>

On 16/12/2015 19:37, Ken Hammer wrote:
> Intent is to print "Jack, Kack, ...." with "O" and "Q" delivering a longer suffix.  Instead, I get the printout shown with duplicates and a second deviation with "O" and "Q" as shown.
> Why?

That's what you've told the code to do :)

>
> prefixes = 'JKLMNOPQ'   ###FAILS WITH REPEATS

### OH NO IT DOESN'T - nothing personal but it's pantomine season in the 
UK :)

> suffix = 'ack'
> suffixb= 'uack'
>
> for letter in prefixes:
>      if letter == "O":
>          print letter + suffixb
>      if letter == "Q":
>          print letter + suffixb
>      else:
>          print letter + suffix
>

You test for "O", but then follow with a test for "Q" and an else 
clause.  You could write :-

elif letter == "Q"

but the cleanest way of doing this is:-

for letter in prefixes:
     if letter in ("O", "Q"):
         print letter + suffixb
     else:
         print letter + suffix

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

Mark Lawrence


From steve at pearwood.info  Wed Dec 16 17:58:21 2015
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 17 Dec 2015 09:58:21 +1100
Subject: [Tutor] Why does loop duplicate?
In-Reply-To: <E1a9Hsw-0002Sc-Cp@elasmtp-mealy.atl.sa.earthlink.net>
References: <E1a9Hsw-0002Sc-Cp@elasmtp-mealy.atl.sa.earthlink.net>
Message-ID: <20151216225820.GA1609@ando.pearwood.info>

On Wed, Dec 16, 2015 at 02:37:18PM -0500, Ken Hammer wrote:

> Intent is to print "Jack, Kack, ...." with "O" and "Q" delivering a 
> longer suffix.  Instead, I get the printout shown with duplicates and 
> a second deviation with "O" and "Q" as shown. Why?

Are you absolutely sure about that? When I run your code, I don't get 
any duplicates:


prefixes = 'JKLMNOPQ'   ###FAILS WITH REPEATS
suffix = 'ack'
suffixb= 'uack'
 
for letter in prefixes:
    if letter == "O":
        print letter + suffixb
    if letter == "Q":
        print letter + suffixb
    else:
        print letter + suffix

Output is:

Jack
Kack
Lack
Mack
Nack
Ouack
Oack
Pack
Quack


If you are getting duplicate lines, you must be running code that is 
different from the code you posted to us. We cannot help you with code 
we can't see.

As far as the code shown, look carefully at the code inside the 
for-loop:

    if letter == "O":
        print letter + suffixb
    if letter == "Q":
        print letter + suffixb
    else:
        print letter + suffix


The first test checks to see if the letter is "O", and if so, it prints 
"Ouack". Then, *regardless* of whether it just printed "Ouack" or not, 
it then does a second test, for "Q". Since Q is not O, it then prints 
"Oack".

No other letter gets treated that way.

Instead, you should change the second "if" to an "elif" (else if). Or 
better still:

    if letter == "O" or letter == "Q":
        print letter + suffixb
    else:
        print letter + suffix


which can be simplified even more to:

    if letter in ("O", "Q"):
        print letter + suffixb
    else:
        print letter + suffix



-- 
Steve

From robertvstepp at gmail.com  Wed Dec 16 20:42:06 2015
From: robertvstepp at gmail.com (boB Stepp)
Date: Wed, 16 Dec 2015 19:42:06 -0600
Subject: [Tutor] interface
In-Reply-To: <fc616a945551ae356144a50e579d1e56@sonic.net>
References: <41d908e5c2dd5cc68875549bcb4c6f1a@sonic.net>
 <n4no99$lh4$1@ger.gmane.org>
 <fc616a945551ae356144a50e579d1e56@sonic.net>
Message-ID: <CANDiX9JBs3-Gz4p2NAFCgdserQh-6v9K_xWTJPcS0HHCFaN2hA@mail.gmail.com>

On Mon, Dec 14, 2015 at 10:08 PM, Alex Kleider <akleider at sonic.net> wrote:
> Thank you, gentlemen (Alan, Ben, Mark,) for your advice.
> The consensus seems to be in favour of tkinter
> so I'll head in that direction.

If you are into books, "Programming Python, 4th ed." by Mark Lutz, has
an extensive section on tkinter (Alan had pointed this out to me, and
I have found Lutz's coverage very helpful).  Plus the book (very
thick!) has lots of other goodies.  Also, the now old book, "Python
and Tkinter Programming" by John E. Grayson is just about Tkinter
(with a capital "T") as it is copyrighted 2000.  Despite this I think
it is still quite useful even if you are working in Python 3 as, as
far as I can tell, t/Tkinter has not changed substantially in how the
coding goes.

-- 
boB

From alan.gauld at btinternet.com  Thu Dec 17 04:16:15 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 17 Dec 2015 09:16:15 +0000
Subject: [Tutor] Why does loop duplicate?
In-Reply-To: <E1a9Hsw-0002Sc-Cp@elasmtp-mealy.atl.sa.earthlink.net>
References: <E1a9Hsw-0002Sc-Cp@elasmtp-mealy.atl.sa.earthlink.net>
Message-ID: <n4tugv$1sd$1@ger.gmane.org>

On 16/12/15 19:37, Ken Hammer wrote:
>...  IDLE and Shell are Python 2.5.4 running on Windows 8.1.

How exactly are you running this?
Have you typed the code into a separate file using IDLE and then
run it via the Run menu?  Or are you importing the module at
the >>> prompt? Or are you typing it into the interactive
shell window? Or something else?

The reason I ask is that I don't get repeats, so either you
are running different code - possibly because of importing
it and then changing it but not reimporting - or the way
you run it is somehow causing the phenomenon.

> prefixes = 'JKLMNOPQ'   ###FAILS WITH REPEATS
> suffix = 'ack'
> suffixb= 'uack'
> 
> for letter in prefixes:
>     if letter == "O":
>         print letter + suffixb
>     if letter == "Q":
>         print letter + suffixb
>     else:
>         print letter + suffix
> 

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From sunil.techspk at gmail.com  Thu Dec 17 06:48:26 2015
From: sunil.techspk at gmail.com (Sunil Tech)
Date: Thu, 17 Dec 2015 17:18:26 +0530
Subject: [Tutor] Need to call a custom/magic method on calling of every
 Class methods
Message-ID: <CAExJxTM56wzmaz6udp2h4NcOF_mgT-1k7XisiVcB3SWZFLmvdA@mail.gmail.com>

Hi Tutor,

I am searching for any magic method/or any method that calls on every
calling of the Class methods.

for example:

Class A(object):
    def one(self):
        return

    def two(self):
        return

I need a method that prints which method is called in this class.
I am aware of __call__() but this is called only once when the Class is
called
and decorators. This is need to placed on every method.

c = A()
c()  # __call__ method is called.

Is there any magic method that is auto called on every call of these Class
Methods?



Thanks,
Sunil. G

From steve at pearwood.info  Thu Dec 17 08:33:21 2015
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 18 Dec 2015 00:33:21 +1100
Subject: [Tutor] Need to call a custom/magic method on calling of every
 Class methods
In-Reply-To: <CAExJxTM56wzmaz6udp2h4NcOF_mgT-1k7XisiVcB3SWZFLmvdA@mail.gmail.com>
References: <CAExJxTM56wzmaz6udp2h4NcOF_mgT-1k7XisiVcB3SWZFLmvdA@mail.gmail.com>
Message-ID: <20151217133320.GE1609@ando.pearwood.info>

On Thu, Dec 17, 2015 at 05:18:26PM +0530, Sunil Tech wrote:
> Hi Tutor,
> 
> I am searching for any magic method/or any method that calls on every
> calling of the Class methods.
[...]
> Is there any magic method that is auto called on every call of these Class
> Methods?

No, not really, but you can get *close* to what you want. You can't 
intercept *calling* the methods, but you can intercept the attribute 
lookup:


class A(object):
    def __getattribute__(self, name):
        attr = super(A, self).__getattribute__(name)
        if callable(attr):
            print(name)
        return attr
    def one(self):
        return 1
    def two(self):
        return 2


But beware that this will slow down all attribute access.

This is possibly the simplest solution. Perhaps a better solution would 
be to create a custom Method descriptor, and then modify the class to 
use this descriptor instead of standard methods. But this is much 
more work.



-- 
Steve

From sunil.techspk at gmail.com  Thu Dec 17 09:36:10 2015
From: sunil.techspk at gmail.com (Sunil Tech)
Date: Thu, 17 Dec 2015 20:06:10 +0530
Subject: [Tutor] Need to call a custom/magic method on calling of every
 Class methods
In-Reply-To: <20151217133320.GE1609@ando.pearwood.info>
References: <CAExJxTM56wzmaz6udp2h4NcOF_mgT-1k7XisiVcB3SWZFLmvdA@mail.gmail.com>
 <20151217133320.GE1609@ando.pearwood.info>
Message-ID: <CAExJxTNRkGNEDWCsefTeZCzKBW6gwF_idKDzynr5B_M4s6b9Og@mail.gmail.com>

Oh!

Thank you so much Steven for the reply.

On Thu, Dec 17, 2015 at 7:03 PM, Steven D'Aprano <steve at pearwood.info>
wrote:

> On Thu, Dec 17, 2015 at 05:18:26PM +0530, Sunil Tech wrote:
> > Hi Tutor,
> >
> > I am searching for any magic method/or any method that calls on every
> > calling of the Class methods.
> [...]
> > Is there any magic method that is auto called on every call of these
> Class
> > Methods?
>
> No, not really, but you can get *close* to what you want. You can't
> intercept *calling* the methods, but you can intercept the attribute
> lookup:
>
>
> class A(object):
>     def __getattribute__(self, name):
>         attr = super(A, self).__getattribute__(name)
>         if callable(attr):
>             print(name)
>         return attr
>     def one(self):
>         return 1
>     def two(self):
>         return 2
>
>
> But beware that this will slow down all attribute access.
>
> This is possibly the simplest solution. Perhaps a better solution would
> be to create a custom Method descriptor, and then modify the class to
> use this descriptor instead of standard methods. But this is much
> more work.
>
>
>
> --
> Steve
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From petermcfarlane4 at gmail.com  Thu Dec 17 13:06:29 2015
From: petermcfarlane4 at gmail.com (peter mcfarlane)
Date: Thu, 17 Dec 2015 18:06:29 +0000
Subject: [Tutor] Fwd: Kivy Install
In-Reply-To: <CAGOURkFDk9=gZQOy85c4173t6_b4m8S2wKR5QzrHCYv4cJAsKw@mail.gmail.com>
References: <CAGOURkFDk9=gZQOy85c4173t6_b4m8S2wKR5QzrHCYv4cJAsKw@mail.gmail.com>
Message-ID: <CAGOURkHso2gdczsx3g0qjGJk1KJ9EoYjRTgg9fVe69UdaPBZKA@mail.gmail.com>

Hi,
     I don't know if this is the correct forum, I am new to Python and
trying to install Kivy.  I keep getting the following error message.
Can you help?

thanks,
pete




pip install --user Kivy


Collecting Kivy
  Using cached Kivy-1.9.0.tar.gz
Requirement already satisfied (use --upgrade to upgrade):
Kivy-Garden==0.1.1 in c:\python27\lib\site-packages (from Kivy)
Requirement already satisfied (use --upgrade to upgrade): requests in
c:\python27\lib\site-packages (from Kivy-Garden==0.1.1->Kivy)
Building wheels for collected packages: Kivy
  Running setup.py bdist_wheel for Kivy
  Complete output from command C:\Python27\python.exe -c "import
setuptools;__file__='C:\\Users\\edge\\AppData\\Local\\Temp\\pycharm-packaging0.tmp\\Kivy\\setup.py';exec(compile(open(__file__).read().replace('\r\n',
'\n'), __file__, 'exec'))" bdist_wheel -d
c:\users\edge\appdata\local\temp\tmps896gmpip-wheel-:
  [INFO              ] [Logger      ] Record log in
C:\Users\edge\.kivy\logs\kivy_15-12-17_35.txt
  [INFO              ] [Kivy        ] v1.9.0
  [INFO              ] [Python      ] v2.7.11 (v2.7.11:6d1b6a68f775, Dec  5
2015, 20:32:19) [MSC v.1500 32 bit (Intel)]

  Detected Cython version 0.21.2
  Windows platform detected, force GLEW usage.
  Using this graphics system: OpenGL
  WARNING: A problem occured while running pkg-config --libs --cflags
gstreamer-1.0 (code 1)

  'pkg-config' is not recognized as an internal or external command,
  operable program or batch file.


  WARNING: A problem occured while running pkg-config --libs --cflags sdl2
SDL2_ttf SDL2_image SDL2_mixer (code 1)

  'pkg-config' is not recognized as an internal or external command,
  operable program or batch file.


  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib.win32-2.7
  creating build\lib.win32-2.7\kivy
  copying kivy\animation.py -> build\lib.win32-2.7\kivy
  copying kivy\app.py -> build\lib.win32-2.7\kivy
  copying kivy\atlas.py -> build\lib.win32-2.7\kivy
  copying kivy\base.py -> build\lib.win32-2.7\kivy
  copying kivy\cache.py -> build\lib.win32-2.7\kivy
  copying kivy\clock.py -> build\lib.win32-2.7\kivy
  copying kivy\compat.py -> build\lib.win32-2.7\kivy
  copying kivy\config.py -> build\lib.win32-2.7\kivy
  copying kivy\context.py -> build\lib.win32-2.7\kivy
  copying kivy\event.py -> build\lib.win32-2.7\kivy
  copying kivy\factory.py -> build\lib.win32-2.7\kivy
  copying kivy\factory_registers.py -> build\lib.win32-2.7\kivy
  copying kivy\geometry.py -> build\lib.win32-2.7\kivy
  copying kivy\gesture.py -> build\lib.win32-2.7\kivy
  copying kivy\interactive.py -> build\lib.win32-2.7\kivy
  copying kivy\lang.py -> build\lib.win32-2.7\kivy
  copying kivy\loader.py -> build\lib.win32-2.7\kivy
  copying kivy\logger.py -> build\lib.win32-2.7\kivy
  copying kivy\metrics.py -> build\lib.win32-2.7\kivy
  copying kivy\multistroke.py -> build\lib.win32-2.7\kivy
  copying kivy\parser.py -> build\lib.win32-2.7\kivy
  copying kivy\resources.py -> build\lib.win32-2.7\kivy
  copying kivy\support.py -> build\lib.win32-2.7\kivy
  copying kivy\utils.py -> build\lib.win32-2.7\kivy
  copying kivy\vector.py -> build\lib.win32-2.7\kivy
  copying kivy\weakmethod.py -> build\lib.win32-2.7\kivy
  copying kivy\__init__.py -> build\lib.win32-2.7\kivy
  creating build\lib.win32-2.7\kivy\adapters
  copying kivy\adapters\adapter.py -> build\lib.win32-2.7\kivy\adapters
  copying kivy\adapters\args_converters.py ->
build\lib.win32-2.7\kivy\adapters
  copying kivy\adapters\dictadapter.py -> build\lib.win32-2.7\kivy\adapters
  copying kivy\adapters\listadapter.py -> build\lib.win32-2.7\kivy\adapters
  copying kivy\adapters\models.py -> build\lib.win32-2.7\kivy\adapters
  copying kivy\adapters\simplelistadapter.py ->
build\lib.win32-2.7\kivy\adapters
  copying kivy\adapters\__init__.py -> build\lib.win32-2.7\kivy\adapters
  creating build\lib.win32-2.7\kivy\core
  copying kivy\core\__init__.py -> build\lib.win32-2.7\kivy\core
  creating build\lib.win32-2.7\kivy\core\audio
  copying kivy\core\audio\audio_ffpyplayer.py ->
build\lib.win32-2.7\kivy\core\audio
  copying kivy\core\audio\audio_gi.py -> build\lib.win32-2.7\kivy\core\audio
  copying kivy\core\audio\audio_gstplayer.py ->
build\lib.win32-2.7\kivy\core\audio
  copying kivy\core\audio\audio_pygame.py ->
build\lib.win32-2.7\kivy\core\audio
  copying kivy\core\audio\audio_pygst.py ->
build\lib.win32-2.7\kivy\core\audio
  copying kivy\core\audio\__init__.py -> build\lib.win32-2.7\kivy\core\audio
  creating build\lib.win32-2.7\kivy\core\camera
  copying kivy\core\camera\camera_gi.py ->
build\lib.win32-2.7\kivy\core\camera
  copying kivy\core\camera\camera_opencv.py ->
build\lib.win32-2.7\kivy\core\camera
  copying kivy\core\camera\camera_pygst.py ->
build\lib.win32-2.7\kivy\core\camera
  copying kivy\core\camera\camera_videocapture.py ->
build\lib.win32-2.7\kivy\core\camera
  copying kivy\core\camera\__init__.py ->
build\lib.win32-2.7\kivy\core\camera
  creating build\lib.win32-2.7\kivy\core\clipboard
  copying kivy\core\clipboard\clipboard_android.py ->
build\lib.win32-2.7\kivy\core\clipboard
  copying kivy\core\clipboard\clipboard_dbusklipper.py ->
build\lib.win32-2.7\kivy\core\clipboard
  copying kivy\core\clipboard\clipboard_dummy.py ->
build\lib.win32-2.7\kivy\core\clipboard
  copying kivy\core\clipboard\clipboard_gtk3.py ->
build\lib.win32-2.7\kivy\core\clipboard
  copying kivy\core\clipboard\clipboard_nspaste.py ->
build\lib.win32-2.7\kivy\core\clipboard
  copying kivy\core\clipboard\clipboard_pygame.py ->
build\lib.win32-2.7\kivy\core\clipboard
  copying kivy\core\clipboard\clipboard_sdl2.py ->
build\lib.win32-2.7\kivy\core\clipboard
  copying kivy\core\clipboard\clipboard_winctypes.py ->
build\lib.win32-2.7\kivy\core\clipboard
  copying kivy\core\clipboard\clipboard_xsel.py ->
build\lib.win32-2.7\kivy\core\clipboard
  copying kivy\core\clipboard\__init__.py ->
build\lib.win32-2.7\kivy\core\clipboard
  creating build\lib.win32-2.7\kivy\core\image
  copying kivy\core\image\img_dds.py -> build\lib.win32-2.7\kivy\core\image
  copying kivy\core\image\img_ffpyplayer.py ->
build\lib.win32-2.7\kivy\core\image
  copying kivy\core\image\img_gif.py -> build\lib.win32-2.7\kivy\core\image
  copying kivy\core\image\img_pil.py -> build\lib.win32-2.7\kivy\core\image
  copying kivy\core\image\img_pygame.py ->
build\lib.win32-2.7\kivy\core\image
  copying kivy\core\image\img_sdl2.py -> build\lib.win32-2.7\kivy\core\image
  copying kivy\core\image\img_tex.py -> build\lib.win32-2.7\kivy\core\image
  copying kivy\core\image\__init__.py -> build\lib.win32-2.7\kivy\core\image
  creating build\lib.win32-2.7\kivy\core\gl
  copying kivy\core\gl\__init__.py -> build\lib.win32-2.7\kivy\core\gl
  creating build\lib.win32-2.7\kivy\core\spelling
  copying kivy\core\spelling\spelling_enchant.py ->
build\lib.win32-2.7\kivy\core\spelling
  copying kivy\core\spelling\spelling_osxappkit.py ->
build\lib.win32-2.7\kivy\core\spelling
  copying kivy\core\spelling\__init__.py ->
build\lib.win32-2.7\kivy\core\spelling
  creating build\lib.win32-2.7\kivy\core\text
  copying kivy\core\text\markup.py -> build\lib.win32-2.7\kivy\core\text
  copying kivy\core\text\text_pil.py -> build\lib.win32-2.7\kivy\core\text
  copying kivy\core\text\text_pygame.py ->
build\lib.win32-2.7\kivy\core\text
  copying kivy\core\text\text_sdl2.py -> build\lib.win32-2.7\kivy\core\text
  copying kivy\core\text\__init__.py -> build\lib.win32-2.7\kivy\core\text
  creating build\lib.win32-2.7\kivy\core\video
  copying kivy\core\video\video_ffmpeg.py ->
build\lib.win32-2.7\kivy\core\video
  copying kivy\core\video\video_ffpyplayer.py ->
build\lib.win32-2.7\kivy\core\video
  copying kivy\core\video\video_gi.py -> build\lib.win32-2.7\kivy\core\video
  copying kivy\core\video\video_gstplayer.py ->
build\lib.win32-2.7\kivy\core\video
  copying kivy\core\video\video_null.py ->
build\lib.win32-2.7\kivy\core\video
  copying kivy\core\video\video_pyglet.py ->
build\lib.win32-2.7\kivy\core\video
  copying kivy\core\video\video_pygst.py ->
build\lib.win32-2.7\kivy\core\video
  copying kivy\core\video\__init__.py -> build\lib.win32-2.7\kivy\core\video
  creating build\lib.win32-2.7\kivy\core\window
  copying kivy\core\window\window_egl_rpi.py ->
build\lib.win32-2.7\kivy\core\window
  copying kivy\core\window\window_pygame.py ->
build\lib.win32-2.7\kivy\core\window
  copying kivy\core\window\window_sdl2.py ->
build\lib.win32-2.7\kivy\core\window
  copying kivy\core\window\__init__.py ->
build\lib.win32-2.7\kivy\core\window
  creating build\lib.win32-2.7\kivy\effects
  copying kivy\effects\dampedscroll.py -> build\lib.win32-2.7\kivy\effects
  copying kivy\effects\kinetic.py -> build\lib.win32-2.7\kivy\effects
  copying kivy\effects\opacityscroll.py -> build\lib.win32-2.7\kivy\effects
  copying kivy\effects\scroll.py -> build\lib.win32-2.7\kivy\effects
  copying kivy\effects\__init__.py -> build\lib.win32-2.7\kivy\effects
  creating build\lib.win32-2.7\kivy\ext
  copying kivy\ext\__init__.py -> build\lib.win32-2.7\kivy\ext
  creating build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\__init__.py -> build\lib.win32-2.7\kivy\graphics
  creating build\lib.win32-2.7\kivy\garden
  copying kivy\garden\__init__.py -> build\lib.win32-2.7\kivy\garden
  creating build\lib.win32-2.7\kivy\input
  copying kivy\input\factory.py -> build\lib.win32-2.7\kivy\input
  copying kivy\input\motionevent.py -> build\lib.win32-2.7\kivy\input
  copying kivy\input\provider.py -> build\lib.win32-2.7\kivy\input
  copying kivy\input\recorder.py -> build\lib.win32-2.7\kivy\input
  copying kivy\input\shape.py -> build\lib.win32-2.7\kivy\input
  copying kivy\input\__init__.py -> build\lib.win32-2.7\kivy\input
  creating build\lib.win32-2.7\kivy\input\postproc
  copying kivy\input\postproc\calibration.py ->
build\lib.win32-2.7\kivy\input\postproc
  copying kivy\input\postproc\dejitter.py ->
build\lib.win32-2.7\kivy\input\postproc
  copying kivy\input\postproc\doubletap.py ->
build\lib.win32-2.7\kivy\input\postproc
  copying kivy\input\postproc\ignorelist.py ->
build\lib.win32-2.7\kivy\input\postproc
  copying kivy\input\postproc\retaintouch.py ->
build\lib.win32-2.7\kivy\input\postproc
  copying kivy\input\postproc\tripletap.py ->
build\lib.win32-2.7\kivy\input\postproc
  copying kivy\input\postproc\__init__.py ->
build\lib.win32-2.7\kivy\input\postproc
  creating build\lib.win32-2.7\kivy\input\providers
  copying kivy\input\providers\androidjoystick.py ->
build\lib.win32-2.7\kivy\input\providers
  copying kivy\input\providers\hidinput.py ->
build\lib.win32-2.7\kivy\input\providers
  copying kivy\input\providers\leapfinger.py ->
build\lib.win32-2.7\kivy\input\providers
  copying kivy\input\providers\linuxwacom.py ->
build\lib.win32-2.7\kivy\input\providers
  copying kivy\input\providers\mactouch.py ->
build\lib.win32-2.7\kivy\input\providers
  copying kivy\input\providers\mouse.py ->
build\lib.win32-2.7\kivy\input\providers
  copying kivy\input\providers\mtdev.py ->
build\lib.win32-2.7\kivy\input\providers
  copying kivy\input\providers\probesysfs.py ->
build\lib.win32-2.7\kivy\input\providers
  copying kivy\input\providers\tuio.py ->
build\lib.win32-2.7\kivy\input\providers
  copying kivy\input\providers\wm_common.py ->
build\lib.win32-2.7\kivy\input\providers
  copying kivy\input\providers\wm_pen.py ->
build\lib.win32-2.7\kivy\input\providers
  copying kivy\input\providers\wm_touch.py ->
build\lib.win32-2.7\kivy\input\providers
  copying kivy\input\providers\__init__.py ->
build\lib.win32-2.7\kivy\input\providers
  creating build\lib.win32-2.7\kivy\lib
  copying kivy\lib\ddsfile.py -> build\lib.win32-2.7\kivy\lib
  copying kivy\lib\mtdev.py -> build\lib.win32-2.7\kivy\lib
  copying kivy\lib\__init__.py -> build\lib.win32-2.7\kivy\lib
  creating build\lib.win32-2.7\kivy\lib\osc
  copying kivy\lib\osc\OSC.py -> build\lib.win32-2.7\kivy\lib\osc
  copying kivy\lib\osc\oscAPI.py -> build\lib.win32-2.7\kivy\lib\osc
  copying kivy\lib\osc\__init__.py -> build\lib.win32-2.7\kivy\lib\osc
  creating build\lib.win32-2.7\kivy\lib\gstplayer
  copying kivy\lib\gstplayer\__init__.py ->
build\lib.win32-2.7\kivy\lib\gstplayer
  creating build\lib.win32-2.7\kivy\lib\vidcore_lite
  copying kivy\lib\vidcore_lite\__init__.py ->
build\lib.win32-2.7\kivy\lib\vidcore_lite
  creating build\lib.win32-2.7\kivy\modules
  copying kivy\modules\inspector.py -> build\lib.win32-2.7\kivy\modules
  copying kivy\modules\keybinding.py -> build\lib.win32-2.7\kivy\modules
  copying kivy\modules\monitor.py -> build\lib.win32-2.7\kivy\modules
  copying kivy\modules\recorder.py -> build\lib.win32-2.7\kivy\modules
  copying kivy\modules\screen.py -> build\lib.win32-2.7\kivy\modules
  copying kivy\modules\touchring.py -> build\lib.win32-2.7\kivy\modules
  copying kivy\modules\webdebugger.py -> build\lib.win32-2.7\kivy\modules
  copying kivy\modules\_webdebugger.py -> build\lib.win32-2.7\kivy\modules
  copying kivy\modules\__init__.py -> build\lib.win32-2.7\kivy\modules
  creating build\lib.win32-2.7\kivy\network
  copying kivy\network\urlrequest.py -> build\lib.win32-2.7\kivy\network
  copying kivy\network\__init__.py -> build\lib.win32-2.7\kivy\network
  creating build\lib.win32-2.7\kivy\storage
  copying kivy\storage\dictstore.py -> build\lib.win32-2.7\kivy\storage
  copying kivy\storage\jsonstore.py -> build\lib.win32-2.7\kivy\storage
  copying kivy\storage\redisstore.py -> build\lib.win32-2.7\kivy\storage
  copying kivy\storage\__init__.py -> build\lib.win32-2.7\kivy\storage
  creating build\lib.win32-2.7\kivy\tools
  copying kivy\tools\benchmark.py -> build\lib.win32-2.7\kivy\tools
  copying kivy\tools\generate-icons.py -> build\lib.win32-2.7\kivy\tools
  copying kivy\tools\report.py -> build\lib.win32-2.7\kivy\tools
  copying kivy\tools\stub-gl-debug.py -> build\lib.win32-2.7\kivy\tools
  copying kivy\tools\texturecompress.py -> build\lib.win32-2.7\kivy\tools
  copying kivy\tools\__init__.py -> build\lib.win32-2.7\kivy\tools
  creating build\lib.win32-2.7\kivy\tools\packaging
  copying kivy\tools\packaging\factory.py ->
build\lib.win32-2.7\kivy\tools\packaging
  copying kivy\tools\packaging\__init__.py ->
build\lib.win32-2.7\kivy\tools\packaging
  creating build\lib.win32-2.7\kivy\tools\packaging\pyinstaller_hooks
  copying kivy\tools\packaging\pyinstaller_hooks\hook-kivy.py ->
build\lib.win32-2.7\kivy\tools\packaging\pyinstaller_hooks
  copying kivy\tools\packaging\pyinstaller_hooks\rt-hook-kivy.py ->
build\lib.win32-2.7\kivy\tools\packaging\pyinstaller_hooks
  copying kivy\tools\packaging\pyinstaller_hooks\__init__.py ->
build\lib.win32-2.7\kivy\tools\packaging\pyinstaller_hooks
  creating build\lib.win32-2.7\kivy\tools\highlight
  copying kivy\tools\highlight\__init__.py ->
build\lib.win32-2.7\kivy\tools\highlight
  creating build\lib.win32-2.7\kivy\extras
  copying kivy\extras\highlight.py -> build\lib.win32-2.7\kivy\extras
  copying kivy\extras\__init__.py -> build\lib.win32-2.7\kivy\extras
  creating build\lib.win32-2.7\kivy\tools\extensions
  copying kivy\tools\extensions\make-kivyext.py ->
build\lib.win32-2.7\kivy\tools\extensions
  copying kivy\tools\extensions\__init__.py ->
build\lib.win32-2.7\kivy\tools\extensions
  creating build\lib.win32-2.7\kivy\uix
  copying kivy\uix\abstractview.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\accordion.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\actionbar.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\anchorlayout.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\behaviors.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\boxlayout.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\bubble.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\button.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\camera.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\carousel.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\checkbox.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\codeinput.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\colorpicker.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\dropdown.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\effectwidget.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\filechooser.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\floatlayout.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\gesturesurface.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\gridlayout.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\image.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\label.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\layout.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\listview.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\modalview.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\pagelayout.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\popup.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\progressbar.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\relativelayout.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\rst.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\sandbox.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\scatter.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\scatterlayout.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\screenmanager.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\scrollview.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\selectableview.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\settings.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\slider.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\spinner.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\splitter.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\stacklayout.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\stencilview.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\switch.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\tabbedpanel.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\textinput.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\togglebutton.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\treeview.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\video.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\videoplayer.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\vkeyboard.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\widget.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\uix\__init__.py -> build\lib.win32-2.7\kivy\uix
  copying kivy\properties.pxd -> build\lib.win32-2.7\kivy
  copying kivy\_event.pxd -> build\lib.win32-2.7\kivy
  copying kivy\core\text\text_layout.pxd ->
build\lib.win32-2.7\kivy\core\text
  copying kivy\graphics\buffer.pxd -> build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\compiler.pxd -> build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\context.pxd -> build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\context_instructions.pxd ->
build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\c_opengl.pxd -> build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\c_opengl_debug.pxd ->
build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\fbo.pxd -> build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\instructions.pxd ->
build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\opengl_utils.pxd ->
build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\shader.pxd -> build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\stencil_instructions.pxd ->
build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\svg.pxd -> build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\tesselator.pxd -> build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\texture.pxd -> build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\transformation.pxd ->
build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\vbo.pxd -> build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\vertex.pxd -> build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\vertex_instructions.pxd ->
build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\common.pxi -> build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\img_tools.pxi -> build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\opcodes.pxi -> build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\opengl_utils_def.pxi ->
build\lib.win32-2.7\kivy\graphics
  copying kivy\graphics\vertex_instructions_line.pxi ->
build\lib.win32-2.7\kivy\graphics
  copying kivy\lib\vidcore_lite\bcm.pxd ->
build\lib.win32-2.7\kivy\lib\vidcore_lite
  creating build\lib.win32-2.7\kivy\data
  copying kivy\data\style.kv -> build\lib.win32-2.7\kivy\data
  copying kivy\data\settings_kivy.json -> build\lib.win32-2.7\kivy\data
  creating build\lib.win32-2.7\kivy\data\fonts
  copying kivy\data\fonts\DejaVuSans.ttf ->
build\lib.win32-2.7\kivy\data\fonts
  copying kivy\data\fonts\DroidSans-Bold.ttf ->
build\lib.win32-2.7\kivy\data\fonts
  copying kivy\data\fonts\DroidSans-BoldItalic.ttf ->
build\lib.win32-2.7\kivy\data\fonts
  copying kivy\data\fonts\DroidSans-Italic.ttf ->
build\lib.win32-2.7\kivy\data\fonts
  copying kivy\data\fonts\DroidSans.ttf ->
build\lib.win32-2.7\kivy\data\fonts
  copying kivy\data\fonts\DroidSansMono.ttf ->
build\lib.win32-2.7\kivy\data\fonts
  creating build\lib.win32-2.7\kivy\data\images
  copying kivy\data\images\defaulttheme-0.png ->
build\lib.win32-2.7\kivy\data\images
  copying kivy\data\images\testpattern.png ->
build\lib.win32-2.7\kivy\data\images
  copying kivy\data\images\background.jpg ->
build\lib.win32-2.7\kivy\data\images
  copying kivy\data\images\image-loading.gif ->
build\lib.win32-2.7\kivy\data\images
  copying kivy\data\images\defaulttheme.atlas ->
build\lib.win32-2.7\kivy\data\images
  creating build\lib.win32-2.7\kivy\data\keyboards
  copying kivy\data\keyboards\azerty.json ->
build\lib.win32-2.7\kivy\data\keyboards
  copying kivy\data\keyboards\de_CH.json ->
build\lib.win32-2.7\kivy\data\keyboards
  copying kivy\data\keyboards\en_US.json ->
build\lib.win32-2.7\kivy\data\keyboards
  copying kivy\data\keyboards\fr_CH.json ->
build\lib.win32-2.7\kivy\data\keyboards
  copying kivy\data\keyboards\qwerty.json ->
build\lib.win32-2.7\kivy\data\keyboards
  copying kivy\data\keyboards\qwertz.json ->
build\lib.win32-2.7\kivy\data\keyboards
  creating build\lib.win32-2.7\kivy\data\logo
  copying kivy\data\logo\kivy-icon-128.png ->
build\lib.win32-2.7\kivy\data\logo
  copying kivy\data\logo\kivy-icon-16.png ->
build\lib.win32-2.7\kivy\data\logo
  copying kivy\data\logo\kivy-icon-24.png ->
build\lib.win32-2.7\kivy\data\logo
  copying kivy\data\logo\kivy-icon-256.png ->
build\lib.win32-2.7\kivy\data\logo
  copying kivy\data\logo\kivy-icon-32.png ->
build\lib.win32-2.7\kivy\data\logo
  copying kivy\data\logo\kivy-icon-512.png ->
build\lib.win32-2.7\kivy\data\logo
  copying kivy\data\logo\kivy-icon-64.png ->
build\lib.win32-2.7\kivy\data\logo
  creating build\lib.win32-2.7\kivy\data\glsl
  copying kivy\data\glsl\default.png -> build\lib.win32-2.7\kivy\data\glsl
  copying kivy\data\glsl\default.vs -> build\lib.win32-2.7\kivy\data\glsl
  copying kivy\data\glsl\header.vs -> build\lib.win32-2.7\kivy\data\glsl
  copying kivy\data\glsl\default.fs -> build\lib.win32-2.7\kivy\data\glsl
  copying kivy\data\glsl\header.fs -> build\lib.win32-2.7\kivy\data\glsl
  copying kivy\tools\highlight\kivy.vim ->
build\lib.win32-2.7\kivy\tools\highlight
  copying kivy\tools\highlight\kivy-mode.el ->
build\lib.win32-2.7\kivy\tools\highlight
  copying kivy\tools\packaging\README.txt ->
build\lib.win32-2.7\kivy\tools\packaging
  creating build\lib.win32-2.7\kivy\tools\packaging\win32
  copying kivy\tools\packaging\win32\README.txt ->
build\lib.win32-2.7\kivy\tools\packaging\win32
  creating build\lib.win32-2.7\kivy\tools\packaging\osx
  copying kivy\tools\packaging\osx\Info.plist ->
build\lib.win32-2.7\kivy\tools\packaging\osx
  copying kivy\tools\packaging\osx\InfoPlist.strings ->
build\lib.win32-2.7\kivy\tools\packaging\osx
  copying kivy\tools\packaging\osx\kivy.sh ->
build\lib.win32-2.7\kivy\tools\packaging\osx
   warning: build_py: byte-compiling is disabled, skipping.

  running build_ext
  Build configuration is:
   * use_rpi = 0
   * use_opengl_es2 = 0
   * use_opengl_debug = 0
   * use_glew = 1
   * use_sdl2 = 0
   * use_ios = 0
   * use_mesagl = 0
   * use_x11 = 0
   * use_gstreamer = 0
   * use_avfoundation = 0
   * use_osx_frameworks = 0
   * debug = False
  Updated build\lib.win32-2.7\kivy\graphics\config.h
  Updated
C:\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy\graphics\config.h
  Updated build\lib.win32-2.7\kivy\graphics\config.pxi
  Updated
C:\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy\graphics\config.pxi
  Updated build\lib.win32-2.7\kivy\setupconfig.py
  Updated
C:\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy\setupconfig.py
  Detected compiler is msvc
  cythoning
C:\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy\graphics/opengl.pyx
to
C:\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy\graphics\opengl.c
  building 'kivy.graphics.opengl' extension
  creating build\temp.win32-2.7
  creating build\temp.win32-2.7\Release
  creating build\temp.win32-2.7\Release\Users
  creating build\temp.win32-2.7\Release\Users\edge
  creating build\temp.win32-2.7\Release\Users\edge\AppData
  creating build\temp.win32-2.7\Release\Users\edge\AppData\Local
  creating build\temp.win32-2.7\Release\Users\edge\AppData\Local\Temp
  creating
build\temp.win32-2.7\Release\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp
  creating
build\temp.win32-2.7\Release\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy
  creating
build\temp.win32-2.7\Release\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy
  creating
build\temp.win32-2.7\Release\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy\graphics
  C:\Users\edge\AppData\Local\Programs\Common\Microsoft\Visual C++ for
Python\9.0\VC\Bin\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG
-IC:\Python27\include -IC:\Python27\PC
/TcC:\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy\graphics\opengl.c
/Fobuild\temp.win32-2.7\Release\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy\graphics\opengl.obj
  opengl.c

c:\users\edge\appdata\local\temp\pycharm-packaging0.tmp\kivy\kivy\graphics\gl_redirect.h(8)
: fatal error C1083: Cannot open include file: 'GL/glew.h': No such file or
directory
   error: command
'C:\\Users\\edge\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++
for Python\\9.0\\VC\\Bin\\cl.exe' failed with exit status 2

  ----------------------------------------
Failed to build Kivy
Installing collected packages: Kivy
  Running setup.py install for Kivy
    Complete output from command C:\Python27\python.exe -c "import
setuptools,
tokenize;__file__='C:\\Users\\edge\\AppData\\Local\\Temp\\pycharm-packaging0.tmp\\Kivy\\setup.py';exec(compile(getattr(tokenize,
'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))"
install --record
c:\users\edge\appdata\local\temp\pip-qnjvsj-record\install-record.txt
--single-version-externally-managed --compile --user --prefix=:
    [INFO              ] [Logger      ] Record log in
C:\Users\edge\.kivy\logs\kivy_15-12-17_36.txt
    [INFO              ] [Kivy        ] v1.9.0
    [INFO              ] [Python      ] v2.7.11 (v2.7.11:6d1b6a68f775, Dec
 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)]

    Detected Cython version 0.21.2
    Windows platform detected, force GLEW usage.
    Using this graphics system: OpenGL
    WARNING: A problem occured while running pkg-config --libs --cflags
gstreamer-1.0 (code 1)

    'pkg-config' is not recognized as an internal or external command,
    operable program or batch file.


    WARNING: A problem occured while running pkg-config --libs --cflags
sdl2 SDL2_ttf SDL2_image SDL2_mixer (code 1)

    'pkg-config' is not recognized as an internal or external command,
    operable program or batch file.


    running install
    running build
    running build_py
     warning: build_py: byte-compiling is disabled, skipping.

    running build_ext
    Build configuration is:
     * use_rpi = 0
     * use_opengl_es2 = 0
     * use_opengl_debug = 0
     * use_glew = 1
     * use_sdl2 = 0
     * use_ios = 0
     * use_mesagl = 0
     * use_x11 = 0
     * use_gstreamer = 0
     * use_avfoundation = 0
     * use_osx_frameworks = 0
     * debug = False
    Detected compiler is msvc
    skipping
'C:\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy\graphics\opengl.c'
Cython extension (up-to-date)
    building 'kivy.graphics.opengl' extension
    C:\Users\edge\AppData\Local\Programs\Common\Microsoft\Visual C++ for
Python\9.0\VC\Bin\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG
-IC:\Python27\include -IC:\Python27\PC
/TcC:\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy\graphics\opengl.c
/Fobuild\temp.win32-2.7\Release\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy\graphics\opengl.obj
    opengl.c

c:\users\edge\appdata\local\temp\pycharm-packaging0.tmp\kivy\kivy\graphics\gl_redirect.h(8)
: fatal error C1083: Cannot open include file: 'GL/glew.h': No such file or
directory
     error: command
'C:\\Users\\edge\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++
for Python\\9.0\\VC\\Bin\\cl.exe' failed with exit status 2

    ----------------------------------------

  Failed building wheel for Kivy
Command "C:\Python27\python.exe -c "import setuptools,
tokenize;__file__='C:\\Users\\edge\\AppData\\Local\\Temp\\pycharm-packaging0.tmp\\Kivy\\setup.py';exec(compile(getattr(tokenize,
'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))"
install --record
c:\users\edge\appdata\local\temp\pip-qnjvsj-record\install-record.txt
--single-version-externally-managed --compile --user --prefix=" failed with
error code 1 in C:\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy

From wolfrage8765 at gmail.com  Thu Dec 17 17:35:05 2015
From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com)
Date: Thu, 17 Dec 2015 17:35:05 -0500
Subject: [Tutor] Fwd: Kivy Install
In-Reply-To: <CAGOURkHso2gdczsx3g0qjGJk1KJ9EoYjRTgg9fVe69UdaPBZKA@mail.gmail.com>
References: <CAGOURkFDk9=gZQOy85c4173t6_b4m8S2wKR5QzrHCYv4cJAsKw@mail.gmail.com>
 <CAGOURkHso2gdczsx3g0qjGJk1KJ9EoYjRTgg9fVe69UdaPBZKA@mail.gmail.com>
Message-ID: <CAOhNYvmiRq=vGucABO8YbgL_wBiX2GvKgvHjGa239LdJpqtVzg@mail.gmail.com>

 This is a general Python mailing list. For Kivy please reference:
https://groups.google.com/forum/#!forum/kivy-users
or find the developers on freenode IRC in #kivy
This is the official Kivy repository here:
https://github.com/kivy/kivy
The official Kivy site is here:
http://kivy.org/

But you are in luck I am a Kivy User too.
However I am a Linux OS user so your luck just became a little less.
For Windows I do not believe installing via Python's PIP is not
supported. However their are pre-built binaries for windows with
executable installers here:
http://kivy.org/#download

So what exactly are you trying to do? Install Kivy on your windows
machine for development or Install Kivy on other peoples computers
that use your software which is built on Kivy?

On Thu, Dec 17, 2015 at 1:06 PM, peter mcfarlane
<petermcfarlane4 at gmail.com> wrote:
> Hi,
>      I don't know if this is the correct forum, I am new to Python and
> trying to install Kivy.  I keep getting the following error message.
> Can you help?
>
> thanks,
> pete
>
>
>
>
> pip install --user Kivy
>
>
> Collecting Kivy
>   Using cached Kivy-1.9.0.tar.gz
> Requirement already satisfied (use --upgrade to upgrade):
> Kivy-Garden==0.1.1 in c:\python27\lib\site-packages (from Kivy)
> Requirement already satisfied (use --upgrade to upgrade): requests in
> c:\python27\lib\site-packages (from Kivy-Garden==0.1.1->Kivy)
> Building wheels for collected packages: Kivy
>   Running setup.py bdist_wheel for Kivy
>   Complete output from command C:\Python27\python.exe -c "import
> setuptools;__file__='C:\\Users\\edge\\AppData\\Local\\Temp\\pycharm-packaging0.tmp\\Kivy\\setup.py';exec(compile(open(__file__).read().replace('\r\n',
> '\n'), __file__, 'exec'))" bdist_wheel -d
> c:\users\edge\appdata\local\temp\tmps896gmpip-wheel-:
>   [INFO              ] [Logger      ] Record log in
> C:\Users\edge\.kivy\logs\kivy_15-12-17_35.txt
>   [INFO              ] [Kivy        ] v1.9.0
>   [INFO              ] [Python      ] v2.7.11 (v2.7.11:6d1b6a68f775, Dec  5
> 2015, 20:32:19) [MSC v.1500 32 bit (Intel)]
>
>   Detected Cython version 0.21.2
>   Windows platform detected, force GLEW usage.
>   Using this graphics system: OpenGL
>   WARNING: A problem occured while running pkg-config --libs --cflags
> gstreamer-1.0 (code 1)
>
>   'pkg-config' is not recognized as an internal or external command,
>   operable program or batch file.
>
>
>   WARNING: A problem occured while running pkg-config --libs --cflags sdl2
> SDL2_ttf SDL2_image SDL2_mixer (code 1)
>
>   'pkg-config' is not recognized as an internal or external command,
>   operable program or batch file.
>
>
>   running bdist_wheel
>   running build
>   running build_py
>   creating build
>   creating build\lib.win32-2.7
>   creating build\lib.win32-2.7\kivy
>   copying kivy\animation.py -> build\lib.win32-2.7\kivy
>   copying kivy\app.py -> build\lib.win32-2.7\kivy
>   copying kivy\atlas.py -> build\lib.win32-2.7\kivy
>   copying kivy\base.py -> build\lib.win32-2.7\kivy
>   copying kivy\cache.py -> build\lib.win32-2.7\kivy
>   copying kivy\clock.py -> build\lib.win32-2.7\kivy
>   copying kivy\compat.py -> build\lib.win32-2.7\kivy
>   copying kivy\config.py -> build\lib.win32-2.7\kivy
>   copying kivy\context.py -> build\lib.win32-2.7\kivy
>   copying kivy\event.py -> build\lib.win32-2.7\kivy
>   copying kivy\factory.py -> build\lib.win32-2.7\kivy
>   copying kivy\factory_registers.py -> build\lib.win32-2.7\kivy
>   copying kivy\geometry.py -> build\lib.win32-2.7\kivy
>   copying kivy\gesture.py -> build\lib.win32-2.7\kivy
>   copying kivy\interactive.py -> build\lib.win32-2.7\kivy
>   copying kivy\lang.py -> build\lib.win32-2.7\kivy
>   copying kivy\loader.py -> build\lib.win32-2.7\kivy
>   copying kivy\logger.py -> build\lib.win32-2.7\kivy
>   copying kivy\metrics.py -> build\lib.win32-2.7\kivy
>   copying kivy\multistroke.py -> build\lib.win32-2.7\kivy
>   copying kivy\parser.py -> build\lib.win32-2.7\kivy
>   copying kivy\resources.py -> build\lib.win32-2.7\kivy
>   copying kivy\support.py -> build\lib.win32-2.7\kivy
>   copying kivy\utils.py -> build\lib.win32-2.7\kivy
>   copying kivy\vector.py -> build\lib.win32-2.7\kivy
>   copying kivy\weakmethod.py -> build\lib.win32-2.7\kivy
>   copying kivy\__init__.py -> build\lib.win32-2.7\kivy
>   creating build\lib.win32-2.7\kivy\adapters
>   copying kivy\adapters\adapter.py -> build\lib.win32-2.7\kivy\adapters
>   copying kivy\adapters\args_converters.py ->
> build\lib.win32-2.7\kivy\adapters
>   copying kivy\adapters\dictadapter.py -> build\lib.win32-2.7\kivy\adapters
>   copying kivy\adapters\listadapter.py -> build\lib.win32-2.7\kivy\adapters
>   copying kivy\adapters\models.py -> build\lib.win32-2.7\kivy\adapters
>   copying kivy\adapters\simplelistadapter.py ->
> build\lib.win32-2.7\kivy\adapters
>   copying kivy\adapters\__init__.py -> build\lib.win32-2.7\kivy\adapters
>   creating build\lib.win32-2.7\kivy\core
>   copying kivy\core\__init__.py -> build\lib.win32-2.7\kivy\core
>   creating build\lib.win32-2.7\kivy\core\audio
>   copying kivy\core\audio\audio_ffpyplayer.py ->
> build\lib.win32-2.7\kivy\core\audio
>   copying kivy\core\audio\audio_gi.py -> build\lib.win32-2.7\kivy\core\audio
>   copying kivy\core\audio\audio_gstplayer.py ->
> build\lib.win32-2.7\kivy\core\audio
>   copying kivy\core\audio\audio_pygame.py ->
> build\lib.win32-2.7\kivy\core\audio
>   copying kivy\core\audio\audio_pygst.py ->
> build\lib.win32-2.7\kivy\core\audio
>   copying kivy\core\audio\__init__.py -> build\lib.win32-2.7\kivy\core\audio
>   creating build\lib.win32-2.7\kivy\core\camera
>   copying kivy\core\camera\camera_gi.py ->
> build\lib.win32-2.7\kivy\core\camera
>   copying kivy\core\camera\camera_opencv.py ->
> build\lib.win32-2.7\kivy\core\camera
>   copying kivy\core\camera\camera_pygst.py ->
> build\lib.win32-2.7\kivy\core\camera
>   copying kivy\core\camera\camera_videocapture.py ->
> build\lib.win32-2.7\kivy\core\camera
>   copying kivy\core\camera\__init__.py ->
> build\lib.win32-2.7\kivy\core\camera
>   creating build\lib.win32-2.7\kivy\core\clipboard
>   copying kivy\core\clipboard\clipboard_android.py ->
> build\lib.win32-2.7\kivy\core\clipboard
>   copying kivy\core\clipboard\clipboard_dbusklipper.py ->
> build\lib.win32-2.7\kivy\core\clipboard
>   copying kivy\core\clipboard\clipboard_dummy.py ->
> build\lib.win32-2.7\kivy\core\clipboard
>   copying kivy\core\clipboard\clipboard_gtk3.py ->
> build\lib.win32-2.7\kivy\core\clipboard
>   copying kivy\core\clipboard\clipboard_nspaste.py ->
> build\lib.win32-2.7\kivy\core\clipboard
>   copying kivy\core\clipboard\clipboard_pygame.py ->
> build\lib.win32-2.7\kivy\core\clipboard
>   copying kivy\core\clipboard\clipboard_sdl2.py ->
> build\lib.win32-2.7\kivy\core\clipboard
>   copying kivy\core\clipboard\clipboard_winctypes.py ->
> build\lib.win32-2.7\kivy\core\clipboard
>   copying kivy\core\clipboard\clipboard_xsel.py ->
> build\lib.win32-2.7\kivy\core\clipboard
>   copying kivy\core\clipboard\__init__.py ->
> build\lib.win32-2.7\kivy\core\clipboard
>   creating build\lib.win32-2.7\kivy\core\image
>   copying kivy\core\image\img_dds.py -> build\lib.win32-2.7\kivy\core\image
>   copying kivy\core\image\img_ffpyplayer.py ->
> build\lib.win32-2.7\kivy\core\image
>   copying kivy\core\image\img_gif.py -> build\lib.win32-2.7\kivy\core\image
>   copying kivy\core\image\img_pil.py -> build\lib.win32-2.7\kivy\core\image
>   copying kivy\core\image\img_pygame.py ->
> build\lib.win32-2.7\kivy\core\image
>   copying kivy\core\image\img_sdl2.py -> build\lib.win32-2.7\kivy\core\image
>   copying kivy\core\image\img_tex.py -> build\lib.win32-2.7\kivy\core\image
>   copying kivy\core\image\__init__.py -> build\lib.win32-2.7\kivy\core\image
>   creating build\lib.win32-2.7\kivy\core\gl
>   copying kivy\core\gl\__init__.py -> build\lib.win32-2.7\kivy\core\gl
>   creating build\lib.win32-2.7\kivy\core\spelling
>   copying kivy\core\spelling\spelling_enchant.py ->
> build\lib.win32-2.7\kivy\core\spelling
>   copying kivy\core\spelling\spelling_osxappkit.py ->
> build\lib.win32-2.7\kivy\core\spelling
>   copying kivy\core\spelling\__init__.py ->
> build\lib.win32-2.7\kivy\core\spelling
>   creating build\lib.win32-2.7\kivy\core\text
>   copying kivy\core\text\markup.py -> build\lib.win32-2.7\kivy\core\text
>   copying kivy\core\text\text_pil.py -> build\lib.win32-2.7\kivy\core\text
>   copying kivy\core\text\text_pygame.py ->
> build\lib.win32-2.7\kivy\core\text
>   copying kivy\core\text\text_sdl2.py -> build\lib.win32-2.7\kivy\core\text
>   copying kivy\core\text\__init__.py -> build\lib.win32-2.7\kivy\core\text
>   creating build\lib.win32-2.7\kivy\core\video
>   copying kivy\core\video\video_ffmpeg.py ->
> build\lib.win32-2.7\kivy\core\video
>   copying kivy\core\video\video_ffpyplayer.py ->
> build\lib.win32-2.7\kivy\core\video
>   copying kivy\core\video\video_gi.py -> build\lib.win32-2.7\kivy\core\video
>   copying kivy\core\video\video_gstplayer.py ->
> build\lib.win32-2.7\kivy\core\video
>   copying kivy\core\video\video_null.py ->
> build\lib.win32-2.7\kivy\core\video
>   copying kivy\core\video\video_pyglet.py ->
> build\lib.win32-2.7\kivy\core\video
>   copying kivy\core\video\video_pygst.py ->
> build\lib.win32-2.7\kivy\core\video
>   copying kivy\core\video\__init__.py -> build\lib.win32-2.7\kivy\core\video
>   creating build\lib.win32-2.7\kivy\core\window
>   copying kivy\core\window\window_egl_rpi.py ->
> build\lib.win32-2.7\kivy\core\window
>   copying kivy\core\window\window_pygame.py ->
> build\lib.win32-2.7\kivy\core\window
>   copying kivy\core\window\window_sdl2.py ->
> build\lib.win32-2.7\kivy\core\window
>   copying kivy\core\window\__init__.py ->
> build\lib.win32-2.7\kivy\core\window
>   creating build\lib.win32-2.7\kivy\effects
>   copying kivy\effects\dampedscroll.py -> build\lib.win32-2.7\kivy\effects
>   copying kivy\effects\kinetic.py -> build\lib.win32-2.7\kivy\effects
>   copying kivy\effects\opacityscroll.py -> build\lib.win32-2.7\kivy\effects
>   copying kivy\effects\scroll.py -> build\lib.win32-2.7\kivy\effects
>   copying kivy\effects\__init__.py -> build\lib.win32-2.7\kivy\effects
>   creating build\lib.win32-2.7\kivy\ext
>   copying kivy\ext\__init__.py -> build\lib.win32-2.7\kivy\ext
>   creating build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\__init__.py -> build\lib.win32-2.7\kivy\graphics
>   creating build\lib.win32-2.7\kivy\garden
>   copying kivy\garden\__init__.py -> build\lib.win32-2.7\kivy\garden
>   creating build\lib.win32-2.7\kivy\input
>   copying kivy\input\factory.py -> build\lib.win32-2.7\kivy\input
>   copying kivy\input\motionevent.py -> build\lib.win32-2.7\kivy\input
>   copying kivy\input\provider.py -> build\lib.win32-2.7\kivy\input
>   copying kivy\input\recorder.py -> build\lib.win32-2.7\kivy\input
>   copying kivy\input\shape.py -> build\lib.win32-2.7\kivy\input
>   copying kivy\input\__init__.py -> build\lib.win32-2.7\kivy\input
>   creating build\lib.win32-2.7\kivy\input\postproc
>   copying kivy\input\postproc\calibration.py ->
> build\lib.win32-2.7\kivy\input\postproc
>   copying kivy\input\postproc\dejitter.py ->
> build\lib.win32-2.7\kivy\input\postproc
>   copying kivy\input\postproc\doubletap.py ->
> build\lib.win32-2.7\kivy\input\postproc
>   copying kivy\input\postproc\ignorelist.py ->
> build\lib.win32-2.7\kivy\input\postproc
>   copying kivy\input\postproc\retaintouch.py ->
> build\lib.win32-2.7\kivy\input\postproc
>   copying kivy\input\postproc\tripletap.py ->
> build\lib.win32-2.7\kivy\input\postproc
>   copying kivy\input\postproc\__init__.py ->
> build\lib.win32-2.7\kivy\input\postproc
>   creating build\lib.win32-2.7\kivy\input\providers
>   copying kivy\input\providers\androidjoystick.py ->
> build\lib.win32-2.7\kivy\input\providers
>   copying kivy\input\providers\hidinput.py ->
> build\lib.win32-2.7\kivy\input\providers
>   copying kivy\input\providers\leapfinger.py ->
> build\lib.win32-2.7\kivy\input\providers
>   copying kivy\input\providers\linuxwacom.py ->
> build\lib.win32-2.7\kivy\input\providers
>   copying kivy\input\providers\mactouch.py ->
> build\lib.win32-2.7\kivy\input\providers
>   copying kivy\input\providers\mouse.py ->
> build\lib.win32-2.7\kivy\input\providers
>   copying kivy\input\providers\mtdev.py ->
> build\lib.win32-2.7\kivy\input\providers
>   copying kivy\input\providers\probesysfs.py ->
> build\lib.win32-2.7\kivy\input\providers
>   copying kivy\input\providers\tuio.py ->
> build\lib.win32-2.7\kivy\input\providers
>   copying kivy\input\providers\wm_common.py ->
> build\lib.win32-2.7\kivy\input\providers
>   copying kivy\input\providers\wm_pen.py ->
> build\lib.win32-2.7\kivy\input\providers
>   copying kivy\input\providers\wm_touch.py ->
> build\lib.win32-2.7\kivy\input\providers
>   copying kivy\input\providers\__init__.py ->
> build\lib.win32-2.7\kivy\input\providers
>   creating build\lib.win32-2.7\kivy\lib
>   copying kivy\lib\ddsfile.py -> build\lib.win32-2.7\kivy\lib
>   copying kivy\lib\mtdev.py -> build\lib.win32-2.7\kivy\lib
>   copying kivy\lib\__init__.py -> build\lib.win32-2.7\kivy\lib
>   creating build\lib.win32-2.7\kivy\lib\osc
>   copying kivy\lib\osc\OSC.py -> build\lib.win32-2.7\kivy\lib\osc
>   copying kivy\lib\osc\oscAPI.py -> build\lib.win32-2.7\kivy\lib\osc
>   copying kivy\lib\osc\__init__.py -> build\lib.win32-2.7\kivy\lib\osc
>   creating build\lib.win32-2.7\kivy\lib\gstplayer
>   copying kivy\lib\gstplayer\__init__.py ->
> build\lib.win32-2.7\kivy\lib\gstplayer
>   creating build\lib.win32-2.7\kivy\lib\vidcore_lite
>   copying kivy\lib\vidcore_lite\__init__.py ->
> build\lib.win32-2.7\kivy\lib\vidcore_lite
>   creating build\lib.win32-2.7\kivy\modules
>   copying kivy\modules\inspector.py -> build\lib.win32-2.7\kivy\modules
>   copying kivy\modules\keybinding.py -> build\lib.win32-2.7\kivy\modules
>   copying kivy\modules\monitor.py -> build\lib.win32-2.7\kivy\modules
>   copying kivy\modules\recorder.py -> build\lib.win32-2.7\kivy\modules
>   copying kivy\modules\screen.py -> build\lib.win32-2.7\kivy\modules
>   copying kivy\modules\touchring.py -> build\lib.win32-2.7\kivy\modules
>   copying kivy\modules\webdebugger.py -> build\lib.win32-2.7\kivy\modules
>   copying kivy\modules\_webdebugger.py -> build\lib.win32-2.7\kivy\modules
>   copying kivy\modules\__init__.py -> build\lib.win32-2.7\kivy\modules
>   creating build\lib.win32-2.7\kivy\network
>   copying kivy\network\urlrequest.py -> build\lib.win32-2.7\kivy\network
>   copying kivy\network\__init__.py -> build\lib.win32-2.7\kivy\network
>   creating build\lib.win32-2.7\kivy\storage
>   copying kivy\storage\dictstore.py -> build\lib.win32-2.7\kivy\storage
>   copying kivy\storage\jsonstore.py -> build\lib.win32-2.7\kivy\storage
>   copying kivy\storage\redisstore.py -> build\lib.win32-2.7\kivy\storage
>   copying kivy\storage\__init__.py -> build\lib.win32-2.7\kivy\storage
>   creating build\lib.win32-2.7\kivy\tools
>   copying kivy\tools\benchmark.py -> build\lib.win32-2.7\kivy\tools
>   copying kivy\tools\generate-icons.py -> build\lib.win32-2.7\kivy\tools
>   copying kivy\tools\report.py -> build\lib.win32-2.7\kivy\tools
>   copying kivy\tools\stub-gl-debug.py -> build\lib.win32-2.7\kivy\tools
>   copying kivy\tools\texturecompress.py -> build\lib.win32-2.7\kivy\tools
>   copying kivy\tools\__init__.py -> build\lib.win32-2.7\kivy\tools
>   creating build\lib.win32-2.7\kivy\tools\packaging
>   copying kivy\tools\packaging\factory.py ->
> build\lib.win32-2.7\kivy\tools\packaging
>   copying kivy\tools\packaging\__init__.py ->
> build\lib.win32-2.7\kivy\tools\packaging
>   creating build\lib.win32-2.7\kivy\tools\packaging\pyinstaller_hooks
>   copying kivy\tools\packaging\pyinstaller_hooks\hook-kivy.py ->
> build\lib.win32-2.7\kivy\tools\packaging\pyinstaller_hooks
>   copying kivy\tools\packaging\pyinstaller_hooks\rt-hook-kivy.py ->
> build\lib.win32-2.7\kivy\tools\packaging\pyinstaller_hooks
>   copying kivy\tools\packaging\pyinstaller_hooks\__init__.py ->
> build\lib.win32-2.7\kivy\tools\packaging\pyinstaller_hooks
>   creating build\lib.win32-2.7\kivy\tools\highlight
>   copying kivy\tools\highlight\__init__.py ->
> build\lib.win32-2.7\kivy\tools\highlight
>   creating build\lib.win32-2.7\kivy\extras
>   copying kivy\extras\highlight.py -> build\lib.win32-2.7\kivy\extras
>   copying kivy\extras\__init__.py -> build\lib.win32-2.7\kivy\extras
>   creating build\lib.win32-2.7\kivy\tools\extensions
>   copying kivy\tools\extensions\make-kivyext.py ->
> build\lib.win32-2.7\kivy\tools\extensions
>   copying kivy\tools\extensions\__init__.py ->
> build\lib.win32-2.7\kivy\tools\extensions
>   creating build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\abstractview.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\accordion.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\actionbar.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\anchorlayout.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\behaviors.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\boxlayout.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\bubble.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\button.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\camera.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\carousel.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\checkbox.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\codeinput.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\colorpicker.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\dropdown.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\effectwidget.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\filechooser.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\floatlayout.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\gesturesurface.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\gridlayout.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\image.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\label.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\layout.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\listview.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\modalview.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\pagelayout.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\popup.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\progressbar.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\relativelayout.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\rst.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\sandbox.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\scatter.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\scatterlayout.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\screenmanager.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\scrollview.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\selectableview.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\settings.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\slider.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\spinner.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\splitter.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\stacklayout.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\stencilview.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\switch.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\tabbedpanel.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\textinput.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\togglebutton.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\treeview.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\video.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\videoplayer.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\vkeyboard.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\widget.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\uix\__init__.py -> build\lib.win32-2.7\kivy\uix
>   copying kivy\properties.pxd -> build\lib.win32-2.7\kivy
>   copying kivy\_event.pxd -> build\lib.win32-2.7\kivy
>   copying kivy\core\text\text_layout.pxd ->
> build\lib.win32-2.7\kivy\core\text
>   copying kivy\graphics\buffer.pxd -> build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\compiler.pxd -> build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\context.pxd -> build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\context_instructions.pxd ->
> build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\c_opengl.pxd -> build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\c_opengl_debug.pxd ->
> build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\fbo.pxd -> build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\instructions.pxd ->
> build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\opengl_utils.pxd ->
> build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\shader.pxd -> build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\stencil_instructions.pxd ->
> build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\svg.pxd -> build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\tesselator.pxd -> build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\texture.pxd -> build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\transformation.pxd ->
> build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\vbo.pxd -> build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\vertex.pxd -> build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\vertex_instructions.pxd ->
> build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\common.pxi -> build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\img_tools.pxi -> build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\opcodes.pxi -> build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\opengl_utils_def.pxi ->
> build\lib.win32-2.7\kivy\graphics
>   copying kivy\graphics\vertex_instructions_line.pxi ->
> build\lib.win32-2.7\kivy\graphics
>   copying kivy\lib\vidcore_lite\bcm.pxd ->
> build\lib.win32-2.7\kivy\lib\vidcore_lite
>   creating build\lib.win32-2.7\kivy\data
>   copying kivy\data\style.kv -> build\lib.win32-2.7\kivy\data
>   copying kivy\data\settings_kivy.json -> build\lib.win32-2.7\kivy\data
>   creating build\lib.win32-2.7\kivy\data\fonts
>   copying kivy\data\fonts\DejaVuSans.ttf ->
> build\lib.win32-2.7\kivy\data\fonts
>   copying kivy\data\fonts\DroidSans-Bold.ttf ->
> build\lib.win32-2.7\kivy\data\fonts
>   copying kivy\data\fonts\DroidSans-BoldItalic.ttf ->
> build\lib.win32-2.7\kivy\data\fonts
>   copying kivy\data\fonts\DroidSans-Italic.ttf ->
> build\lib.win32-2.7\kivy\data\fonts
>   copying kivy\data\fonts\DroidSans.ttf ->
> build\lib.win32-2.7\kivy\data\fonts
>   copying kivy\data\fonts\DroidSansMono.ttf ->
> build\lib.win32-2.7\kivy\data\fonts
>   creating build\lib.win32-2.7\kivy\data\images
>   copying kivy\data\images\defaulttheme-0.png ->
> build\lib.win32-2.7\kivy\data\images
>   copying kivy\data\images\testpattern.png ->
> build\lib.win32-2.7\kivy\data\images
>   copying kivy\data\images\background.jpg ->
> build\lib.win32-2.7\kivy\data\images
>   copying kivy\data\images\image-loading.gif ->
> build\lib.win32-2.7\kivy\data\images
>   copying kivy\data\images\defaulttheme.atlas ->
> build\lib.win32-2.7\kivy\data\images
>   creating build\lib.win32-2.7\kivy\data\keyboards
>   copying kivy\data\keyboards\azerty.json ->
> build\lib.win32-2.7\kivy\data\keyboards
>   copying kivy\data\keyboards\de_CH.json ->
> build\lib.win32-2.7\kivy\data\keyboards
>   copying kivy\data\keyboards\en_US.json ->
> build\lib.win32-2.7\kivy\data\keyboards
>   copying kivy\data\keyboards\fr_CH.json ->
> build\lib.win32-2.7\kivy\data\keyboards
>   copying kivy\data\keyboards\qwerty.json ->
> build\lib.win32-2.7\kivy\data\keyboards
>   copying kivy\data\keyboards\qwertz.json ->
> build\lib.win32-2.7\kivy\data\keyboards
>   creating build\lib.win32-2.7\kivy\data\logo
>   copying kivy\data\logo\kivy-icon-128.png ->
> build\lib.win32-2.7\kivy\data\logo
>   copying kivy\data\logo\kivy-icon-16.png ->
> build\lib.win32-2.7\kivy\data\logo
>   copying kivy\data\logo\kivy-icon-24.png ->
> build\lib.win32-2.7\kivy\data\logo
>   copying kivy\data\logo\kivy-icon-256.png ->
> build\lib.win32-2.7\kivy\data\logo
>   copying kivy\data\logo\kivy-icon-32.png ->
> build\lib.win32-2.7\kivy\data\logo
>   copying kivy\data\logo\kivy-icon-512.png ->
> build\lib.win32-2.7\kivy\data\logo
>   copying kivy\data\logo\kivy-icon-64.png ->
> build\lib.win32-2.7\kivy\data\logo
>   creating build\lib.win32-2.7\kivy\data\glsl
>   copying kivy\data\glsl\default.png -> build\lib.win32-2.7\kivy\data\glsl
>   copying kivy\data\glsl\default.vs -> build\lib.win32-2.7\kivy\data\glsl
>   copying kivy\data\glsl\header.vs -> build\lib.win32-2.7\kivy\data\glsl
>   copying kivy\data\glsl\default.fs -> build\lib.win32-2.7\kivy\data\glsl
>   copying kivy\data\glsl\header.fs -> build\lib.win32-2.7\kivy\data\glsl
>   copying kivy\tools\highlight\kivy.vim ->
> build\lib.win32-2.7\kivy\tools\highlight
>   copying kivy\tools\highlight\kivy-mode.el ->
> build\lib.win32-2.7\kivy\tools\highlight
>   copying kivy\tools\packaging\README.txt ->
> build\lib.win32-2.7\kivy\tools\packaging
>   creating build\lib.win32-2.7\kivy\tools\packaging\win32
>   copying kivy\tools\packaging\win32\README.txt ->
> build\lib.win32-2.7\kivy\tools\packaging\win32
>   creating build\lib.win32-2.7\kivy\tools\packaging\osx
>   copying kivy\tools\packaging\osx\Info.plist ->
> build\lib.win32-2.7\kivy\tools\packaging\osx
>   copying kivy\tools\packaging\osx\InfoPlist.strings ->
> build\lib.win32-2.7\kivy\tools\packaging\osx
>   copying kivy\tools\packaging\osx\kivy.sh ->
> build\lib.win32-2.7\kivy\tools\packaging\osx
>    warning: build_py: byte-compiling is disabled, skipping.
>
>   running build_ext
>   Build configuration is:
>    * use_rpi = 0
>    * use_opengl_es2 = 0
>    * use_opengl_debug = 0
>    * use_glew = 1
>    * use_sdl2 = 0
>    * use_ios = 0
>    * use_mesagl = 0
>    * use_x11 = 0
>    * use_gstreamer = 0
>    * use_avfoundation = 0
>    * use_osx_frameworks = 0
>    * debug = False
>   Updated build\lib.win32-2.7\kivy\graphics\config.h
>   Updated
> C:\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy\graphics\config.h
>   Updated build\lib.win32-2.7\kivy\graphics\config.pxi
>   Updated
> C:\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy\graphics\config.pxi
>   Updated build\lib.win32-2.7\kivy\setupconfig.py
>   Updated
> C:\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy\setupconfig.py
>   Detected compiler is msvc
>   cythoning
> C:\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy\graphics/opengl.pyx
> to
> C:\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy\graphics\opengl.c
>   building 'kivy.graphics.opengl' extension
>   creating build\temp.win32-2.7
>   creating build\temp.win32-2.7\Release
>   creating build\temp.win32-2.7\Release\Users
>   creating build\temp.win32-2.7\Release\Users\edge
>   creating build\temp.win32-2.7\Release\Users\edge\AppData
>   creating build\temp.win32-2.7\Release\Users\edge\AppData\Local
>   creating build\temp.win32-2.7\Release\Users\edge\AppData\Local\Temp
>   creating
> build\temp.win32-2.7\Release\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp
>   creating
> build\temp.win32-2.7\Release\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy
>   creating
> build\temp.win32-2.7\Release\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy
>   creating
> build\temp.win32-2.7\Release\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy\graphics
>   C:\Users\edge\AppData\Local\Programs\Common\Microsoft\Visual C++ for
> Python\9.0\VC\Bin\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG
> -IC:\Python27\include -IC:\Python27\PC
> /TcC:\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy\graphics\opengl.c
> /Fobuild\temp.win32-2.7\Release\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy\graphics\opengl.obj
>   opengl.c
>
> c:\users\edge\appdata\local\temp\pycharm-packaging0.tmp\kivy\kivy\graphics\gl_redirect.h(8)
> : fatal error C1083: Cannot open include file: 'GL/glew.h': No such file or
> directory
>    error: command
> 'C:\\Users\\edge\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++
> for Python\\9.0\\VC\\Bin\\cl.exe' failed with exit status 2
>
>   ----------------------------------------
> Failed to build Kivy
> Installing collected packages: Kivy
>   Running setup.py install for Kivy
>     Complete output from command C:\Python27\python.exe -c "import
> setuptools,
> tokenize;__file__='C:\\Users\\edge\\AppData\\Local\\Temp\\pycharm-packaging0.tmp\\Kivy\\setup.py';exec(compile(getattr(tokenize,
> 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))"
> install --record
> c:\users\edge\appdata\local\temp\pip-qnjvsj-record\install-record.txt
> --single-version-externally-managed --compile --user --prefix=:
>     [INFO              ] [Logger      ] Record log in
> C:\Users\edge\.kivy\logs\kivy_15-12-17_36.txt
>     [INFO              ] [Kivy        ] v1.9.0
>     [INFO              ] [Python      ] v2.7.11 (v2.7.11:6d1b6a68f775, Dec
>  5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)]
>
>     Detected Cython version 0.21.2
>     Windows platform detected, force GLEW usage.
>     Using this graphics system: OpenGL
>     WARNING: A problem occured while running pkg-config --libs --cflags
> gstreamer-1.0 (code 1)
>
>     'pkg-config' is not recognized as an internal or external command,
>     operable program or batch file.
>
>
>     WARNING: A problem occured while running pkg-config --libs --cflags
> sdl2 SDL2_ttf SDL2_image SDL2_mixer (code 1)
>
>     'pkg-config' is not recognized as an internal or external command,
>     operable program or batch file.
>
>
>     running install
>     running build
>     running build_py
>      warning: build_py: byte-compiling is disabled, skipping.
>
>     running build_ext
>     Build configuration is:
>      * use_rpi = 0
>      * use_opengl_es2 = 0
>      * use_opengl_debug = 0
>      * use_glew = 1
>      * use_sdl2 = 0
>      * use_ios = 0
>      * use_mesagl = 0
>      * use_x11 = 0
>      * use_gstreamer = 0
>      * use_avfoundation = 0
>      * use_osx_frameworks = 0
>      * debug = False
>     Detected compiler is msvc
>     skipping
> 'C:\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy\graphics\opengl.c'
> Cython extension (up-to-date)
>     building 'kivy.graphics.opengl' extension
>     C:\Users\edge\AppData\Local\Programs\Common\Microsoft\Visual C++ for
> Python\9.0\VC\Bin\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG
> -IC:\Python27\include -IC:\Python27\PC
> /TcC:\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy\graphics\opengl.c
> /Fobuild\temp.win32-2.7\Release\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy\kivy\graphics\opengl.obj
>     opengl.c
>
> c:\users\edge\appdata\local\temp\pycharm-packaging0.tmp\kivy\kivy\graphics\gl_redirect.h(8)
> : fatal error C1083: Cannot open include file: 'GL/glew.h': No such file or
> directory
>      error: command
> 'C:\\Users\\edge\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++
> for Python\\9.0\\VC\\Bin\\cl.exe' failed with exit status 2
>
>     ----------------------------------------
>
>   Failed building wheel for Kivy
> Command "C:\Python27\python.exe -c "import setuptools,
> tokenize;__file__='C:\\Users\\edge\\AppData\\Local\\Temp\\pycharm-packaging0.tmp\\Kivy\\setup.py';exec(compile(getattr(tokenize,
> 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))"
> install --record
> c:\users\edge\appdata\local\temp\pip-qnjvsj-record\install-record.txt
> --single-version-externally-managed --compile --user --prefix=" failed with
> error code 1 in C:\Users\edge\AppData\Local\Temp\pycharm-packaging0.tmp\Kivy
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

From alan.gauld at btinternet.com  Thu Dec 17 20:54:03 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 18 Dec 2015 01:54:03 +0000
Subject: [Tutor] Fwd: Kivy Install
In-Reply-To: <CAGOURkHso2gdczsx3g0qjGJk1KJ9EoYjRTgg9fVe69UdaPBZKA@mail.gmail.com>
References: <CAGOURkFDk9=gZQOy85c4173t6_b4m8S2wKR5QzrHCYv4cJAsKw@mail.gmail.com>
 <CAGOURkHso2gdczsx3g0qjGJk1KJ9EoYjRTgg9fVe69UdaPBZKA@mail.gmail.com>
Message-ID: <n4vovr$ibn$1@ger.gmane.org>

On 17/12/15 18:06, peter mcfarlane wrote:
> Hi,
>      I don't know if this is the correct forum, 

Not really, this is for folks learning the python language
and its standard library. kivy is a bit outside that remit.
But pip isn't so...

> ...I am new to Python and
> trying to install Kivy.  I keep getting the following error message.
> Can you help?

I'm no expert on Kivy and only a basics guy on pip but...

> c:\users\edge\appdata\local\temp\pycharm-packaging0.tmp\kivy\kivy\graphics\gl_redirect.h(8)
> : fatal error C1083: Cannot open include file: 'GL/glew.h': No such file or
> directory
>    error: command
> 'C:\\Users\\edge\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++
> for Python\\9.0\\VC\\Bin\\cl.exe' failed with exit status 2

Do you have Visual C++ installed?

It looks like its trying to use it to compile something...
But thats just a guess.

I've just noticed another reply saying there are binary
versions of kivy. If so I'd also recommend that route.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From breamoreboy at yahoo.co.uk  Fri Dec 18 06:13:53 2015
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Fri, 18 Dec 2015 11:13:53 +0000
Subject: [Tutor] Fwd: Kivy Install
In-Reply-To: <CAGOURkHso2gdczsx3g0qjGJk1KJ9EoYjRTgg9fVe69UdaPBZKA@mail.gmail.com>
References: <CAGOURkFDk9=gZQOy85c4173t6_b4m8S2wKR5QzrHCYv4cJAsKw@mail.gmail.com>
 <CAGOURkHso2gdczsx3g0qjGJk1KJ9EoYjRTgg9fVe69UdaPBZKA@mail.gmail.com>
Message-ID: <n50ppr$ojl$1@ger.gmane.org>

On 17/12/2015 18:06, peter mcfarlane wrote:
> Hi,
>       I don't know if this is the correct forum, I am new to Python and
> trying to install Kivy.  I keep getting the following error message.
> Can you help?
>
> thanks,
> pete
>
> pip install --user Kivy
>

[snip attempted Windows build]

I've given up trying to build anything on Windows, it's just too much 
like hard work.  So go to http://www.lfd.uci.edu/~gohlke/pythonlibs/ and 
download Kivy-1.9.0+sdl2-cp27-none-win32.whl or 
Kivy-1.9.0+sdl2-cp27-none-win_amd64.whl as appropriate.  Then use "pip 
install" against the local file name.

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

Mark Lawrence


From akleider at sonic.net  Fri Dec 18 13:38:45 2015
From: akleider at sonic.net (Alex Kleider)
Date: Fri, 18 Dec 2015 10:38:45 -0800
Subject: [Tutor] interface
In-Reply-To: <CANDiX9JBs3-Gz4p2NAFCgdserQh-6v9K_xWTJPcS0HHCFaN2hA@mail.gmail.com>
References: <41d908e5c2dd5cc68875549bcb4c6f1a@sonic.net>
 <n4no99$lh4$1@ger.gmane.org> <fc616a945551ae356144a50e579d1e56@sonic.net>
 <CANDiX9JBs3-Gz4p2NAFCgdserQh-6v9K_xWTJPcS0HHCFaN2hA@mail.gmail.com>
Message-ID: <cec8c7eec488c79d0efa759fa147794a@sonic.net>

On 2015-12-16 17:42, boB Stepp wrote:
> On Mon, Dec 14, 2015 at 10:08 PM, Alex Kleider <akleider at sonic.net> 
> wrote:
>> Thank you, gentlemen (Alan, Ben, Mark,) for your advice.
>> The consensus seems to be in favour of tkinter
>> so I'll head in that direction.
> 
> If you are into books, "Programming Python, 4th ed." by Mark Lutz, has
> an extensive section on tkinter (Alan had pointed this out to me, and
> I have found Lutz's coverage very helpful).  Plus the book (very
> thick!) has lots of other goodies.  Also, the now old book, "Python
> and Tkinter Programming" by John E. Grayson is just about Tkinter
> (with a capital "T") as it is copyrighted 2000.  Despite this I think
> it is still quite useful even if you are working in Python 3 as, as
> far as I can tell, t/Tkinter has not changed substantially in how the
> coding goes.


I've settled on "Modern Tkinter" by Mark Roseman.
His is the most recently published of the various references recommended
and he makes the point that the "themed" (ttk) component is recent
(and I assume not covered in the other sources.)
I'd prefer a real book but have had to settle for the kindle edition:-)
A pdf version may also be available.


Another issue about which I'd like to hear comments has to do with
how the imports are done.
Roseman indicates that
     from tkinter import *
     from tkinter import ttk
is the generally accepted way of doing the importing but the first line
uses a syntax that is strongly discouraged so my inclination is to use
     import tkinter as tk
     from tkinter import ttk
instead.

Comments?

From breamoreboy at yahoo.co.uk  Fri Dec 18 17:13:56 2015
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Fri, 18 Dec 2015 22:13:56 +0000
Subject: [Tutor] interface
In-Reply-To: <cec8c7eec488c79d0efa759fa147794a@sonic.net>
References: <41d908e5c2dd5cc68875549bcb4c6f1a@sonic.net>
 <n4no99$lh4$1@ger.gmane.org> <fc616a945551ae356144a50e579d1e56@sonic.net>
 <CANDiX9JBs3-Gz4p2NAFCgdserQh-6v9K_xWTJPcS0HHCFaN2hA@mail.gmail.com>
 <cec8c7eec488c79d0efa759fa147794a@sonic.net>
Message-ID: <n520fe$rvg$1@ger.gmane.org>

On 18/12/2015 18:38, Alex Kleider wrote:
> On 2015-12-16 17:42, boB Stepp wrote:
>> On Mon, Dec 14, 2015 at 10:08 PM, Alex Kleider <akleider at sonic.net>
>> wrote:
>>> Thank you, gentlemen (Alan, Ben, Mark,) for your advice.
>>> The consensus seems to be in favour of tkinter
>>> so I'll head in that direction.
>>
>> If you are into books, "Programming Python, 4th ed." by Mark Lutz, has
>> an extensive section on tkinter (Alan had pointed this out to me, and
>> I have found Lutz's coverage very helpful).  Plus the book (very
>> thick!) has lots of other goodies.  Also, the now old book, "Python
>> and Tkinter Programming" by John E. Grayson is just about Tkinter
>> (with a capital "T") as it is copyrighted 2000.  Despite this I think
>> it is still quite useful even if you are working in Python 3 as, as
>> far as I can tell, t/Tkinter has not changed substantially in how the
>> coding goes.
>
>
> I've settled on "Modern Tkinter" by Mark Roseman.
> His is the most recently published of the various references recommended
> and he makes the point that the "themed" (ttk) component is recent
> (and I assume not covered in the other sources.)
> I'd prefer a real book but have had to settle for the kindle edition:-)
> A pdf version may also be available.
>
>
> Another issue about which I'd like to hear comments has to do with
> how the imports are done.
> Roseman indicates that
>      from tkinter import *
>      from tkinter import ttk
> is the generally accepted way of doing the importing but the first line
> uses a syntax that is strongly discouraged so my inclination is to use
>      import tkinter as tk
>      from tkinter import ttk
> instead.
>
> Comments?
>

from xyz import * is The Road To Hell.

Sticking with the explicit way of importing modules makes life so much 
easier in the long term that there is IMHO nothing to discuss.

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

Mark Lawrence


From akleider at sonic.net  Fri Dec 18 17:56:37 2015
From: akleider at sonic.net (Alex Kleider)
Date: Fri, 18 Dec 2015 14:56:37 -0800
Subject: [Tutor] interface
In-Reply-To: <n520fe$rvg$1@ger.gmane.org>
References: <41d908e5c2dd5cc68875549bcb4c6f1a@sonic.net>
 <n4no99$lh4$1@ger.gmane.org> <fc616a945551ae356144a50e579d1e56@sonic.net>
 <CANDiX9JBs3-Gz4p2NAFCgdserQh-6v9K_xWTJPcS0HHCFaN2hA@mail.gmail.com>
 <cec8c7eec488c79d0efa759fa147794a@sonic.net> <n520fe$rvg$1@ger.gmane.org>
Message-ID: <e65627b014f3ce49547473dd8a268034@sonic.net>

On 2015-12-18 14:13, Mark Lawrence wrote:
> On 18/12/2015 18:38, Alex Kleider wrote:

>> Another issue about which I'd like to hear comments has to do with
>> how the imports are done.
>> Roseman indicates that
>>      from tkinter import *
>>      from tkinter import ttk
>> is the generally accepted way of doing the importing but the first 
>> line
>> uses a syntax that is strongly discouraged so my inclination is to use
>>      import tkinter as tk
>>      from tkinter import ttk
>> instead.
>> 
>> Comments?
>> 
> 
> from xyz import * is The Road To Hell.
> 
> Sticking with the explicit way of importing modules makes life so much
> easier in the long term that there is IMHO nothing to discuss.

Vindicated!
Thank you.
Alex

From ben+python at benfinney.id.au  Fri Dec 18 19:40:37 2015
From: ben+python at benfinney.id.au (Ben Finney)
Date: Sat, 19 Dec 2015 11:40:37 +1100
Subject: [Tutor] interface
References: <41d908e5c2dd5cc68875549bcb4c6f1a@sonic.net>
 <n4no99$lh4$1@ger.gmane.org>
 <fc616a945551ae356144a50e579d1e56@sonic.net>
 <CANDiX9JBs3-Gz4p2NAFCgdserQh-6v9K_xWTJPcS0HHCFaN2hA@mail.gmail.com>
 <cec8c7eec488c79d0efa759fa147794a@sonic.net>
 <n520fe$rvg$1@ger.gmane.org>
 <e65627b014f3ce49547473dd8a268034@sonic.net>
Message-ID: <85d1u32rui.fsf@benfinney.id.au>

Alex Kleider <akleider at sonic.net> writes:

> On 2015-12-18 14:13, Mark Lawrence wrote:
> > On 18/12/2015 18:38, Alex Kleider wrote:
>
> >> [?] uses a syntax that is strongly discouraged

Yes. It is discouraged in PEP 8 and in other guides for Pythonic code.

    Wildcard imports ( from <module> import * ) should be avoided, as
    they make it unclear which names are present in the namespace,
    confusing both readers and many automated tools.

    <URL:https://www.python.org/dev/peps/pep-0008/#id17>

For all new Python code, that should IMO be strongly enforced.

> >> so my inclination is to use
> >>      import tkinter as tk
> >>      from tkinter import ttk
> >> instead.
> >>
> >> Comments?

I agree with that usage. ?import inconvenientlongname as shortname? is
excellent code that combines the virtues of being explicit, concise,
readable, and easily-introspected.

> > from xyz import * is The Road To Hell.
>
> Vindicated!

Note that the Python standard library documentation for Tkinter
explicitly contradicts PEP 8 advice:

    [?] usually, to use Tkinter all you need is a simple import statement:

    import tkinter

    Or, more often:

    from tkinter import *

    <URL:https://docs.python.org/3/library/tkinter.html#tkinter-modules>

This is one of many cases where conventions have resolved after some
significant code (and documentation) violating the convention entered
the standard library.

So, it is an uncomfortable fact that Python's Tkinter recommends
un-Pythonic idioms ? and that will likely remain the case.

I applaud attempts to carve out an ever-increasing space where the more
Pythonic idiom ?import tkinter as tk? is enforced. Be aware, though,
that there is a lot of existing code ? most of which shouldn't be
changed only to fix this ? which violates that idiom.

-- 
 \         ?If we don't believe in freedom of expression for people we |
  `\           despise, we don't believe in it at all.? ?Noam Chomsky, |
_o__)                                                       1992-11-25 |
Ben Finney


From alan.gauld at btinternet.com  Fri Dec 18 20:22:13 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 19 Dec 2015 01:22:13 +0000
Subject: [Tutor] interface
In-Reply-To: <cec8c7eec488c79d0efa759fa147794a@sonic.net>
References: <41d908e5c2dd5cc68875549bcb4c6f1a@sonic.net>
 <n4no99$lh4$1@ger.gmane.org> <fc616a945551ae356144a50e579d1e56@sonic.net>
 <CANDiX9JBs3-Gz4p2NAFCgdserQh-6v9K_xWTJPcS0HHCFaN2hA@mail.gmail.com>
 <cec8c7eec488c79d0efa759fa147794a@sonic.net>
Message-ID: <n52bg4$s3h$1@ger.gmane.org>

On 18/12/15 18:38, Alex Kleider wrote:

> I've settled on "Modern Tkinter" by Mark Roseman.
> His is the most recently published of the various references recommended
> and he makes the point that the "themed" (ttk) component is recent
> (and I assume not covered in the other sources.)

FWIW My recent book Python Projects includes coverage of
both ttk and Tix as well as core tkinter. But it's only
designed to be a taster, it's not a complete reference.
It's more about the general approach to putting a UI on
an app than about any specific toolkit.

>      import tkinter as tk
>      from tkinter import ttk

For production code this is better.
And you can swap out Tkinter for Tix by just changing
one line:

import tkinter.tixix as tk   # v3

or

import Tix as tk    # v2

So all  the existing tk code carries on working but
you now have access to the extra widgets in Tix too.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at btinternet.com  Sat Dec 19 11:05:02 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 19 Dec 2015 16:05:02 +0000
Subject: [Tutor] OOD post missing
Message-ID: <n53v7e$86r$1@ger.gmane.org>

Somebody posted a question about OO design this morning.
Once more the approved message has disappeared.

I've asked the list managers to see if they can find out
what's happening but in the meantime if it was your
message that has gone please repost it.

Sorry about this.

-- 
Alan G
List moderator


From nathaniel.olivier at googlemail.com  Sat Dec 19 12:39:15 2015
From: nathaniel.olivier at googlemail.com (Nathaniel Olivier)
Date: Sat, 19 Dec 2015 17:39:15 +0000
Subject: [Tutor] help!
Message-ID: <CALgFgMDfA8ePrt8wfCknb8d6ip87HiNB9k1T2BVWtXFyJra77g@mail.gmail.com>

I don't understand what's wrong with this piece of code?
print ("The Flying Circus recently entered your town and are doing a never
seen before performance")
answer=raw_input("Shall you go? Type Yes or No to answer.")

def the_flying_circus():
    if answer == "Yes" or "yes" or "YES" or "yES":
        print ("You decided to go but your wallet was stolen by a circus
monkey. YOU LOSE!")
    elif answer == "no" or "No" or "NO" or "nO":
        print ("Your friends pressure you into coming but you stay
defiant.")
        print ("
























































































                                       Wait a minute.... YOU HAVE NO
FRIENDS! Cri evri tim ENDING")
    else:
        print ("U dumb m8? Try again idiot.")
    the_flying_circus()
the_flying_circus()
Note, Elif print 2 is made up of tabs.

From steve at pearwood.info  Sat Dec 19 18:43:48 2015
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 20 Dec 2015 10:43:48 +1100
Subject: [Tutor] help!
In-Reply-To: <CALgFgMDfA8ePrt8wfCknb8d6ip87HiNB9k1T2BVWtXFyJra77g@mail.gmail.com>
References: <CALgFgMDfA8ePrt8wfCknb8d6ip87HiNB9k1T2BVWtXFyJra77g@mail.gmail.com>
Message-ID: <20151219234348.GO1609@ando.pearwood.info>

On Sat, Dec 19, 2015 at 05:39:15PM +0000, Nathaniel Olivier via Tutor wrote:
> I don't understand what's wrong with this piece of code?

>         print ("

SyntaxError here. If you want multiply lines in a string, use THREE 
quotation marks, not one:

print ("""

more than one
line of text

""")


-- 
Steve

From alan.gauld at btinternet.com  Sat Dec 19 19:33:20 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 20 Dec 2015 00:33:20 +0000
Subject: [Tutor] help!
In-Reply-To: <CALgFgMDfA8ePrt8wfCknb8d6ip87HiNB9k1T2BVWtXFyJra77g@mail.gmail.com>
References: <CALgFgMDfA8ePrt8wfCknb8d6ip87HiNB9k1T2BVWtXFyJra77g@mail.gmail.com>
Message-ID: <n54t0g$hjj$1@ger.gmane.org>

On 19/12/15 17:39, Nathaniel Olivier via Tutor wrote:
> I don't understand what's wrong with this piece of code?

Thee are several problems

> print ("The Flying Circus recently entered your town and are doing a never
> seen before performance")
> answer=raw_input("Shall you go? Type Yes or No to answer.")
> 
> def the_flying_circus():
>     if answer == "Yes" or "yes" or "YES" or "yES":

THis is not doping what you think.
Python reads it like this:

if (answer == "Yes") or ("yes") or ("YES") or ("yES"):

And sinve the last three are all True in a boolean zsense the if is
always true.

You probably want to do two tyhings to fix this:

1) convert answer to lowercase (or upper if you prefer)
to avoid worrying about case combinations

if answer.lower() == 'yes':

2) use the in operator rather than or to cater for multiple
options, such as:

if answer.lower() in ('yes','y','yep','yup'):

>         print ("You decided to go but your wallet was stolen by a circus
> monkey. YOU LOSE!")
>     elif answer == "no" or "No" or "NO" or "nO":

same here

>         print ("Your friends pressure you into coming but you stay
> defiant.")
>         print ("
> 

Problem number 2.
Single quotes cannot bridge lines. You must use triple quotes (either
''' or """) to do that. OR you can embed newline literals in your single
quoted string:

print ("First line\n\n\n\n\n\\nlast line")

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at btinternet.com  Sat Dec 19 19:36:53 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 20 Dec 2015 00:36:53 +0000
Subject: [Tutor] OOD post missing
In-Reply-To: <n53v7e$86r$1@ger.gmane.org>
References: <n53v7e$86r$1@ger.gmane.org>
Message-ID: <n54t75$ka4$1@ger.gmane.org>

On 19/12/15 16:05, Alan Gauld wrote:

> I've asked the list managers to see if they can find out
> what's happening

It seems the vanishing messages come into the moderation queue
as multi-part mime messages. Once they are approved they go
through content filtering and in these cases the content is
all embedded in an unrecognised mime part which gets deleted.
This leaves an empty message which the server duly bins.

They have recommended some new filtering settings
which I've now applied, so hopefully we won't lose any
more messages.

Watch this space...
-- 
Alan G
List moderator



From breamoreboy at yahoo.co.uk  Sat Dec 19 19:44:33 2015
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sun, 20 Dec 2015 00:44:33 +0000
Subject: [Tutor] help!
In-Reply-To: <n54t0g$hjj$1@ger.gmane.org>
References: <CALgFgMDfA8ePrt8wfCknb8d6ip87HiNB9k1T2BVWtXFyJra77g@mail.gmail.com>
 <n54t0g$hjj$1@ger.gmane.org>
Message-ID: <n54tls$qk5$1@ger.gmane.org>

On 20/12/2015 00:33, Alan Gauld wrote:
> On 19/12/15 17:39, Nathaniel Olivier via Tutor wrote:
>> I don't understand what's wrong with this piece of code?

It does help if you give a more meaningful subject when asking, 
otherwise trying to find a specific thread in the archives is all but 
impossible.

>
> Thee are several problems
>
>> print ("The Flying Circus recently entered your town and are doing a never
>> seen before performance")
>> answer=raw_input("Shall you go? Type Yes or No to answer.")
>>
>> def the_flying_circus():
>>      if answer == "Yes" or "yes" or "YES" or "yES":
>
> THis is not doping what you think.
----------------^
whoops :)

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

Mark Lawrence


From akleider at sonic.net  Sat Dec 19 21:21:54 2015
From: akleider at sonic.net (Alex Kleider)
Date: Sat, 19 Dec 2015 18:21:54 -0800
Subject: [Tutor] interface
In-Reply-To: <n52bg4$s3h$1@ger.gmane.org>
References: <41d908e5c2dd5cc68875549bcb4c6f1a@sonic.net>
 <n4no99$lh4$1@ger.gmane.org> <fc616a945551ae356144a50e579d1e56@sonic.net>
 <CANDiX9JBs3-Gz4p2NAFCgdserQh-6v9K_xWTJPcS0HHCFaN2hA@mail.gmail.com>
 <cec8c7eec488c79d0efa759fa147794a@sonic.net> <n52bg4$s3h$1@ger.gmane.org>
Message-ID: <8a0e6d9fb2555e553eb3c033e2547743@sonic.net>

On 2015-12-18 17:22, Alan Gauld wrote:

> FWIW My recent book Python Projects includes coverage of
> both ttk and Tix as well as core tkinter. But it's only
> designed to be a taster, it's not a complete reference.
> It's more about the general approach to putting a UI on
> an app than about any specific toolkit.

I have it (the book by Laura Cassell and you!)
The first chapter still has me stumbling! (Super, slots and property() 
were new to me.)
Hadn't yet noticed the Tkinter section- thanks for pointing it out to 
me.


> 
>>      import tkinter as tk
>>      from tkinter import ttk
> 
> For production code this is better.
> And you can swap out Tkinter for Tix by just changing
> one line:
> 
> import tkinter.tixix as tk   # v3
> 
> or
> 
> import Tix as tk    # v2
> 
> So all  the existing tk code carries on working but
> you now have access to the extra widgets in Tix too.

First I've heard of Tix!
Much to learn.

Thanks, Alex

From jamiehu17 at yandex.com  Sat Dec 19 19:48:58 2015
From: jamiehu17 at yandex.com (jamie hu)
Date: Sat, 19 Dec 2015 16:48:58 -0800
Subject: [Tutor] Object oriented design
In-Reply-To: <3586891450500743@web28m.yandex.ru>
Message-ID: <1365671450572538@web10g.yandex.ru>

   *
   Hi,

   I am starting with Python object oriented concepts and have difficulty in
   understanding object instantiation. Below is an example code that I am
   trying to think/implement. I can create a given student object based on
   given firstname, lastname and grade. How do I find all objects matching
   particular criteria and return them to caller? Do I need to iterate/select
   through some list/database and create Student objects again?

   *

   Sorry that question is not quite clear, but I am confused and not sure how
   to put it in right words.*

   *

   class Student():
   * def __init__(self,firstname,lastname,age):
   * * self.firstname = firstname
   * * self.lastname = lastname
   * * self.grade = grade

   * def set_grade(self,grade):
   * * self.grade = grade

   * @classmethod

   * # Find all Students with given lastname
   * def find_by_lastname():
   * * # How do I return all student objects that have same lastname?
   * * # Do I need to call init method again? I am confused here.
   * * pass

   *

   Thanks,

   Jamie

   *
   *

From anshu.kumar726 at gmail.com  Sat Dec 19 21:47:21 2015
From: anshu.kumar726 at gmail.com (Anshu Kumar)
Date: Sun, 20 Dec 2015 08:17:21 +0530
Subject: [Tutor] Python String and Unicode data types and Encode Decode
 Functions
Message-ID: <CAMFBua4KC+rCBHA_11O0j575B5w3xQJZFyTPU_kzsCx5RKY4jA@mail.gmail.com>

Hi Everyone,

In my current project I am dealing a lot with unicode type. There are some
text files which contain unicode to accommodate data in multiple languages.
I have to continuously parse these files in xml or yaml format using xml
and yaml libraries. I have encountered several errors due to unicode and
have to encode such texts to utf-8 using encode('utf-8') method. Though I
could resolve my issue but could not appreciate the datatypes unicode ,
string, encode and decode methods.

I know certain facts like

1. String is nothing but a byte array so it has only 8 bits to encode
character using ascii, so it should not be used whenever we have characters
from other language thats why a broader type unicode is used.

2. Python internally uses different implementation  to store strings in RAM

3. print function can print both string and unicode because it has some
kind of function overloading.


4. u'' , that is u prefixed before single quotes or double quotes tells
python interpreter that the following type is unicode and not a string.


Now my doubts start

*1. I tried below code and see that japanese characters can be accommodated
in strings. I do not get how is it possible?*

>>> temo = '??'
>>> temo
'\xe3\x81\x84\xe3\x81\x84'
>>> print temo
??
>>> type(temo)
<type 'str'>
>>>


*2. When i try to iterate over characters i do not get anything meaningful*

for character in temo:
...     print character
...

?
?

?
?

*3 . When I do I get length  as 6 *

len(temo)
6

Why so?


*4.  When i try to spit out each character I get below error*

 for character in temo:
...     print character.encode('utf-8')
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0:
ordinal not in range(128)


Now I am not able to appreciate how unicode and string are working in
background with the facts I know. Please help me to understand this magic.

Thanks a lot in advance,
Anshu

From alan.gauld at btinternet.com  Sun Dec 20 04:23:45 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 20 Dec 2015 09:23:45 +0000
Subject: [Tutor] Object oriented design
In-Reply-To: <1365671450572538@web10g.yandex.ru>
References: <3586891450500743@web28m.yandex.ru>
 <1365671450572538@web10g.yandex.ru>
Message-ID: <n55s31$g2b$1@ger.gmane.org>

On 20/12/15 00:48, jamie hu wrote:

>    trying to think/implement. I can create a given student object based on
>    given firstname, lastname and grade. How do I find all objects matching
>    particular criteria and return them to caller? Do I need to iterate/select
>    through some list/database and create Student objects again?

You need to store a referejce to each object in some kind of
container - a list or dictionary for example, or maybe a full
blown database.

>    class Student():
>    * def __init__(self,firstname,lastname,age):
>    * * self.firstname = firstname
>    * * self.lastname = lastname
>    * * self.grade = grade
> 
>    * def set_grade(self,grade):
>    * * self.grade = grade
> 
>    * @classmethod
> 
>    * # Find all Students with given lastname
>    * def find_by_lastname():
>    * * # How do I return all student objects that have same lastname?
>    * * # Do I need to call init method again? I am confused here.
>    * * pass

You don't need to call init a second time but you do need to put
your instances into a container as you create them. A common way
to do this is to have a class attribute (ie not an instance one)
called _instances or similar and have a line at the end
of __init__() that does

Student._instances.append(self)

Your class method can then traverse the _instances collection
checking each instance until it finds the desired object.

If you have many objects, and especially if they will not
all be instantiated at once you would use a database and
in that case the class method would check the instances
collection first to see if you already had the object
in memory and, if not, instantiate it from the database.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From steve at pearwood.info  Sun Dec 20 05:25:27 2015
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 20 Dec 2015 21:25:27 +1100
Subject: [Tutor] Python String and Unicode data types and Encode Decode
 Functions
In-Reply-To: <CAMFBua4KC+rCBHA_11O0j575B5w3xQJZFyTPU_kzsCx5RKY4jA@mail.gmail.com>
References: <CAMFBua4KC+rCBHA_11O0j575B5w3xQJZFyTPU_kzsCx5RKY4jA@mail.gmail.com>
Message-ID: <20151220102526.GP1609@ando.pearwood.info>

On Sun, Dec 20, 2015 at 08:17:21AM +0530, Anshu Kumar wrote:

> I know certain facts like

What version of Python are you using? My *guess* is that you are using 
Python 2.7, is that correct?

What operating system are you using? Windows, Linux, Mac OS X, Unix, 
something else?


> 1. String is nothing but a byte array so it has only 8 bits to encode
> character using ascii, so it should not be used whenever we have characters
> from other language thats why a broader type unicode is used.

If you are using Python 2, this is correct.

> 2. Python internally uses different implementation  to store strings in RAM

Correct.


> 3. print function can print both string and unicode because it has some
> kind of function overloading.

Mostly correct. `print` can print any object in Python (within reason). 
The details are probably not important.


> 4. u'' , that is u prefixed before single quotes or double quotes tells
> python interpreter that the following type is unicode and not a string.

In Python 2, this is correct.


> Now my doubts start

Unicode is sometimes hard to understand, and unfortunately Python 2 
makes it even harder rather than easier.


> *1. I tried below code and see that japanese characters can be accommodated
> in strings. I do not get how is it possible?*
> 
> >>> temo = '??'
> >>> temo
> '\xe3\x81\x84\xe3\x81\x84'
> >>> print temo
> ??
> >>> type(temo)
> <type 'str'>

This appears to be Python 2 code.

The fact that this works is an accident of the terminal/console you are 
using. If you tried it on another computer, using a different OS, you 
might find the results will change or possibly won't work at all.

What seems to be happening is this:

(1) You type, or paste, two Unicode characters into the terminal input 
buffer, namely `HIRAGANA LETTER I` repeated twice.

(2) The terminal is set to use UTF-8 encoding, so it puts the six bytes 
\xe3\x81\x84 \xe3\x81\x84 into the buffer, and displays HIRAGANA LETTER 
I twice.

(3) Python generates a string object containing six bytes (as above).

(4) When you print those six bytes, the terminal recognises this as 
UTF-8, and displays HIRAGANA LETTER I (twice).


This seems to work, but it is an accident. If you change the terminal 
settings, you will see different results:


# terminal using UTF-8 as the encoding
py> s = '??'  # looks like HIRAGANA LETTER I twice but actually six bytes
py> print s  # terminal recognises this as UTF-8
??
py> s  # The actual six bytes.
'\xe3\x81\x84\xe3\x81\x84'

# now I change the terminal to use ISO-8859-7 (Greek) instead.
# the same six bytes now display as a Greek character plus invisible 
# control characters
py> print s  
??


# now I change the terminal to use Latin-1 ISO-8859-1
py> print s
??


So the results you get are dependent on the terminal's encoding. The 
fact that it happens to work on your computer is a lucky accident.


Instead, you should ensure Python knows to use proper Unicode text:

py> s = u'??'
py> print s
??


Provided your terminal is capable of entering the HIRAGANA LETTER I 
character in the first place, then s will ALWAYS be treated as that same 
HIRAGANA LETTER I. (Although, if you change the encoding of the 
terminal, it may print differently. That's not Python's fault -- that's 
the terminal.)

In this case, instead of s being a *byte* string of three bytes, 
\xe3 \x81 \x84, s is a Unicode string of ONE character ?. (Double 
everything if you enter the character twice.)


> *2. When i try to iterate over characters i do not get anything meaningful*
> 
> for character in temo:
> ...     print character
> ...

You are trying to print the six control characters 

\xe3 \x81 \x84 \xe3 \x81 \x84

What they look like on your system could be anything -- a blank space, 
no space at all, or the "missing character" glyph.


> *3 . When I do I get length  as 6 *
> 
> len(temo)
> 6
> 
> Why so?

Because your terminal has entered each Unicode character as three UTF-8 
bytes; you have two characters, and 2*3 is 6. Hence the byte string is 
length six.

If you use a Unicode string, the length will be two Unicode characters.

Internally, in the computer's RAM, those two characters might be stored 
as any of the following bytes:

# UTF-16 Big Endian
\x30 \x44 \x30 \x44

# UTF-16 Little Endian
\x44 \x30 \x44 \x30

# UTF-32 Big Endian
\x00 \x00 \x30 \x44 \x00 \x00 \x30 \x44

# UTF-32 Little Endian
\x44 \x30 \x00 \x00 \x44 \x30 \x00 \x00

# UTF-8
\xe3 \x81 \x84 \xe3 \x81 \x84

depending on the implementation and version of Python. The internal 
representation isn't very important, the important thing is that Unicode 
strings are treated as sequences of Unicode characters, not as sequences 
of bytes.


> *4.  When i try to spit out each character I get below error*
> 
>  for character in temo:
> ...     print character.encode('utf-8')
> ...
> Traceback (most recent call last):
>   File "<stdin>", line 2, in <module>
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0:
> ordinal not in range(128)


You have two problems here. The first is that you are trying to 
encode bytes to bytes. That doesn't work. The rule is:

Unicode characters *encode* to bytes;
Bytes *decode* to Unicode characters.

Unfortunately, Python 2 has a design flaw that allows you to attempt the 
following (wrong) transformations:

# Wrong, don't do this:
Unicode characters decoded to bytes;
Bytes encoded to Unicode characters.

Python 2 will try to make sense of this, but will usually get it wrong. 
That's what is happening here: you're asking for an impossible 
transformation (bytes encoded to Unicode) so Python tries to be helpful 
by guess that maybe you wanted to *decode* the bytes to ASCII first, 
only that failed.

This confusing and broken design is fixed in Python 3.


The RIGHT way to do this is to use a Unicode string, not a byte string:

py> s = u'?'  # HIRAGANA LETTER I
py> print s
?
py> b = s.encode('utf-8')
py> b
'\xe3\x81\x84'
py> b.decode('utf-8') == s
True



Hope that this helps, and feel free to ask more questions!



-- 
Steve

From alan.gauld at btinternet.com  Sun Dec 20 09:11:32 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 20 Dec 2015 14:11:32 +0000
Subject: [Tutor] interface
In-Reply-To: <8a0e6d9fb2555e553eb3c033e2547743@sonic.net>
References: <41d908e5c2dd5cc68875549bcb4c6f1a@sonic.net>
 <n4no99$lh4$1@ger.gmane.org> <fc616a945551ae356144a50e579d1e56@sonic.net>
 <CANDiX9JBs3-Gz4p2NAFCgdserQh-6v9K_xWTJPcS0HHCFaN2hA@mail.gmail.com>
 <cec8c7eec488c79d0efa759fa147794a@sonic.net> <n52bg4$s3h$1@ger.gmane.org>
 <8a0e6d9fb2555e553eb3c033e2547743@sonic.net>
Message-ID: <n56cuk$m5$1@ger.gmane.org>

On 20/12/15 02:21, Alex Kleider wrote:

> First I've heard of Tix!
> Much to learn.

A potentially useful set of extra widgets on top of Tkinter.
Unfortunately the Tkinter port of the original Tcl/Tk TIX
package is incomplete and only reliable for about half the
extended widgets (thankfully the most common ones such
as scrolledList and a tabbed Notebook etc).

The biggest disappointment is the Grid widget which
theoretically should work but despite many attempts I've
failed to get anything useful. It's on my todo list to spend
some time either fixing it, or documenting how it works,
or both...

But because Tix is a superset of Tkinter I rarely use
raw Tkinter nowadays I usually just start with Tix.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From akleider at sonic.net  Sun Dec 20 15:00:33 2015
From: akleider at sonic.net (Alex Kleider)
Date: Sun, 20 Dec 2015 12:00:33 -0800
Subject: [Tutor] interface
In-Reply-To: <n56cuk$m5$1@ger.gmane.org>
References: <41d908e5c2dd5cc68875549bcb4c6f1a@sonic.net>
 <n4no99$lh4$1@ger.gmane.org> <fc616a945551ae356144a50e579d1e56@sonic.net>
 <CANDiX9JBs3-Gz4p2NAFCgdserQh-6v9K_xWTJPcS0HHCFaN2hA@mail.gmail.com>
 <cec8c7eec488c79d0efa759fa147794a@sonic.net> <n52bg4$s3h$1@ger.gmane.org>
 <8a0e6d9fb2555e553eb3c033e2547743@sonic.net> <n56cuk$m5$1@ger.gmane.org>
Message-ID: <df74d66c192fe47287348b36d2fbb052@sonic.net>

On 2015-12-20 06:11, Alan Gauld wrote:
> On 20/12/15 02:21, Alex Kleider wrote:
> 
>> First I've heard of Tix!
> 
> A potentially useful set of extra widgets on top of Tkinter.
> Unfortunately the Tkinter port of the original Tcl/Tk TIX
> package is incomplete and only reliable for about half the
> extended widgets (thankfully the most common ones such
> as scrolledList and a tabbed Notebook etc).
> 
> The biggest disappointment is the Grid widget which
> theoretically should work but despite many attempts I've
> failed to get anything useful. It's on my todo list to spend
> some time either fixing it, or documenting how it works,
> or both...
> 
> But because Tix is a superset of Tkinter I rarely use
> raw Tkinter nowadays I usually just start with Tix.

Thanks for the background insight.
How does Ttk (T for 'themed' I assume) fit in? is it used in addition to 
Tix
(as it would be used in addition to tkinter)
or is it an either/or situation?

Alex

From dyoo at hashcollision.org  Sun Dec 20 15:48:56 2015
From: dyoo at hashcollision.org (Danny Yoo)
Date: Sun, 20 Dec 2015 12:48:56 -0800
Subject: [Tutor] Object oriented design
In-Reply-To: <1365671450572538@web10g.yandex.ru>
References: <3586891450500743@web28m.yandex.ru>
 <1365671450572538@web10g.yandex.ru>
Message-ID: <CAGZAPF7XdGu3zoGCOdeXGr-kb0zexVtgfaiP3WPeb3qpnVqHNw@mail.gmail.com>

On Sat, Dec 19, 2015 at 4:48 PM, jamie hu <jamiehu17 at yandex.com> wrote:
>    I am starting with Python object oriented concepts and have difficulty in
>    understanding object instantiation. Below is an example code that I am
>    trying to think/implement. I can create a given student object based on
>    given firstname, lastname and grade. How do I find all objects matching
>    particular criteria and return them to caller? Do I need to iterate/select
>    through some list/database and create Student objects again?


In order to find something, that something needs to be accessible from
"somewhere".

In typical beginner programs, that "somewhere" is an in-memory
collection, like a list or dictionary, as Alan suggests.  I'd expect,
for your purposes, that this is an appropriate representation for
"somewhere".

find_by_lastname needs to know about this "somewhere".  You have a few
options.  1.  You can either pass the "somewhere" in as an explicit
parameter, or 2. hardcode it within find_by_lastname's definition.

We expect that #1 will look something like:

#####################################
"""Collection of things."""
STUDENTS = []

...

def find_by_lastname(students, lastname):
    """Contract: listof(Student) string -> Student
    Given a list of students and a student's last name,
    returns the student with that last name.
    """
   # ... fill me in


## later, we can call find_by_lastname, passing in the
## collection as an explicit argument.
find_by_lastname(STUDENTS, "jamie")
#####################################


And #2 will probably look something like:

#####################################
"""Collection of things."""
STUDENTS = []

...

def find_by_lastname(lastname):
    """Contract: string -> Student
    Given a student's last name, returns the student
    with that last name, looking through STUDENTS.
    """
   # ... fill me in


## later, we can call find_by_lastname, passing in the
## collection as an explicit argument.
find_by_lastname("jamie")
#####################################


This is a rough sketch.  So, which one do you choose?

I have no idea!

This is a decision point, and one that you need to resolve, because
either choice has its own advantages and tradeoffs.  Assuming this is
an assignment, you need to talk with your instructor to see if there's
one that they had in mind, or if this is something you get to decide.
Personally, I don't like hardcoding, so #1 is my pick, but #2 has its
advantages too: it's easier to call.


Please feel free to ask questions.  Good luck.

From alan.gauld at btinternet.com  Sun Dec 20 20:51:59 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 21 Dec 2015 01:51:59 +0000
Subject: [Tutor] interface
In-Reply-To: <df74d66c192fe47287348b36d2fbb052@sonic.net>
References: <41d908e5c2dd5cc68875549bcb4c6f1a@sonic.net>
 <n4no99$lh4$1@ger.gmane.org> <fc616a945551ae356144a50e579d1e56@sonic.net>
 <CANDiX9JBs3-Gz4p2NAFCgdserQh-6v9K_xWTJPcS0HHCFaN2hA@mail.gmail.com>
 <cec8c7eec488c79d0efa759fa147794a@sonic.net> <n52bg4$s3h$1@ger.gmane.org>
 <8a0e6d9fb2555e553eb3c033e2547743@sonic.net> <n56cuk$m5$1@ger.gmane.org>
 <df74d66c192fe47287348b36d2fbb052@sonic.net>
Message-ID: <n57lvu$5j8$1@ger.gmane.org>

On 20/12/15 20:00, Alex Kleider wrote:

>> But because Tix is a superset of Tkinter I rarely use
>> raw Tkinter nowadays I usually just start with Tix.
> 
> Thanks for the background insight.
> How does Ttk (T for 'themed' I assume) fit in? is it used in addition to 
> Tix

Yes. Tkinter and Tix both share the same look n feel
and are just collections of widgets.

Ttk is a smaller set of widgets but uses the style of the
native toolkit(or at least a much closer approximation
than Tkinter). Personally the look of Tk doesn't offend
me that much so I rarely bother using ttk, but if you
plan on sharing apps with folks who live and breath Windows
or Mac then they might feel more comfortable with
ttk buttons/menus. But it does need an extra
import/reference beyond Tkinter or Tix.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From vrkratheesh at live.com  Sun Dec 20 23:34:52 2015
From: vrkratheesh at live.com (vrkratheesh at live.com)
Date: Mon, 21 Dec 2015 04:34:52 +0000
Subject: [Tutor] Python 2 vs Python 3
Message-ID: <SNT407-EAS1717A2F30D7FD0084B025B9D8E40@phx.gbl>



Hi I am starting to learn Python with the help of head first python. I have installed python 2.x.x.? But the book is explaining python 3 syntaxes. For example,? 

Avoiding a new line in print statement which made a confusion to me.? So is it wise I change to python or can anyone recommend any websites or books where I can see the difference between python 3 and python 2 syntax changes.? Thanks in advance. 

Ratheeshkumar. 

From anshu.kumar726 at gmail.com  Mon Dec 21 04:05:25 2015
From: anshu.kumar726 at gmail.com (Anshu Kumar)
Date: Mon, 21 Dec 2015 14:35:25 +0530
Subject: [Tutor] Python String and Unicode data types and Encode Decode
 Functions
In-Reply-To: <20151220102526.GP1609@ando.pearwood.info>
References: <CAMFBua4KC+rCBHA_11O0j575B5w3xQJZFyTPU_kzsCx5RKY4jA@mail.gmail.com>
 <20151220102526.GP1609@ando.pearwood.info>
Message-ID: <CAMFBua4ercA3JSXYW=WggW3y2Y2C2--X3baQN+2fZu484OUOmA@mail.gmail.com>

Hi Steven.

Thanks a lot for your reply. Now I have some clarity.

Could you please confirm if i get it correct?


1. There is an internal encoding of input characters to bytes which depends
on python version and os
2. For non unicode types every text gets encoded using point 1 and gets
printed using the decode of same way.
3. Unicode is universal coding and will not fail to accommodate any input
character.
4. For unicode type first character is encoded to unicode bytes and then
encoded to get stored in memory
5. thats why we need to encode the unicode characters to bytes

Thanks and Regards,
Anshu

On Sun, Dec 20, 2015 at 3:55 PM, Steven D'Aprano <steve at pearwood.info>
wrote:

> On Sun, Dec 20, 2015 at 08:17:21AM +0530, Anshu Kumar wrote:
>
> > I know certain facts like
>
> What version of Python are you using? My *guess* is that you are using
> Python 2.7, is that correct?
>
> What operating system are you using? Windows, Linux, Mac OS X, Unix,
> something else?
>
>
> > 1. String is nothing but a byte array so it has only 8 bits to encode
> > character using ascii, so it should not be used whenever we have
> characters
> > from other language thats why a broader type unicode is used.
>
> If you are using Python 2, this is correct.
>
> > 2. Python internally uses different implementation  to store strings in
> RAM
>
> Correct.
>
>
> > 3. print function can print both string and unicode because it has some
> > kind of function overloading.
>
> Mostly correct. `print` can print any object in Python (within reason).
> The details are probably not important.
>
>
> > 4. u'' , that is u prefixed before single quotes or double quotes tells
> > python interpreter that the following type is unicode and not a string.
>
> In Python 2, this is correct.
>
>
> > Now my doubts start
>
> Unicode is sometimes hard to understand, and unfortunately Python 2
> makes it even harder rather than easier.
>
>
> > *1. I tried below code and see that japanese characters can be
> accommodated
> > in strings. I do not get how is it possible?*
> >
> > >>> temo = '??'
> > >>> temo
> > '\xe3\x81\x84\xe3\x81\x84'
> > >>> print temo
> > ??
> > >>> type(temo)
> > <type 'str'>
>
> This appears to be Python 2 code.
>
> The fact that this works is an accident of the terminal/console you are
> using. If you tried it on another computer, using a different OS, you
> might find the results will change or possibly won't work at all.
>
> What seems to be happening is this:
>
> (1) You type, or paste, two Unicode characters into the terminal input
> buffer, namely `HIRAGANA LETTER I` repeated twice.
>
> (2) The terminal is set to use UTF-8 encoding, so it puts the six bytes
> \xe3\x81\x84 \xe3\x81\x84 into the buffer, and displays HIRAGANA LETTER
> I twice.
>
> (3) Python generates a string object containing six bytes (as above).
>
> (4) When you print those six bytes, the terminal recognises this as
> UTF-8, and displays HIRAGANA LETTER I (twice).
>
>
> This seems to work, but it is an accident. If you change the terminal
> settings, you will see different results:
>
>
> # terminal using UTF-8 as the encoding
> py> s = '??'  # looks like HIRAGANA LETTER I twice but actually six bytes
> py> print s  # terminal recognises this as UTF-8
> ??
> py> s  # The actual six bytes.
> '\xe3\x81\x84\xe3\x81\x84'
>
> # now I change the terminal to use ISO-8859-7 (Greek) instead.
> # the same six bytes now display as a Greek character plus invisible
> # control characters
> py> print s
> ??
>
>
> # now I change the terminal to use Latin-1 ISO-8859-1
> py> print s
> ??
>
>
> So the results you get are dependent on the terminal's encoding. The
> fact that it happens to work on your computer is a lucky accident.
>
>
> Instead, you should ensure Python knows to use proper Unicode text:
>
> py> s = u'??'
> py> print s
> ??
>
>
> Provided your terminal is capable of entering the HIRAGANA LETTER I
> character in the first place, then s will ALWAYS be treated as that same
> HIRAGANA LETTER I. (Although, if you change the encoding of the
> terminal, it may print differently. That's not Python's fault -- that's
> the terminal.)
>
> In this case, instead of s being a *byte* string of three bytes,
> \xe3 \x81 \x84, s is a Unicode string of ONE character ?. (Double
> everything if you enter the character twice.)
>
>
> > *2. When i try to iterate over characters i do not get anything
> meaningful*
> >
> > for character in temo:
> > ...     print character
> > ...
>
> You are trying to print the six control characters
>
> \xe3 \x81 \x84 \xe3 \x81 \x84
>
> What they look like on your system could be anything -- a blank space,
> no space at all, or the "missing character" glyph.
>
>
> > *3 . When I do I get length  as 6 *
> >
> > len(temo)
> > 6
> >
> > Why so?
>
> Because your terminal has entered each Unicode character as three UTF-8
> bytes; you have two characters, and 2*3 is 6. Hence the byte string is
> length six.
>
> If you use a Unicode string, the length will be two Unicode characters.
>
> Internally, in the computer's RAM, those two characters might be stored
> as any of the following bytes:
>
> # UTF-16 Big Endian
> \x30 \x44 \x30 \x44
>
> # UTF-16 Little Endian
> \x44 \x30 \x44 \x30
>
> # UTF-32 Big Endian
> \x00 \x00 \x30 \x44 \x00 \x00 \x30 \x44
>
> # UTF-32 Little Endian
> \x44 \x30 \x00 \x00 \x44 \x30 \x00 \x00
>
> # UTF-8
> \xe3 \x81 \x84 \xe3 \x81 \x84
>
> depending on the implementation and version of Python. The internal
> representation isn't very important, the important thing is that Unicode
> strings are treated as sequences of Unicode characters, not as sequences
> of bytes.
>
>
> > *4.  When i try to spit out each character I get below error*
> >
> >  for character in temo:
> > ...     print character.encode('utf-8')
> > ...
> > Traceback (most recent call last):
> >   File "<stdin>", line 2, in <module>
> > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0:
> > ordinal not in range(128)
>
>
> You have two problems here. The first is that you are trying to
> encode bytes to bytes. That doesn't work. The rule is:
>
> Unicode characters *encode* to bytes;
> Bytes *decode* to Unicode characters.
>
> Unfortunately, Python 2 has a design flaw that allows you to attempt the
> following (wrong) transformations:
>
> # Wrong, don't do this:
> Unicode characters decoded to bytes;
> Bytes encoded to Unicode characters.
>
> Python 2 will try to make sense of this, but will usually get it wrong.
> That's what is happening here: you're asking for an impossible
> transformation (bytes encoded to Unicode) so Python tries to be helpful
> by guess that maybe you wanted to *decode* the bytes to ASCII first,
> only that failed.
>
> This confusing and broken design is fixed in Python 3.
>
>
> The RIGHT way to do this is to use a Unicode string, not a byte string:
>
> py> s = u'?'  # HIRAGANA LETTER I
> py> print s
> ?
> py> b = s.encode('utf-8')
> py> b
> '\xe3\x81\x84'
> py> b.decode('utf-8') == s
> True
>
>
>
> Hope that this helps, and feel free to ask more questions!
>
>
>
> --
> Steve
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From berkayaksoy at gmail.com  Sun Dec 20 22:36:31 2015
From: berkayaksoy at gmail.com (Seint Aksoy)
Date: Mon, 21 Dec 2015 05:36:31 +0200
Subject: [Tutor] Hi pyusb Cant Connect Hid Device !
Message-ID: <CAFMhnMTwYL-h2dPT+JO9CNoG+ikGfy+Lmn1o_nxPt0HgRCF2Vg@mail.gmail.com>

Hello i ve searching some information for my problem .
i m trying to write data to usb hid device
idVendor=0x0123, idProduct=0x0012
its pic18f2550


Bus 001 Device 008: ID 0123:0012
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               1.10
  bDeviceClass            0 (Defined at Interface level)
  bDeviceSubClass         0
  bDeviceProtocol         0
  bMaxPacketSize0        64
  idVendor           0x0123
  idProduct          0x0012
  bcdDevice            1.00
  iManufacturer           1 USB
  iProduct                2 IO INTERFACE
  iSerial                 0
  bNumConfigurations      1
  Configuration Descriptor:
    bLength                 9
    bDescriptorType         2
    wTotalLength           41
    bNumInterfaces          1
    bConfigurationValue     1
    iConfiguration          0
    bmAttributes         0xc0
      Self Powered
    MaxPower              100mA
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        0
      bAlternateSetting       0
      bNumEndpoints           2
      bInterfaceClass         3 Human Interface Device
      bInterfaceSubClass      0 No Subclass
      bInterfaceProtocol      0 None
      iInterface              0
        HID Device Descriptor:
          bLength                 9
          bDescriptorType        33
          bcdHID               1.00
          bCountryCode            0 Not supported
          bNumDescriptors         1
          bDescriptorType        34 Report
          wDescriptorLength      32
          Report Descriptor: (length is 32)
            Item(Global): Usage Page, data= [ 0x00 0xff ] 65280
                            (null)
            Item(Local ): Usage, data= [ 0x01 ] 1
                            (null)
            Item(Main  ): Collection, data= [ 0x01 ] 1
                            Application
            Item(Local ): Usage Minimum, data= [ 0x01 ] 1
                            (null)
            Item(Local ): Usage Maximum, data= [ 0x08 ] 8
                            (null)
            Item(Global): Logical Minimum, data= [ 0x80 ] 128
            Item(Global): Logical Maximum, data= [ 0x7f ] 127
            Item(Global): Report Size, data= [ 0x08 ] 8
            Item(Global): Report Count, data= [ 0x02 ] 2
            Item(Main  ): Input, data= [ 0x02 ] 2
                            Data Variable Absolute No_Wrap Linear
                            Preferred_State No_Null_Position Non_Volatile
Bitfield
            Item(Local ): Usage Minimum, data= [ 0x01 ] 1
                            (null)
            Item(Local ): Usage Maximum, data= [ 0x08 ] 8
                            (null)
            Item(Global): Report Size, data= [ 0x08 ] 8
            Item(Global): Report Count, data= [ 0x02 ] 2
            Item(Main  ): Output, data= [ 0x02 ] 2
                            Data Variable Absolute No_Wrap Linear
                            Preferred_State No_Null_Position Non_Volatile
Bitfield
            Item(Main  ): End Collection, data=none
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x81  EP 1 IN
        bmAttributes            3
          Transfer Type            Interrupt
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0008  1x 8 bytes
        bInterval             250
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x01  EP 1 OUT
        bmAttributes            3
          Transfer Type            Interrupt
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0008  1x 8 bytes
        bInterval              10
Device Status:     0x0001


i ve tried kind of codes
read_bytes = self.handle.interruptRead(0x81, 8, 1000)

hid_device.write(0x1, ([0x91]))

both is return len(data)
so it should write but its not writing !
is there anyone can help me thank you!

From alan.gauld at btinternet.com  Mon Dec 21 04:12:10 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 21 Dec 2015 09:12:10 +0000
Subject: [Tutor] Python 2 vs Python 3
In-Reply-To: <SNT407-EAS1717A2F30D7FD0084B025B9D8E40@phx.gbl>
References: <SNT407-EAS1717A2F30D7FD0084B025B9D8E40@phx.gbl>
Message-ID: <n58fp9$gkr$1@ger.gmane.org>

On 21/12/15 04:34, vrkratheesh at live.com wrote:
> Hi I am starting to learn Python with the help of head first python. 
> I have installed python 2.x.x.
> But the book is explaining python 3 syntaxes. 

There are many differences between v2 and v3, not only in syntax but in
module structure and content. It will be easier if you install Python v3
sooner rather than later.

The only real reason to use Python v2 nowadays is if some special module
or package that you need is only available for v2, but that's
increasingly uncommon and as a beginner probably not an issue for you.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From dyoo at hashcollision.org  Mon Dec 21 04:13:25 2015
From: dyoo at hashcollision.org (Danny Yoo)
Date: Mon, 21 Dec 2015 01:13:25 -0800
Subject: [Tutor] Python 2 vs Python 3
In-Reply-To: <SNT407-EAS1717A2F30D7FD0084B025B9D8E40@phx.gbl>
References: <SNT407-EAS1717A2F30D7FD0084B025B9D8E40@phx.gbl>
Message-ID: <CAGZAPF7Sv--WZ8GZpjQTShzeYggOWKRDLM7TePyESr44dWypaw@mail.gmail.com>

Hi Ratheeshkumar,

It probably makes the most sense to switch to Python 3; Python 3 was
meant to have fewer idiosyncrasies than Python 2, and should be easier
to learn.

There is a document that summarizes the Python 2 -> Python 3 changes.
It's here: https://docs.python.org/3/whatsnew/3.0.html.  You can find
more information at: https://wiki.python.org/moin/Python2orPython3.

But I think you probably want to use Python 3, unless you have a
legacy reason for it.  And as a beginner, those legacy reasons should
be minimal for you.  :P

From alan.gauld at btinternet.com  Mon Dec 21 04:19:03 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 21 Dec 2015 09:19:03 +0000
Subject: [Tutor] Hi pyusb Cant Connect Hid Device !
In-Reply-To: <CAFMhnMTwYL-h2dPT+JO9CNoG+ikGfy+Lmn1o_nxPt0HgRCF2Vg@mail.gmail.com>
References: <CAFMhnMTwYL-h2dPT+JO9CNoG+ikGfy+Lmn1o_nxPt0HgRCF2Vg@mail.gmail.com>
Message-ID: <n58g66$n6t$1@ger.gmane.org>

On 21/12/15 03:36, Seint Aksoy wrote:
> Hello i ve searching some information for my problem .
> i m trying to write data to usb hid device

This list if for learning the core python language and standard
library. Pyusb is not part of that and a bit more technical
than our normal scope. You would be better asking on a pyusb
support forum, or failing that on the main Python mailing list/newsgroup.

The pyusb list details are here:
https://lists.sourceforge.net/lists/listinfo/pyusb-users


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From sunil.techspk at gmail.com  Mon Dec 21 07:22:29 2015
From: sunil.techspk at gmail.com (Sunil Tech)
Date: Mon, 21 Dec 2015 17:52:29 +0530
Subject: [Tutor] Optimize the code - removing the multiple IF conditions
Message-ID: <CAExJxTO--WzrSfTyxari3nGN+qJ_ivA1ynW2Bh6TDN=Hct4HcQ@mail.gmail.com>

Hi,

I Have a code..


class OptIf(object):
    """docstring for OptIf"""

    def opt_me(self, ext):
        if ext == 'CM':
            rec = self.call_cm(cm, ad)
        if ext == 'MM':
            rec = self.call_mm(mm, ax)
        if ext == 'DM':
            rec = self.call_dm(dm, md)
        return rec

    def call_cm(cm, ad):
        pass

    def call_mm(mm, ax):
        pass

    def call_dm(dm, md):
        pass


I want to optimize the code by removing the if conditions in the opt_me
method,
I tried with few things making a dictionary of key as the ext and the value
as the method that to be called.

med_map = {'CM': call_cm, 'MM': call_mm, 'DM': call_dm}
but I am not able to pass the arguments.

can you please help or suggest the other way?


Thanks,

From __peter__ at web.de  Mon Dec 21 07:46:27 2015
From: __peter__ at web.de (Peter Otten)
Date: Mon, 21 Dec 2015 13:46:27 +0100
Subject: [Tutor] Optimize the code - removing the multiple IF conditions
References: <CAExJxTO--WzrSfTyxari3nGN+qJ_ivA1ynW2Bh6TDN=Hct4HcQ@mail.gmail.com>
Message-ID: <n58sb7$pk1$1@ger.gmane.org>

Sunil Tech wrote:

> Hi,
> 
> I Have a code..
> 
> 
> class OptIf(object):
>     """docstring for OptIf"""
> 
>     def opt_me(self, ext):
>         if ext == 'CM':
>             rec = self.call_cm(cm, ad)
>         if ext == 'MM':
>             rec = self.call_mm(mm, ax)
>         if ext == 'DM':
>             rec = self.call_dm(dm, md)
>         return rec
> 
>     def call_cm(cm, ad):
>         pass
> 
>     def call_mm(mm, ax):
>         pass
> 
>     def call_dm(dm, md):
>         pass
> 
> 
> I want to optimize the code by removing the if conditions in the opt_me
> method,

No offence, but you have been around for some time now, long enough to learn 
how to properly present a problem.

The above code is broken, and until you have a working base that uses if 
statements it does not make much sense to "optimize" it. 

> I tried with few things making a dictionary of key as the ext and the
> value as the method that to be called.
> 
> med_map = {'CM': call_cm, 'MM': call_mm, 'DM': call_dm}
> but I am not able to pass the arguments.
> 
> can you please help or suggest the other way?

Go back to the drawing board and once you can present correct code that uses 
if statements it will be our pleasure to show you how to convert it to dict 
lookup.



From steve at pearwood.info  Mon Dec 21 08:42:49 2015
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 22 Dec 2015 00:42:49 +1100
Subject: [Tutor] Optimize the code - removing the multiple IF conditions
In-Reply-To: <CAExJxTO--WzrSfTyxari3nGN+qJ_ivA1ynW2Bh6TDN=Hct4HcQ@mail.gmail.com>
References: <CAExJxTO--WzrSfTyxari3nGN+qJ_ivA1ynW2Bh6TDN=Hct4HcQ@mail.gmail.com>
Message-ID: <20151221134247.GR1609@ando.pearwood.info>

On Mon, Dec 21, 2015 at 05:52:29PM +0530, Sunil Tech wrote:

> class OptIf(object):
>     """docstring for OptIf"""
> 
>     def opt_me(self, ext):
>         if ext == 'CM':
>             rec = self.call_cm(cm, ad)
>         if ext == 'MM':
>             rec = self.call_mm(mm, ax)
>         if ext == 'DM':
>             rec = self.call_dm(dm, md)
>         return rec

As written above, it probably is not worth re-factoring that code, since 
not only are the method calls different, but so are the arguments. But 
let's do it anyway:

        if ext == 'CM':
            method = self.call_cm
            arguments = (cm, ad)
        if ext == 'MM':
            method = self.call_mm
            arguments = (mm, ax)
        if ext == 'DM':
            method = self.call_dm
            arguments = (dm, md)
        return method(*arguments)


Hardly worth it, is it? It's actually longer than the original.

Can we do better? Not really, but let's do it anyway:

       
        arguments = {'CM': (cm, ad), 
                     'MM': (mm, ax),
                     'DM': (dm, md)}
        method = getattr(self, "call_" + ext.lower())
        return method(*(arguments[ext]))

Shorter, but perhaps not more readable.

The following methods are all broken. They all need a "self" parameter.

 
>     def call_cm(cm, ad):
>         pass
>     def call_mm(mm, ax):
>         pass
>     def call_dm(dm, md):
>         pass



-- 
Steve

From alan.gauld at btinternet.com  Mon Dec 21 11:26:37 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 21 Dec 2015 16:26:37 +0000
Subject: [Tutor] Optimize the code - removing the multiple IF conditions
In-Reply-To: <CAExJxTO--WzrSfTyxari3nGN+qJ_ivA1ynW2Bh6TDN=Hct4HcQ@mail.gmail.com>
References: <CAExJxTO--WzrSfTyxari3nGN+qJ_ivA1ynW2Bh6TDN=Hct4HcQ@mail.gmail.com>
Message-ID: <n5997s$j35$1@ger.gmane.org>

On 21/12/15 12:22, Sunil Tech wrote:

> class OptIf(object):
>     """docstring for OptIf"""

This does not look like a useful class, it should probably
just be a function. Are you really going to have multiple
instances?

>     def opt_me(self, ext):
>         if ext == 'CM':
>             rec = self.call_cm(cm, ad)
>         if ext == 'MM':
>             rec = self.call_mm(mm, ax)
>         if ext == 'DM':
>             rec = self.call_dm(dm, md)
>         return rec

These should probably be an if/elif chain rather
than multiple if options (no risk of multiple
operations).

Without knowing more about what this is doing and what the
various parameters represent it's hard to be sure how best
to "optimise" it. Bear in mind too that optimising may mean
improving readability and the if statements may be more
readable and maintainable than any dictionary lookup
would be.

>     def call_cm(cm, ad):
>     def call_mm(mm, ax):
>     def call_dm(dm, md):

As methods they should have a self parameter.

But these look suspiciously like the same method
with different names. The first parameter looks
like it might be a size value. (But I've no idea
what the second is supposed to be.)

Could this be a single function which incorporates
a scaling factor?

> med_map = {'CM': call_cm, 'MM': call_mm, 'DM': call_dm}
> but I am not able to pass the arguments.

They all take two arguments so you can pass those in
if the types are consistent.

result = med_map[unit](arg1,arg2)

Your problems start if the parameters are all
different types. If that's the case you are probably
better sticking with the if chain. Or maybe creating
three real classes that can be instantiated as needed
and use polymorphism to avoid the if statements.

But without any more detail on what's really going on
I am just making wild guesses.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From jamiehu17 at yandex.com  Mon Dec 21 19:14:17 2015
From: jamiehu17 at yandex.com (jamie hu)
Date: Mon, 21 Dec 2015 16:14:17 -0800
Subject: [Tutor] Object oriented design
In-Reply-To: <n55s31$g2b$1@ger.gmane.org>
References: <3586891450500743@web28m.yandex.ru>
 <1365671450572538@web10g.yandex.ru> <n55s31$g2b$1@ger.gmane.org>
Message-ID: <2553521450743257@web13m.yandex.ru>

   *
   *
   20.12.2015, 01:25, "Alan Gauld" <alan.gauld at btinternet.com>:

     On 20/12/15 00:48, jamie hu wrote:

       ****trying to think/implement. I can create a given student object
       based on
       ****given firstname, lastname and grade. How do I find all objects
       matching
       ****particular criteria and return them to caller? Do I need to
       iterate/select
       ****through some list/database and create Student objects again?

     You need to store a referejce to each object in some kind of
     container - a list or dictionary for example, or maybe a full
     blown database.

       ****class Student():
       ***** def __init__(self,firstname,lastname,age):
       ***** * self.firstname = firstname
       ***** * self.lastname = lastname
       ***** * self.grade = grade

       ***** def set_grade(self,grade):
       ***** * self.grade = grade

       ***** @classmethod

       ***** # Find all Students with given lastname
       ***** def find_by_lastname():
       ***** * # How do I return all student objects that have same lastname?
       ***** * # Do I need to call init method again? I am confused here.
       ***** * pass

     You don't need to call init a second time but you do need to put
     your instances into a container as you create them. A common way
     to do this is to have a class attribute (ie not an instance one)
     called _instances or similar and have a line at the end
     of __init__() that does

     Student._instances.append(self)

     Your class method can then traverse the _instances collection
     checking each instance until it finds the desired object.

     If you have many objects, and especially if they will not
     all be instantiated at once you would use a database and
     in that case the class method would check the instances
     collection first to see if you already had the objectld
     in memory and, if not, instantiate it from the database.

     HTH

     --
     Alan G

   *
   *
   Thanks Alan. I was thinking about making a list of objects and search
   through it, but wasn't sure if that was right way.
   *
   I wasn't sure instantiation needed when using database, but it seems like
   that's the way. So ORM libraries do this work (fetch data and return
   instantiated objects) behind the scenes??
   *
   --
   Thanks,
   Jamie
   *

From jamiehu17 at yandex.com  Mon Dec 21 19:17:48 2015
From: jamiehu17 at yandex.com (jamie hu)
Date: Mon, 21 Dec 2015 16:17:48 -0800
Subject: [Tutor] Object oriented design
In-Reply-To: <CAGZAPF7XdGu3zoGCOdeXGr-kb0zexVtgfaiP3WPeb3qpnVqHNw@mail.gmail.com>
References: <3586891450500743@web28m.yandex.ru>
 <1365671450572538@web10g.yandex.ru>
 <CAGZAPF7XdGu3zoGCOdeXGr-kb0zexVtgfaiP3WPeb3qpnVqHNw@mail.gmail.com>
Message-ID: <2556011450743468@web13m.yandex.ru>

   *
   *
   20.12.2015, 12:49, "Danny Yoo" <dyoo at hashcollision.org>:

     On Sat, Dec 19, 2015 at 4:48 PM, jamie hu <[1]jamiehu17 at yandex.com>
     wrote:

       ****I am starting with Python object oriented concepts and have
       difficulty in
       ****understanding object instantiation. Below is an example code that
       I am
       ****trying to think/implement. I can create a given student object
       based on
       ****given firstname, lastname and grade. How do I find all objects
       matching
       ****particular criteria and return them to caller? Do I need to
       iterate/select
       ****through some list/database and create Student objects again?

     In order to find something, that something needs to be accessible from
     "somewhere".

     In typical beginner programs, that "somewhere" is an in-memory
     collection, like a list or dictionary, as Alan suggests. I'd expect,
     for your purposes, that this is an appropriate representation for
     "somewhere".

     find_by_lastname needs to know about this "somewhere". You have a few
     options. 1. You can either pass the "somewhere" in as an explicit
     parameter, or 2. hardcode it within find_by_lastname's definition.

     We expect that #1 will look something like:

     #####################################
     """Collection of things."""
     STUDENTS = []

     ...

     def find_by_lastname(students, lastname):
     ****"""Contract: listof(Student) string -> Student
     ****Given a list of students and a student's last name,
     ****returns the student with that last name.
     ****"""
     ***# ... fill me in

     ## later, we can call find_by_lastname, passing in the
     ## collection as an explicit argument.
     find_by_lastname(STUDENTS, "jamie")
     #####################################

     And #2 will probably look something like:

     #####################################
     """Collection of things."""
     STUDENTS = []

     ...

     def find_by_lastname(lastname):
     ****"""Contract: string -> Student
     ****Given a student's last name, returns the student
     ****with that last name, looking through STUDENTS.
     ****"""
     ***# ... fill me in

     ## later, we can call find_by_lastname, passing in the
     ## collection as an explicit argument.
     find_by_lastname("jamie")
     #####################################

     This is a rough sketch. So, which one do you choose?

     I have no idea!

     This is a decision point, and one that you need to resolve, because
     either choice has its own advantages and tradeoffs. Assuming this is
     an assignment, you need to talk with your instructor to see if there's
     one that they had in mind, or if this is something you get to decide.
     Personally, I don't like hardcoding, so #1 is my pick, but #2 has its
     advantages too: it's easier to call.

     Please feel free to ask questions. Good luck.

   *
   *
   Thanks Danny. I was confused about what to return and How? Should I return
   user objects for User.find_by_lastname() method and do I need to
   re-instantiate objects?
   *
   I think storing them as a list in memory solves this issue. If I were to
   use database I will need to search and create object again while returning
   to user. Is that right?*
   *
   --
   Jamie
   *
   *

     *

References

   Visible links
   1. mailto:jamiehu17 at yandex.com

From alan.gauld at btinternet.com  Mon Dec 21 20:58:30 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 22 Dec 2015 01:58:30 +0000
Subject: [Tutor] Object oriented design
In-Reply-To: <2553521450743257@web13m.yandex.ru>
References: <3586891450500743@web28m.yandex.ru>
 <1365671450572538@web10g.yandex.ru> <n55s31$g2b$1@ger.gmane.org>
 <2553521450743257@web13m.yandex.ru>
Message-ID: <n5aao6$oeo$1@ger.gmane.org>

On 22/12/15 00:14, jamie hu wrote:

>    Thanks Alan. I was thinking about making a list of objects and search
>    through it, but wasn't sure if that was right way.

For small numbers of objects( aa few hundreds say) its the easiest option.

>    I wasn't sure instantiation needed when using database, 

It makes life easier but only instantiate the objects you
need to work with.

If doing bulk updates or just searching for specific data
you can write SQL functions that work at database level.
But remember the rule of OOD - objects do it to themselves.
So you need to instantiate the objects to be able to
call their methods.

Sometimes a hybrid approach can work. Store the objects
in a dict keyed by ID. Use SQL to identify the object
you need then use the ID to fetch it from the dictionary
if its already instantiated otherwise use an ID based
init() method to fetch it from the database. That way
the select only has to return an ID and the object
instantiation fetches the specific data when you
need it. Remember that any updates to instance data
need to be written back to the database... The idea
is usually to  minimise the time any object lives in
memory since that's when its most vulnerable to unrecorded
changes and especially if more than one client or app
is accessing the same data.

>    that's the way. So ORM libraries do this work (fetch data and return
>    instantiated objects) behind the scenes??

Yes, that's exactly why they are used. They hide the fact
that there is a database there at all, it looks like you
are just working with objects in memory. At least that's
the theory, in practice there are usually some compromises!

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From dyoo at hashcollision.org  Mon Dec 21 21:15:15 2015
From: dyoo at hashcollision.org (Danny Yoo)
Date: Mon, 21 Dec 2015 18:15:15 -0800
Subject: [Tutor] Object oriented design
In-Reply-To: <n5aao6$oeo$1@ger.gmane.org>
References: <3586891450500743@web28m.yandex.ru>
 <1365671450572538@web10g.yandex.ru>
 <n55s31$g2b$1@ger.gmane.org> <2553521450743257@web13m.yandex.ru>
 <n5aao6$oeo$1@ger.gmane.org>
Message-ID: <CAGZAPF4nK7agqA+ASjrzz+Zfc2EeC9DyX995iXkL7fBzsjRF-w@mail.gmail.com>

On Mon, Dec 21, 2015 at 5:58 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> On 22/12/15 00:14, jamie hu wrote:
>
>>    Thanks Alan. I was thinking about making a list of objects and search
>>    through it, but wasn't sure if that was right way.
>
> For small numbers of objects( aa few hundreds say) its the easiest option.

If the data is small, it likely doesn't matter too much if you're
using an unsorted list.

For anything larger, but still in-memory, you may eventually want to
start considering the appropriate data structures for the operations
you're performing.  That's the kind of stuff a standard
data-structures/algorithms course talks about.

If we want to support exact lookups by key, a dictionary may be an
appropriate choice.  But we shouldn't immediately discount a sorted
list: binary search might also be appropriate.
(https://docs.python.org/3.1/library/bisect.html).  It's another
design choice that hinges on what operations we want to make go fast.

From alan.gauld at btinternet.com  Mon Dec 21 21:23:16 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 22 Dec 2015 02:23:16 +0000
Subject: [Tutor] Object oriented design
In-Reply-To: <2556011450743468@web13m.yandex.ru>
References: <3586891450500743@web28m.yandex.ru>
 <1365671450572538@web10g.yandex.ru>
 <CAGZAPF7XdGu3zoGCOdeXGr-kb0zexVtgfaiP3WPeb3qpnVqHNw@mail.gmail.com>
 <2556011450743468@web13m.yandex.ru>
Message-ID: <n5ac6j$f5g$1@ger.gmane.org>

On 22/12/15 00:17, jamie hu wrote:

>    I think storing them as a list in memory solves this issue. If I were to
>    use database I will need to search and create object again while returning
>    to user. Is that right?*

Yes, although you can keep a list of instantiated objects
in memory (sometimes referred to as an object pool or cache).
What you should not do with database is simply instantiate
every object in the database and keep it in memory for
the lifetime of the app.

You can either instantiate then delete as you go or sometimes
have a policy of using a fixed number of objects in memory
and delete on a least recently used basis. This is more work
but can yield performance improvements where a relatively
few objects get repeatedly accessed.

When you need to instantiate an object check the pool to see
if its already there, and if not such it out of the database.
You can hide most of that inside a factory function or class
method:

def getFoo(ID):
   try: return Foo._instances[ID]
   except KeyError: return Foo(ID)  # init() accesses DB

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From dyoo at hashcollision.org  Mon Dec 21 21:27:45 2015
From: dyoo at hashcollision.org (Danny Yoo)
Date: Mon, 21 Dec 2015 18:27:45 -0800
Subject: [Tutor] Object oriented design
In-Reply-To: <2556011450743468@web13m.yandex.ru>
References: <3586891450500743@web28m.yandex.ru>
 <1365671450572538@web10g.yandex.ru>
 <CAGZAPF7XdGu3zoGCOdeXGr-kb0zexVtgfaiP3WPeb3qpnVqHNw@mail.gmail.com>
 <2556011450743468@web13m.yandex.ru>
Message-ID: <CAGZAPF76CX-LnqdSrxnHK9g=Kqx-Np3zc3+j9v=nM3Sqo1iJiw@mail.gmail.com>

>
> Thanks Danny. I was confused about what to return and How? Should I return
> user objects for User.find_by_lastname() method and do I need to
> re-instantiate objects?
>

If we pull a value out of an in-memory container, we've got it already in hand.

For example, here's a little interaction:

#####################################
>>> class Person(object):
...     def __init__(self, name):
...         self.name = name
...
>>> people = [Person('jamie'), Person('alan')]
#####################################


'people' is a list of two people.  We can get at the first, or the
second, and they are 'People'.

#####################################
>>> firstPerson = people[0]
>>> secondPerson = people[1]
>>> firstPerson
<__main__.Person object at 0x7fdf6d9e1fd0>
>>> secondPerson
<__main__.Person object at 0x7fdf6d9f1050>
#####################################


That's a main point of an in-memory collection: we have ready,
immediate access to values that we've constructed.

If we do need to put those values "on ice", into longer-term storage,
then we do need to start considering the issues of translating those
in-memory values into sequential byte streams, also known as
"serialization".  The purpose of quite a few software libraries is to
manage the complexity of going from sequential byte streams back into
in-memory data structures.

From breamoreboy at yahoo.co.uk  Tue Dec 22 03:08:30 2015
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 22 Dec 2015 08:08:30 +0000
Subject: [Tutor] Object oriented design
In-Reply-To: <CAGZAPF4nK7agqA+ASjrzz+Zfc2EeC9DyX995iXkL7fBzsjRF-w@mail.gmail.com>
References: <3586891450500743@web28m.yandex.ru>
 <1365671450572538@web10g.yandex.ru> <n55s31$g2b$1@ger.gmane.org>
 <2553521450743257@web13m.yandex.ru> <n5aao6$oeo$1@ger.gmane.org>
 <CAGZAPF4nK7agqA+ASjrzz+Zfc2EeC9DyX995iXkL7fBzsjRF-w@mail.gmail.com>
Message-ID: <n5b0ea$um5$1@ger.gmane.org>

On 22/12/2015 02:15, Danny Yoo wrote:
> On Mon, Dec 21, 2015 at 5:58 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>> On 22/12/15 00:14, jamie hu wrote:
>>
>>>     Thanks Alan. I was thinking about making a list of objects and search
>>>     through it, but wasn't sure if that was right way.
>>
>> For small numbers of objects( aa few hundreds say) its the easiest option.
>
> If the data is small, it likely doesn't matter too much if you're
> using an unsorted list.
>
> For anything larger, but still in-memory, you may eventually want to
> start considering the appropriate data structures for the operations
> you're performing.  That's the kind of stuff a standard
> data-structures/algorithms course talks about.
>
> If we want to support exact lookups by key, a dictionary may be an
> appropriate choice.  But we shouldn't immediately discount a sorted
> list: binary search might also be appropriate.
> (https://docs.python.org/3.1/library/bisect.html).  It's another
> design choice that hinges on what operations we want to make go fast.

Theses are useful if you don't want to roll your own 
https://pypi.python.org/pypi/sortedcontainers

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

Mark Lawrence


From wuzzyluzy at gmail.com  Tue Dec 22 05:05:06 2015
From: wuzzyluzy at gmail.com (Satya Luzy)
Date: Tue, 22 Dec 2015 17:05:06 +0700
Subject: [Tutor] Is there a Big Integer Class in Python?
Message-ID: <CAAMZLuw9ZS4J_N1SGn3Q+zQz1JSeYYgZm4rMnVpJSDZzi+KvTQ@mail.gmail.com>

I'm currently making a cryptanalysis program that involves up to 150
integer digits.
The number will be used for multiplication and exponentiation purpose.
So, do I need to use something like a big integer class? or does that even
exist?

Thank you,

Python learner

From alan.gauld at btinternet.com  Tue Dec 22 08:29:25 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 22 Dec 2015 13:29:25 +0000
Subject: [Tutor] Is there a Big Integer Class in Python?
In-Reply-To: <CAAMZLuw9ZS4J_N1SGn3Q+zQz1JSeYYgZm4rMnVpJSDZzi+KvTQ@mail.gmail.com>
References: <CAAMZLuw9ZS4J_N1SGn3Q+zQz1JSeYYgZm4rMnVpJSDZzi+KvTQ@mail.gmail.com>
Message-ID: <n5bj7l$cdf$1@ger.gmane.org>

On 22/12/15 10:05, Satya Luzy wrote:
> I'm currently making a cryptanalysis program that involves up to 150
> integer digits.
> The number will be used for multiplication and exponentiation purpose.
> So, do I need to use something like a big integer class? or does that even
> exist?

Python integers are effectively big integers, no need of a special
class. Just use normal integers.

If in doubt try this (using Python v2):

>>> print 2 ** 500
327339060789614187001318969682759915221664204604306
478948329136809613379640467455488327009232590415715
0886684127560071009217256545885393053328527589376L

Notice the L at the end? That tells you python is using a
long integer. You only see that in Python v2. If you are
using v3 there is no L and no distinction between long
and regular integers.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From sunil.techspk at gmail.com  Tue Dec 22 09:41:57 2015
From: sunil.techspk at gmail.com (Sunil Tech)
Date: Tue, 22 Dec 2015 20:11:57 +0530
Subject: [Tutor] Optimize the code - removing the multiple IF conditions
In-Reply-To: <n5997s$j35$1@ger.gmane.org>
References: <CAExJxTO--WzrSfTyxari3nGN+qJ_ivA1ynW2Bh6TDN=Hct4HcQ@mail.gmail.com>
 <n5997s$j35$1@ger.gmane.org>
Message-ID: <CAExJxTPMykG06RJjCD=1vhN_PN8=Mu3Ew_m0i7iKSHkKRNwd=g@mail.gmail.com>

My heartly thanks to Steven D'Aprano, Alan Gauld and Peter Otten
? for addressing this.?

I would go with Steven D'Aprano
? point?
 and will take Alan Gauld inputs.
Thanks once again.


On Mon, Dec 21, 2015 at 9:56 PM, Alan Gauld <alan.gauld at btinternet.com>
wrote:

> On 21/12/15 12:22, Sunil Tech wrote:
>
> > class OptIf(object):
> >     """docstring for OptIf"""
>
> This does not look like a useful class, it should probably
> just be a function. Are you really going to have multiple
> instances?
>
> >     def opt_me(self, ext):
> >         if ext == 'CM':
> >             rec = self.call_cm(cm, ad)
> >         if ext == 'MM':
> >             rec = self.call_mm(mm, ax)
> >         if ext == 'DM':
> >             rec = self.call_dm(dm, md)
> >         return rec
>
> These should probably be an if/elif chain rather
> than multiple if options (no risk of multiple
> operations).
>
> Without knowing more about what this is doing and what the
> various parameters represent it's hard to be sure how best
> to "optimise" it. Bear in mind too that optimising may mean
> improving readability and the if statements may be more
> readable and maintainable than any dictionary lookup
> would be.
>
> >     def call_cm(cm, ad):
> >     def call_mm(mm, ax):
> >     def call_dm(dm, md):
>
> As methods they should have a self parameter.
>
> But these look suspiciously like the same method
> with different names. The first parameter looks
> like it might be a size value. (But I've no idea
> what the second is supposed to be.)
>
> Could this be a single function which incorporates
> a scaling factor?
>
> > med_map = {'CM': call_cm, 'MM': call_mm, 'DM': call_dm}
> > but I am not able to pass the arguments.
>
> They all take two arguments so you can pass those in
> if the types are consistent.
>
> result = med_map[unit](arg1,arg2)
>
> Your problems start if the parameters are all
> different types. If that's the case you are probably
> better sticking with the if chain. Or maybe creating
> three real classes that can be instantiated as needed
> and use polymorphism to avoid the if statements.
>
> But without any more detail on what's really going on
> I am just making wild guesses.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From alan.gauld at btinternet.com  Tue Dec 22 11:20:49 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 22 Dec 2015 16:20:49 +0000
Subject: [Tutor] Is there a Big Integer Class in Python?
In-Reply-To: <CAAMZLuyxdoiDCoYE7yp2dzp3M=s6dPywzNa1wiKdg4PAUu_17g@mail.gmail.com>
References: <CAAMZLuw9ZS4J_N1SGn3Q+zQz1JSeYYgZm4rMnVpJSDZzi+KvTQ@mail.gmail.com>
 <n5bj7l$cdf$1@ger.gmane.org>
 <CAAMZLuyxdoiDCoYE7yp2dzp3M=s6dPywzNa1wiKdg4PAUu_17g@mail.gmail.com>
Message-ID: <56797861.7090900@btinternet.com>

On 22/12/15 14:22, Satya Luzy wrote:
> Is there a way to extend the numbers so that there is no more L?

The L is only part of the representation it is not part of the data.
You use the data just like any other integer.

In Python v3 there is no L since there is no longer any distinction
between long and other integers.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


From wuzzyluzy at gmail.com  Tue Dec 22 09:22:03 2015
From: wuzzyluzy at gmail.com (Satya Luzy)
Date: Tue, 22 Dec 2015 21:22:03 +0700
Subject: [Tutor] Is there a Big Integer Class in Python?
In-Reply-To: <n5bj7l$cdf$1@ger.gmane.org>
References: <CAAMZLuw9ZS4J_N1SGn3Q+zQz1JSeYYgZm4rMnVpJSDZzi+KvTQ@mail.gmail.com>
 <n5bj7l$cdf$1@ger.gmane.org>
Message-ID: <CAAMZLuyxdoiDCoYE7yp2dzp3M=s6dPywzNa1wiKdg4PAUu_17g@mail.gmail.com>

Is there a way to extend the numbers so that there is no more L?

Thanks :)

On Tue, Dec 22, 2015 at 8:29 PM, Alan Gauld <alan.gauld at btinternet.com>
wrote:

> On 22/12/15 10:05, Satya Luzy wrote:
> > I'm currently making a cryptanalysis program that involves up to 150
> > integer digits.
> > The number will be used for multiplication and exponentiation purpose.
> > So, do I need to use something like a big integer class? or does that
> even
> > exist?
>
> Python integers are effectively big integers, no need of a special
> class. Just use normal integers.
>
> If in doubt try this (using Python v2):
>
> >>> print 2 ** 500
> 327339060789614187001318969682759915221664204604306
> 478948329136809613379640467455488327009232590415715
> 0886684127560071009217256545885393053328527589376L
>
> Notice the L at the end? That tells you python is using a
> long integer. You only see that in Python v2. If you are
> using v3 there is no L and no distinction between long
> and regular integers.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From dyoo at hashcollision.org  Tue Dec 22 17:17:19 2015
From: dyoo at hashcollision.org (Danny Yoo)
Date: Tue, 22 Dec 2015 14:17:19 -0800
Subject: [Tutor] Is there a Big Integer Class in Python?
In-Reply-To: <CAAMZLuyxdoiDCoYE7yp2dzp3M=s6dPywzNa1wiKdg4PAUu_17g@mail.gmail.com>
References: <CAAMZLuw9ZS4J_N1SGn3Q+zQz1JSeYYgZm4rMnVpJSDZzi+KvTQ@mail.gmail.com>
 <n5bj7l$cdf$1@ger.gmane.org>
 <CAAMZLuyxdoiDCoYE7yp2dzp3M=s6dPywzNa1wiKdg4PAUu_17g@mail.gmail.com>
Message-ID: <CAGZAPF4FVE1uehuo2UFVsTObXJY3foPb+PGNLOT73H6q-ooUkQ@mail.gmail.com>

On Tue, Dec 22, 2015 at 6:22 AM, Satya Luzy <wuzzyluzy at gmail.com> wrote:
> Is there a way to extend the numbers so that there is no more L?


Data can be presented in many different ways.  That's something that
you should have control over.  Rather than change the definition of
how numbers are representing in the machine, or do something
fundamental to change their internal structure, you can just present
them in the way you want.

A common term for presenting data for humans to consume is called
"formatting".  Take a look at:

    https://pyformat.info/

If we format a large number, it should show up in a form without the
"L" that signifies a long integer.

################################################################
>>> '{}'.format(2 ** 500)
'3273390607896141870013189696827599152216642046043064789483291368096133796404674554883270092325904157150886684127560071009217256545885393053328527589376'
################################################################


But this is not the only way that numbers can be presented.  For
example, we might consider using the 'humanize' library:

    https://pypi.python.org/pypi/humanize

#############################
import humanize
print(humanize.intcomma(2**100))
print(humanize.intword(2**100))
#############################

which, when I run it, shows:

######################################
1,267,650,600,228,229,401,496,703,205,376
1.3 nonillion
######################################


The main point is: presenting data for humans to consume is something
that *you* can control.  You can write functions from numbers to
strings, and those functions can do arbitrary things.

From jamiehu17 at yandex.com  Tue Dec 22 17:06:11 2015
From: jamiehu17 at yandex.com (jamie hu)
Date: Tue, 22 Dec 2015 14:06:11 -0800
Subject: [Tutor] Another OO modeling question
Message-ID: <1589081450821971@web9m.yandex.ru>

   *
   *
   I am trying to write down class and object definition for a Virtual
   Machine type. For example, I would like to create a Virtual Machine
   (object) that can have actions like launch, terminate, stop, add_disk,
   remove_disk etc..
   *
   My confusion here is that VirtualMachine object doesn't exist until it is
   actually launched successfully. So should the launch method be part of
   VirtualMachine class or some other VirtualMachineConfigurator class?
   Should*VirtualMachineConfigurator.launch() return VirtualMachine object or
   some string like vmid that can be used to create*VirtualMachine object??
   *
   Any help on modeling such objects would be helpful.
   *
   *
   Example class blueprint that I've been thinking:
   *
   class VirtualMachineConfigurator():
   * def __init__(self,memory,vcpu,network,base_image):
   * * * self.memory = memory
   * * * self.vcpu = vcpu
   * * * self.network = network
   * * * self.base_image = base_image
   *
   def launch(self)
   * """ Launches Virtual Machine and returns VirtualMachine object """
   * try:
   * * vm = hypervisor_conn.launch_vm(self.memory, self.vcpu, self.network,
   self.base_image)
   * * return vm
   * except Exception as e:
   * * raise e
   *
   *
   class VirtualMachine():
   * def __init__(self, vmid):
   * * self.vmid = vmid
   *
   * def stop(self):
   * * """ Stops VM"""
   * **
   * def attach_disk(self):
   *
   *
   --
   Thanks,
   Jamie

From rahulkumar5july at gmail.com  Tue Dec 22 16:45:49 2015
From: rahulkumar5july at gmail.com (Rahul Kumar)
Date: Wed, 23 Dec 2015 03:15:49 +0530
Subject: [Tutor] Python script for ganglia
Message-ID: <CA+FcjO43Xyrk52r1+bd-t-Sr2oUtcP_zk1bpKjTvD33W7j098Q@mail.gmail.com>

Hi,
I would like to know about how python can be use to get data from
ganglia monitoring tool.
For example,this link show the live production Ganglia instance for Wikimedia
http://ganglia.wikimedia.org/latest/
There are various of graphs have detail about grid load,grid memory,
grid cpu, grid network.
Ganglia is also running on my server.
How to write a python script for get data directly from ganglia and
store last hour monitoring detail in database,so that i can use this
information for other purposes.
i have average knowledge of python.
Is it possible with python?
How can i get this information from ganglia tool running on my server
using python ?

Regards,
Rahul

From alan.gauld at btinternet.com  Tue Dec 22 18:24:54 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 22 Dec 2015 23:24:54 +0000
Subject: [Tutor] Another OO modeling question
In-Reply-To: <1589081450821971@web9m.yandex.ru>
References: <1589081450821971@web9m.yandex.ru>
Message-ID: <n5cm45$g67$1@ger.gmane.org>

On 22/12/15 22:06, jamie hu wrote:
>    *
>    *
>    I am trying to write down class and object definition for a Virtual
>    Machine type. For example, I would like to create a Virtual Machine
>    (object) that can have actions like launch, terminate, stop, add_disk,
>    remove_disk etc..
>    *

Seems reasonable.

>    My confusion here is that VirtualMachine object doesn't exist until it is
>    actually launched successfully. 

Most objects don't exist until they are created, so it looks like
your init() method may need to call the launch code.


> So should the launch method be part of
>    VirtualMachine class or some other VirtualMachineConfigurator class?

Sounds like you just include it as part of the creation mechanism.
Alternatively you can use a class method that returns a new machine
instance.


>    Should*VirtualMachineConfigurator.launch() return VirtualMachine object

In general objects should do it to themselves so I'd suggest you either
1) include the configuration as part of construction
2) configure the machine when you create it then launch(start) it
   after the object comes into existence
3 If (and only if) all instances will share configuration you can make
the config mechanism a class method and the config settings class
attributes, but that seems very unlikely.

>    Example class blueprint that I've been thinking:
>    *
>    class VirtualMachineConfigurator():
>    * def __init__(self,memory,vcpu,network,base_image):
>    * * * self.memory = memory
>    * * * self.vcpu = vcpu
>    * * * self.network = network
>    * * * self.base_image = base_image
>    *
>    def launch(self)
>    * """ Launches Virtual Machine and returns VirtualMachine object """
>    * try:
>    * * vm = hypervisor_conn.launch_vm(self.memory, self.vcpu, self.network,
>    self.base_image)
>    * * return vm
>    * except Exception as e:
>    * * raise e

Just put that code into your VirtualMachine class.

>    class VirtualMachine():
>    * def __init__(self, vmid):
>    * * self.vmid = vmid

and add the init() code to launch() above

>    * def stop(self):
>    * * """ Stops VM"""
>    * **
>    * def attach_disk(self):

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From steve at pearwood.info  Tue Dec 22 19:09:14 2015
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 23 Dec 2015 11:09:14 +1100
Subject: [Tutor] Python script for ganglia
In-Reply-To: <CA+FcjO43Xyrk52r1+bd-t-Sr2oUtcP_zk1bpKjTvD33W7j098Q@mail.gmail.com>
References: <CA+FcjO43Xyrk52r1+bd-t-Sr2oUtcP_zk1bpKjTvD33W7j098Q@mail.gmail.com>
Message-ID: <20151223000914.GS1609@ando.pearwood.info>

On Wed, Dec 23, 2015 at 03:15:49AM +0530, Rahul Kumar wrote:
> Hi,
> I would like to know about how python can be use to get data from
> ganglia monitoring tool.

This may be a bit too specialised for a beginner's list like this, but 
we can try.

Is there a Ganglia discussion list or forum where you can ask? Does it 
provide an API for accessing data, or do you have to screen-scrape from 
the displayed web-page?

Have you googled for any information? E.g. start here:

https://duckduckgo.com/html/?q=ganglia+api+python


which looks like it may put you on the right track.


-- 
Steve

From jamiehu17 at yandex.com  Tue Dec 22 18:47:31 2015
From: jamiehu17 at yandex.com (jamie hu)
Date: Tue, 22 Dec 2015 15:47:31 -0800
Subject: [Tutor] Another OO modeling question
In-Reply-To: <n5cm45$g67$1@ger.gmane.org>
References: <1589081450821971@web9m.yandex.ru> <n5cm45$g67$1@ger.gmane.org>
Message-ID: <1665341450828051@web14j.yandex.ru>

   *
   *
   22.12.2015, 15:26, "Alan Gauld" <alan.gauld at btinternet.com>:

     On 22/12/15 22:06, jamie hu wrote:

       *****
       *****
       ****I am trying to write down class and object definition for a
       Virtual
       ****Machine type. For example, I would like to create a Virtual
       Machine
       ****(object) that can have actions like launch, terminate, stop,
       add_disk,
       ****remove_disk etc..
       *****

     Seems reasonable.

       ****My confusion here is that VirtualMachine object doesn't exist
       until it is
       ****actually launched successfully.

     Most objects don't exist until they are created, so it looks like
     your init() method may need to call the launch code.

       *So should the launch method be part of
       ****VirtualMachine class or some other VirtualMachineConfigurator
       class?

     Sounds like you just include it as part of the creation mechanism.
     Alternatively you can use a class method that returns a new machine
     instance.

       ****Should*VirtualMachineConfigurator.launch() return VirtualMachine
       object

     In general objects should do it to themselves so I'd suggest you either
     1) include the configuration as part of construction
     2) configure the machine when you create it then launch(start) it
     ***after the object comes into existence
     3 If (and only if) all instances will share configuration you can make
     the config mechanism a class method and the config settings class
     attributes, but that seems very unlikely.

       ****Example class blueprint that I've been thinking:
       *****
       ****class VirtualMachineConfigurator():
       ***** def __init__(self,memory,vcpu,network,base_image):
       ***** * * self.memory = memory
       ***** * * self.vcpu = vcpu
       ***** * * self.network = network
       ***** * * self.base_image = base_image
       *****
       ****def launch(self)
       ***** """ Launches Virtual Machine and returns VirtualMachine object
       """
       ***** try:
       ***** * vm = hypervisor_conn.launch_vm(self.memory, self.vcpu,
       self.network,
       ****self.base_image)
       ***** * return vm
       ***** except Exception as e:
       ***** * raise e

     Just put that code into your VirtualMachine class.

       ****class VirtualMachine():
       ***** def __init__(self, vmid):
       ***** * self.vmid = vmid

     and add the init() code to launch() above

       ***** def stop(self):
       ***** * """ Stops VM"""
       ***** **
       ***** def attach_disk(self):

     *

     --
     Alan G

   *
   Thanks for the reply Alan. If init code calls launch method then I would
   have problems in looking up objects afterwards.
   *
   For example:
   1. First or initial calls to VirtualMachine(memory, vcpu, network,
   base_image) will try to launch a VM and return a vmid string.
   2. Now if I need to terminate all VMs with a specific base_image then I
   will use VirtualMachine.find_by_baseimage() method. This needs to
   return*VirtualMachine objects with matching base image.
   3. If this data was stored in a database then, before returning this data
   I will need to call init method again.
   *
   As init is calling launch method, wouldn't this trigger VM launch again?
   *
   Or am I missing something here?
   *
   -*jM
   *
   *

From alan.gauld at btinternet.com  Tue Dec 22 19:31:26 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 23 Dec 2015 00:31:26 +0000
Subject: [Tutor] Another OO modeling question
In-Reply-To: <1665341450828051@web14j.yandex.ru>
References: <1589081450821971@web9m.yandex.ru> <n5cm45$g67$1@ger.gmane.org>
 <1665341450828051@web14j.yandex.ru>
Message-ID: <5679EB5E.9010901@btinternet.com>

On 22/12/15 23:47, jamie hu wrote:
> Thanks for the reply Alan. If init code calls launch method then I
> would have problems in looking up objects afterwards.

In that case use the init to do the config then explicitly call the launch.

> For example:
> 1. First or initial calls to VirtualMachine(memory, vcpu, network,
> base_image) will try to launch a VM and return a vmid string.
> 2. Now if I need to terminate all VMs with a specific base_image then
> I will use VirtualMachine.find_by_baseimage() method. This needs to
> return VirtualMachine objects with matching base image.

This is the same as your previous question, so I'd store the VMs in a
dictionary keyed by vmid. I'd put the dictionary in the class (not the
instance)
as an attribute. And i'd make the find method a class method.

> 3. If this data was stored in a database then, before returning this
> data I will need to call init method again.

Yes, but would you really be running so many virtual machines that you'd
store it in a database? Maybe if you run a very large data center you would
but that seems an unlikely use for a database. But if you wanted to and
didn't want to start an identical VM then you definitely need to keep
the init
for config and have a separate launch() method.

See previous mails for how to instantiate an existing object from the
database.

> As init is calling launch method, wouldn't this trigger VM launch again?
> Or am I missing something here?

No, it's just that you've now included several extra requirements that
weren't in the original spec.  The requirements largely determine the
design.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


From vrkratheesh at live.com  Wed Dec 23 02:29:10 2015
From: vrkratheesh at live.com (Ratheesh kumar)
Date: Wed, 23 Dec 2015 12:59:10 +0530
Subject: [Tutor] File reading-(encoding problems)
Message-ID: <SNT148-W5379CD9E0E61C26227F805D8E60@phx.gbl>

Here is my code..try:
    data=open('info.txt')
    for each_line in data:
        try:
            (role,line_spoken)=each_line.split(':',1)
            print(role,end='')
            print(' said: ',end='')
            print(line_spoken,end='')
        except ValueError:
            print(each_line)
    data.close()
except IOError:
     print("File is missing")The actual output is 
???Man said:  Is this the right room for an argument?
Other Man said:  I've told you once.
Man said:  No you haven't!
Other Man said:  Yes I have.The characters  "???"  got added to the contents of my file in the beginning. Later identified it as a encoding problem. I cleared the problem by adding the encoding arguments when opening the file( data=open('info.txt',encoding='utf-8-sig')).Now my question is each time do I have to make this change or is there away to make this encoding a default one? 		 	   		  

From ben+python at benfinney.id.au  Wed Dec 23 05:28:24 2015
From: ben+python at benfinney.id.au (Ben Finney)
Date: Wed, 23 Dec 2015 21:28:24 +1100
Subject: [Tutor] File reading-(encoding problems)
References: <SNT148-W5379CD9E0E61C26227F805D8E60@phx.gbl>
Message-ID: <857fk51mt3.fsf@benfinney.id.au>

Ratheesh kumar <vrkratheesh at live.com> writes:

> Here is my code..try:
>     data=open('info.txt')

[?]

Please be sure to present the code as distinct lines.

You have posted it as plain text (good), the indentation is preserved
(good). The problem here is that your commentary is mingled with the
program code, so that it's difficult to see where the program begins and
ends.

> Man said:  No you haven't!
> Other Man said:  Yes I have.The characters  "???"  got added to the
> contents of my file in the beginning.

And again here, you've somehow got your commentary stuck directly onto
the output example. Please be sure to use one empty line to surround any
code examples or output examples.

> Later identified it as a encoding problem. I cleared the problem by
> adding the encoding arguments when opening the file(
> data=open('info.txt',encoding='utf-8-sig')).Now my question is each
> time do I have to make this change or is there away to make this
> encoding a default one?

Yes, you need to specify the encoding of text, when you input or output
that text as bytes (e.g. in a file). Representing text as bytes is done
with a text encoding, and you must be explicit about that encoding
because guessing the encoding leads to heartache.

Your use of an explicit encoding in that program is correct.

-- 
 \        ?I took it easy today. I just pretty much layed around in my |
  `\        underwear all day. ? Got kicked out of quite a few places, |
_o__)                              though.? ?Bug-Eyed Earl, _Red Meat_ |
Ben Finney


From jf_byrnes at comcast.net  Wed Dec 23 17:58:24 2015
From: jf_byrnes at comcast.net (Jim Byrnes)
Date: Wed, 23 Dec 2015 16:58:24 -0600
Subject: [Tutor] Using python 3 on Ubuntu 14.04
Message-ID: <n5f8uh$hib$1@ger.gmane.org>

I am in the process of moving from unbutu 12.04 to 14.04. I was doing 
some testing and got this:

jfb at Jims-1404:~$ cd MyProgs
jfb at Jims-1404:~/MyProgs$ cd passwords
jfb at Jims-1404:~/MyProgs/passwords$ python3 passwords.py
Traceback (most recent call last):
   File "passwords.py", line 8, in <module>
     from PythonCard import  model,clipboard
ImportError: No module named 'PythonCard'

If I simply start it with  python passwords.py  it runs fine. There is 
no need to use python 3 on this particular program but if I wanted to 
write for python 3 in the future what do I need to do to run programs 
with it?

Thanks,  Jim


From ben+python at benfinney.id.au  Wed Dec 23 18:03:50 2015
From: ben+python at benfinney.id.au (Ben Finney)
Date: Thu, 24 Dec 2015 10:03:50 +1100
Subject: [Tutor] Using python 3 on Ubuntu 14.04
References: <n5f8uh$hib$1@ger.gmane.org>
Message-ID: <85h9j8zs15.fsf@benfinney.id.au>

Jim Byrnes <jf_byrnes at comcast.net> writes:

> If I simply start it with  python passwords.py  it runs fine.

If you type ?python --version? and ?python3 --version? you will see two
different version numbers.

Different versions of Python have their own separate run-time
environments. Any modules you want a particular Python interpreter to
import, must be installed specifically for that interperter to find.

> There is no need to use python 3 on this particular program but if I
> wanted to write for python 3 in the future what do I need to do to run
> programs with it?

You need to install the Python 3 modules for the correct Python 3
version.

-- 
 \        ?It is undesirable to believe a proposition when there is no |
  `\   ground whatever for supposing it true.? ?Bertrand Russell, _The |
_o__)                                       Value of Scepticism_, 1928 |
Ben Finney


From akleider at sonic.net  Wed Dec 23 18:10:44 2015
From: akleider at sonic.net (Alex Kleider)
Date: Wed, 23 Dec 2015 15:10:44 -0800
Subject: [Tutor] Using python 3 on Ubuntu 14.04
In-Reply-To: <n5f8uh$hib$1@ger.gmane.org>
References: <n5f8uh$hib$1@ger.gmane.org>
Message-ID: <645c9abe388549f947d7bdee0a020f1b@sonic.net>

On 2015-12-23 14:58, Jim Byrnes wrote:
> I am in the process of moving from unbutu 12.04 to 14.04. I was doing
> some testing and got this:
> 
> jfb at Jims-1404:~$ cd MyProgs
> jfb at Jims-1404:~/MyProgs$ cd passwords
> jfb at Jims-1404:~/MyProgs/passwords$ python3 passwords.py
> Traceback (most recent call last):
>   File "passwords.py", line 8, in <module>
>     from PythonCard import  model,clipboard
> ImportError: No module named 'PythonCard'
> 
> If I simply start it with  python passwords.py  it runs fine. There is
> no need to use python 3 on this particular program but if I wanted to
> write for python 3 in the future what do I need to do to run programs
> with it?
> 
> Thanks,  Jim

Jim, make

#!/usr/bin/env python3

the very first line in your myscript.py file
and change it's permissions with the following command:

chmod 775 myscript.py

Then you'll be able to run it simply by entering

./password.py

on the command line.

PS I don't think this will fix your current problem which is
probably the result of importing something that exists with
Python 2 but not 3- specifically PythonCard.


From breamoreboy at yahoo.co.uk  Wed Dec 23 19:00:17 2015
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Thu, 24 Dec 2015 00:00:17 +0000
Subject: [Tutor] Using python 3 on Ubuntu 14.04
In-Reply-To: <n5f8uh$hib$1@ger.gmane.org>
References: <n5f8uh$hib$1@ger.gmane.org>
Message-ID: <n5fciv$76k$1@ger.gmane.org>

On 23/12/2015 22:58, Jim Byrnes wrote:
> I am in the process of moving from unbutu 12.04 to 14.04. I was doing
> some testing and got this:
>
> jfb at Jims-1404:~$ cd MyProgs
> jfb at Jims-1404:~/MyProgs$ cd passwords
> jfb at Jims-1404:~/MyProgs/passwords$ python3 passwords.py
> Traceback (most recent call last):
>    File "passwords.py", line 8, in <module>
>      from PythonCard import  model,clipboard
> ImportError: No module named 'PythonCard'
>
> If I simply start it with  python passwords.py  it runs fine. There is
> no need to use python 3 on this particular program but if I wanted to
> write for python 3 in the future what do I need to do to run programs
> with it?
>
> Thanks,  Jim
>

Read this https://docs.python.org/3/howto/pyporting.html.

Find a replacement for anything that relies on PythonCard as it hasn't 
been supported for years.

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

Mark Lawrence


From nnamdi.anyanwu at gmail.com  Wed Dec 23 18:15:34 2015
From: nnamdi.anyanwu at gmail.com (Nnamdi Anyanwu)
Date: Wed, 23 Dec 2015 18:15:34 -0500
Subject: [Tutor] Using python 3 on Ubuntu 14.04
In-Reply-To: <645c9abe388549f947d7bdee0a020f1b@sonic.net>
References: <n5f8uh$hib$1@ger.gmane.org>
 <645c9abe388549f947d7bdee0a020f1b@sonic.net>
Message-ID: <CAM7omEv19Xfto-CjFHZKREaPYYauwseqDzjZSmfCPTS07GCH0w@mail.gmail.com>

If you're installing modules with pip, install pip3 and install the
appropriate modules using pip3 instead of using regular pip.
On Dec 24, 2015 12:12 AM, "Alex Kleider" <akleider at sonic.net> wrote:

> On 2015-12-23 14:58, Jim Byrnes wrote:
>
>> I am in the process of moving from unbutu 12.04 to 14.04. I was doing
>> some testing and got this:
>>
>> jfb at Jims-1404:~$ cd MyProgs
>> jfb at Jims-1404:~/MyProgs$ cd passwords
>> jfb at Jims-1404:~/MyProgs/passwords$ python3 passwords.py
>> Traceback (most recent call last):
>>   File "passwords.py", line 8, in <module>
>>     from PythonCard import  model,clipboard
>> ImportError: No module named 'PythonCard'
>>
>> If I simply start it with  python passwords.py  it runs fine. There is
>> no need to use python 3 on this particular program but if I wanted to
>> write for python 3 in the future what do I need to do to run programs
>> with it?
>>
>> Thanks,  Jim
>>
>
> Jim, make
>
> #!/usr/bin/env python3
>
> the very first line in your myscript.py file
> and change it's permissions with the following command:
>
> chmod 775 myscript.py
>
> Then you'll be able to run it simply by entering
>
> ./password.py
>
> on the command line.
>
> PS I don't think this will fix your current problem which is
> probably the result of importing something that exists with
> Python 2 but not 3- specifically PythonCard.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From alan.gauld at btinternet.com  Wed Dec 23 20:50:28 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 24 Dec 2015 01:50:28 +0000
Subject: [Tutor] Using python 3 on Ubuntu 14.04
In-Reply-To: <n5fciv$76k$1@ger.gmane.org>
References: <n5f8uh$hib$1@ger.gmane.org> <n5fciv$76k$1@ger.gmane.org>
Message-ID: <n5fj13$1md$1@ger.gmane.org>

On 24/12/15 00:00, Mark Lawrence wrote:

> Find a replacement for anything that relies on PythonCard as it hasn't 
> been supported for years.

"Years" might be a bit much, there was an update for most
distros 10 months ago, so its not quite dead. But since it
relies on wxPython and that doesn't yet support Python 3
the result is the same. If you need it to work on python3
don't use PythonCard

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at btinternet.com  Wed Dec 23 20:52:07 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 24 Dec 2015 01:52:07 +0000
Subject: [Tutor] Using python 3 on Ubuntu 14.04
In-Reply-To: <CAM7omEv19Xfto-CjFHZKREaPYYauwseqDzjZSmfCPTS07GCH0w@mail.gmail.com>
References: <n5f8uh$hib$1@ger.gmane.org>
 <645c9abe388549f947d7bdee0a020f1b@sonic.net>
 <CAM7omEv19Xfto-CjFHZKREaPYYauwseqDzjZSmfCPTS07GCH0w@mail.gmail.com>
Message-ID: <n5fj46$1md$2@ger.gmane.org>

On 23/12/15 23:15, Nnamdi Anyanwu wrote:
> If you're installing modules with pip, install pip3 and install the
> appropriate modules using pip3 instead of using regular pip.

Most v3 modules are also available via the Ubuntu package system
so you can install via synaptic which I tend to find more reliable
than pip.

YMMV,

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From rbekenstein at mail.com  Wed Dec 23 20:45:50 2015
From: rbekenstein at mail.com (Richard Bekenstein)
Date: Thu, 24 Dec 2015 02:45:50 +0100
Subject: [Tutor] Modules and variable usage in functions from other files
Message-ID: <trinity-02007098-fc0c-46d3-bb6a-4ec0fed4b77f-1450921550262@3capp-mailcom-lxa08>

   Dear All,

   I have a main .py script which contains code that occasionally calls some
   functions. This script calls in these defined functions from other .py
   files in the same directory as the main .py. However, even after importing
   the functions from the different .py files, I get error messages, such as
   "global name 'np' is not defined" even though I define "import numpy as
   np" initially in my main .py script.
   To show some detail, I import some modules at the beggining of my main .py
   script as such:

       from scipy.constants import m_p,G,k
       import numpy as np
       from math import cos, pi, floor
       import matplotlib.pyplot as plt
       from findall import findall
       from pylab import *
       import sys
       import timeit
       from copy import copy
       from array import array
       from bol_heatFTCS_nonadaptive import heatFTCS #this is my first
   user-defined function that calls the defined function 'heatFTCS' from file
   'bol_heatFTCS_nonadaptive.py'
       from bol_runge_kutta_functions import dy1_dt,dy2_dt,dy3_dt,dy5_dt
   #this is my second user-defined function that calls the defined functions
   'dyi_dt's from file 'bol_runge_kutta_functions.py'
       from bol_runge_kutta_evl_nonadaptive import runge_kutta_evl #this is
   my first user-defined function that calls the defined function
   'runge_kutta_evl' from file 'bol_runge_kutta_evl_nonadaptive.py'
       m_range,p_range,T_range,r_range,rho_range = np.loadtxt('(there are
   some other directories here that don't matter for this
   discussion)/planetary_structure_params.txt', unpack=True,
   usecols=[0,1,2,3,4])  #imports some data to 5 arrays


   When I run this main.py, I get an error message from the imported
   'runge_kutta_evl' function that numpy is not defined. Why is it that even
   though I have it defined in my script it does not recognize it in my
   function called to the script? It turns out that even if I then state
   'import numpy as np' in my 'runge_kutta_evl' function, I then another
   error that 'r_range' is not defined. But aren't 'r_range' and 'np'
   supposed to be accesible to all called functions in the main .py?

   Thank you,
   R.B.

From alan.gauld at btinternet.com  Thu Dec 24 05:28:43 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 24 Dec 2015 10:28:43 +0000
Subject: [Tutor] Modules and variable usage in functions from other files
In-Reply-To: <trinity-02007098-fc0c-46d3-bb6a-4ec0fed4b77f-1450921550262@3capp-mailcom-lxa08>
References: <trinity-02007098-fc0c-46d3-bb6a-4ec0fed4b77f-1450921550262@3capp-mailcom-lxa08>
Message-ID: <n5ghcr$5hg$1@ger.gmane.org>

On 24/12/15 01:45, Richard Bekenstein wrote:

>        from scipy.constants import m_p,G,k
>        import numpy as np
>        from math import cos, pi, floor
...
>        from bol_runge_kutta_evl_nonadaptive import runge_kutta_evl 

>    When I run this main.py, I get an error message from the imported
>    'runge_kutta_evl' function that numpy is not defined. Why is it that even
>    though I have it defined in my script it does not recognize it in my
>    function called to the script? 

The function is in the other module. You only imported the names
into your main module, that does not make them visible in the
other modules.

Making the function *name* visible in main (by importing it) does
not make the function *object* to which the name refers part of
main. The function object remains in the original module. So
you need to import all of the names the function uses into
its module too.(**)

> It turns out that even if I then state
>    'import numpy as np' in my 'runge_kutta_evl' function, I then another
>    error that 'r_range' is not defined. But aren't 'r_range' and 'np'
>    supposed to be accesible to all called functions in the main .py?

They are visible in main but they are not visible in the
other modules that main imports. Importing only makes things
visible to the module doing the importing. Python has no
concept of a "main" module as a kind of global namespace,
it treats your main.py just like any other module. It only
exposes the names you import to main.py Every module must
import the names it needs and in that way becomes an
independent, and therefore reusable, piece of code.

BTW In future, please include the full error message in any
posts. Although in this case we could just about guess
what it looked like, its better to see a cut n' paste
version in case there are subtle clues hidden in the message.

(**)The fact you are getting these kinds of errors suggests
you are not testing the individual modules in isolation
from your main program. It's a good habit to (as a minimum!)
import any modules you write into the interpreter and exercise
the functions manually to be sure they work. That would have
revealed that the modules did not have access to all the
names they needed to work. Even better would be to start
using some of the automated test tools such as unittest
or doctest to ensure your modules work consistently after
each change.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From robertvstepp at gmail.com  Thu Dec 24 09:54:04 2015
From: robertvstepp at gmail.com (boB Stepp)
Date: Thu, 24 Dec 2015 08:54:04 -0600
Subject: [Tutor] OT: How to automate user interactions with GUI elements of
 closed-source programs?
Message-ID: <CANDiX9JWpVdqeq8NkbFF=uGtSZr-ri+44NGSFPzKdDP_TPDocQ@mail.gmail.com>

My Google-fu is weak on this question.  I keep getting lots of hits on
web scraping, but my interest is actually as follows:

I find myself doing the same boring, repetitive tasks by hand, which
amounts to copying certain information from one program and putting it
into other programs.  None of these programs, to my knowledge, have a
publicly accessible API.  Are there ways to programmatically
accurately click the right buttons (or check boxes, radio buttons,
etc.), copy desired fields and then switch to another program and
paste the desired information into the desired fields, accurately
clicking all things that need to be clicked, etc.?  This is mostly a
Windows-based scenario, but if the techniques (if they exist) can be
abstracted to any OS I can find plenty of uses elsewhere as well!

TIA!
Merry Christmas!!!

-- 
boB

From jf_byrnes at comcast.net  Thu Dec 24 11:51:25 2015
From: jf_byrnes at comcast.net (Jim Byrnes)
Date: Thu, 24 Dec 2015 10:51:25 -0600
Subject: [Tutor] OT: How to automate user interactions with GUI elements
 of closed-source programs?
In-Reply-To: <CANDiX9JWpVdqeq8NkbFF=uGtSZr-ri+44NGSFPzKdDP_TPDocQ@mail.gmail.com>
References: <CANDiX9JWpVdqeq8NkbFF=uGtSZr-ri+44NGSFPzKdDP_TPDocQ@mail.gmail.com>
Message-ID: <n5h7qe$cmb$1@ger.gmane.org>

On 12/24/2015 08:54 AM, boB Stepp wrote:
> My Google-fu is weak on this question.  I keep getting lots of hits on
> web scraping, but my interest is actually as follows:
>
> I find myself doing the same boring, repetitive tasks by hand, which
> amounts to copying certain information from one program and putting it
> into other programs.  None of these programs, to my knowledge, have a
> publicly accessible API.  Are there ways to programmatically
> accurately click the right buttons (or check boxes, radio buttons,
> etc.), copy desired fields and then switch to another program and
> paste the desired information into the desired fields, accurately
> clicking all things that need to be clicked, etc.?  This is mostly a
> Windows-based scenario, but if the techniques (if they exist) can be
> abstracted to any OS I can find plenty of uses elsewhere as well!
>
> TIA!
> Merry Christmas!!!
>

I don't know if there is a Python solution, as I am just starting to 
read up on using Python on the web. Either iMarcos or GreaseMonkey could 
probably do what you what you want.

Both are browser extensions.  iMacros is available for both Firefox and 
Chrome, GreaseMonkey is available for Firefox, but I'm not sure about 
Chrome. Both also have user forums.

Regards,  Jim


From oscar.j.benjamin at gmail.com  Thu Dec 24 12:34:06 2015
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Thu, 24 Dec 2015 17:34:06 +0000
Subject: [Tutor] OT: How to automate user interactions with GUI elements
 of closed-source programs?
In-Reply-To: <CANDiX9JWpVdqeq8NkbFF=uGtSZr-ri+44NGSFPzKdDP_TPDocQ@mail.gmail.com>
References: <CANDiX9JWpVdqeq8NkbFF=uGtSZr-ri+44NGSFPzKdDP_TPDocQ@mail.gmail.com>
Message-ID: <CAHVvXxTT=JaX-WuOEYJr4_E8-fJtjaxQA2O6HJfhXeEEN9siRw@mail.gmail.com>

On 24 Dec 2015 14:55, "boB Stepp" <robertvstepp at gmail.com> wrote:
>
> My Google-fu is weak on this question.  I keep getting lots of hits on
> web scraping, but my interest is actually as follows:
>
> I find myself doing the same boring, repetitive tasks by hand, which
> amounts to copying certain information from one program and putting it
> into other programs.  None of these programs, to my knowledge, have a
> publicly accessible API.  Are there ways to programmatically
> accurately click the right buttons (or check boxes, radio buttons,
> etc.), copy desired fields and then switch to another program and
> paste the desired information into the desired fields, accurately
> clicking all things that need to be clicked, etc.?  This is mostly a
> Windows-based scenario, but if the techniques (if they exist) can be
> abstracted to any OS I can find plenty of uses elsewhere as well!

This is certainly doable for Windows. You can make the mouse move and click
on things, send keypress events. Look for Windows specific modules like
pywin32 etc. I've done this from Python possibly using ctypes but I don't
remember exactly.

For OSX I think there's a policy that prohibits programmatic control of
user interfaces. There will be solutions for all X11 systems (Linux etc) as
well.

Don't expect anything for all OSes but searching PyPI is probably
worthwhile...

...I googled "Python windows control mouse" and got:

http://stackoverflow.com/questions/1181464/controlling-mouse-with-python

Also this:
https://pypi.python.org/pypi/PyAutoGUI

Which apparently does solve the problem for the main platforms (contrary to
what I wrote above).

--
Oscar

From marcus.luetolf at bluewin.ch  Thu Dec 24 12:21:37 2015
From: marcus.luetolf at bluewin.ch (=?utf-8?Q?marcus_l=C3=BCtolf?=)
Date: Thu, 24 Dec 2015 18:21:37 +0100
Subject: [Tutor] trouble with beautiful soup
Message-ID: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>

dear pythonistas,
for hours I'am traying to use Beautiful Soup for scraping some websites as an exercise.
But each time I run the code below:

>>> import urllib
>>> from BeautifulSpoup import *

>>> url =  raw_input( 'Enter -')
                  
>>> html = urllib.urlopen(url).read()

>>> soup = BeautifulSoup(html)
>>> print soup

I am getting the following trace back without beeing prompted for an input:

Traceback (most recent call last):
  File "C:/Python27/Beautiful Soup_ex1.py", line 2, in <module>
    from beautifulspoup import *
ImportError: No module named beautifulspoup

I have installed and unzipped etc. the latest file from www.crummy.com many times. 
If I click setup.py the command window appears only a fraction of a second.
??????

Happy holidays and thanks for help, Marcus.





---
Diese E-Mail wurde von Avast Antivirus-Software auf Viren gepr?ft.
https://www.avast.com/antivirus


From joskerc at gmail.com  Thu Dec 24 13:50:12 2015
From: joskerc at gmail.com (Jos Kerc)
Date: Thu, 24 Dec 2015 19:50:12 +0100
Subject: [Tutor] trouble with beautiful soup
In-Reply-To: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>
References: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>
Message-ID: <CAKs9Esvkndvp1Qmi5oTaF=rAB2CDXrCe68L28=8LPPed+mNvsg@mail.gmail.com>

Hi, see below.

On Thu, Dec 24, 2015 at 6:21 PM, marcus l?tolf
<marcus.luetolf at bluewin.ch> wrote:
> dear pythonistas,
> for hours I'am traying to use Beautiful Soup for scraping some websites as an exercise.
> But each time I run the code below:
>
>>>> import urllib
>>>> from BeautifulSpoup import *
>
>>>> url =  raw_input( 'Enter -')
>
>>>> html = urllib.urlopen(url).read()
>
>>>> soup = BeautifulSoup(html)
>>>> print soup
>
> I am getting the following trace back without beeing prompted for an input:
>
> Traceback (most recent call last):
>   File "C:/Python27/Beautiful Soup_ex1.py", line 2, in <module>
>     from beautifulspoup import *
> ImportError: No module named beautifulspoup


Change beautifulspoup to beautifulsoup It's just a typo...

>
> I have installed and unzipped etc. the latest file from www.crummy.com many times.
> If I click setup.py the command window appears only a fraction of a second.
> ??????
>
> Happy holidays and thanks for help, Marcus.
>

HTH & nice holidays too!
>
>
>
>
> ---
> Diese E-Mail wurde von Avast Antivirus-Software auf Viren gepr?ft.
> https://www.avast.com/antivirus
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

From richkappler at gmail.com  Thu Dec 24 13:54:41 2015
From: richkappler at gmail.com (richard kappler)
Date: Thu, 24 Dec 2015 13:54:41 -0500
Subject: [Tutor] reading an input stream
Message-ID: <CAG7edPHOoqWVxfYsx-KDCo7JPxdSRZKBAE_yrWeRBh9dvazTvA@mail.gmail.com>

I have to create a script that reads  xml data over a tcp socket, parses it
and outputs it to console. Not so bad, most of which I already know how to
do. I know how to set up the socket, though I am using a file for
development and testing, am using lxml and have created an xslt that does
what I want with the xml, and it outputs it to console.

What I'm not really sure of, each xml 'message' is preceeded by an STX
(\x02) and ends with an ETX (\x03). These 'messages' (Danny, are you noting
I don't say -lines- anymore? :-)  ) need to be parsed and output whole as
opposed to partial.

My concern is, there will actually be numerous machines sending data to the
tcp socket, so it's entirely likely the messages will come in fragmented
and the fragments will need to be held until complete so they can be sent
on whole to the parser. While this is the job of tcp, my script needs to

I think what I need to do would be analogous to (pardon if I'm using the
wrong terminology, at this poing in the discussion I am officially out of
my depth) sending the input stream to a buffer(s) until  the ETX for that
message comes in, shoot the buffer contents to the parser while accepting
the next STX + message fragment into the buffer, or something analogous.

Any guidance here?

And Merry Christmas / Happy Holidays / Festive whatever you celebrate!!!

regards, Richard

-- 

"I want to makes shoes!" -> elf fleeing the fire engulfed Keebler Tree

From dyoo at hashcollision.org  Thu Dec 24 14:39:30 2015
From: dyoo at hashcollision.org (Danny Yoo)
Date: Thu, 24 Dec 2015 11:39:30 -0800
Subject: [Tutor] trouble with beautiful soup
In-Reply-To: <CAKs9Esvkndvp1Qmi5oTaF=rAB2CDXrCe68L28=8LPPed+mNvsg@mail.gmail.com>
References: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>
 <CAKs9Esvkndvp1Qmi5oTaF=rAB2CDXrCe68L28=8LPPed+mNvsg@mail.gmail.com>
Message-ID: <CAGZAPF6Nmq6bC5tQB6+ewVyket9FCx0mMQE5cyaJsueR9Mh10g@mail.gmail.com>

The error message suggests that something is misspelled.  Let's look
at the message again:

>> Traceback (most recent call last):
>>   File "C:/Python27/Beautiful Soup_ex1.py", line 2, in <module>
>>     from beautifulspoup import *
>> ImportError: No module named beautifulspoup


A "spoup" is, according to Urban Dictionary, a: "A descriptive word,
mainly used in the North Northumberland border area...it describes a
person that is being obviously silly, but they do not notice."
http://www.urbandictionary.com/define.php?term=Spoup

A "soup" is something slightly different.  As Jos suggests, try
correcting the spelling and try again.

Good luck!

From jf_byrnes at comcast.net  Thu Dec 24 16:25:33 2015
From: jf_byrnes at comcast.net (Jim Byrnes)
Date: Thu, 24 Dec 2015 15:25:33 -0600
Subject: [Tutor] Using python 3 on Ubuntu 14.04
In-Reply-To: <n5fj46$1md$2@ger.gmane.org>
References: <n5f8uh$hib$1@ger.gmane.org>
 <645c9abe388549f947d7bdee0a020f1b@sonic.net>
 <CAM7omEv19Xfto-CjFHZKREaPYYauwseqDzjZSmfCPTS07GCH0w@mail.gmail.com>
 <n5fj46$1md$2@ger.gmane.org>
Message-ID: <n5hnse$jt1$1@ger.gmane.org>

On 12/23/2015 07:52 PM, Alan Gauld wrote:
> On 23/12/15 23:15, Nnamdi Anyanwu wrote:
>> If you're installing modules with pip, install pip3 and install the
>> appropriate modules using pip3 instead of using regular pip.
>
> Most v3 modules are also available via the Ubuntu package system
> so you can install via synaptic which I tend to find more reliable
> than pip.
>
> YMMV,
>

Thanks for all the info guys. I got myself confused because I thought 
that python 3 was the default for Ubuntu 14.04, but it is just installed 
by default. I realize now that the modules need to be installed in the 
proper environment.

I know Pythoncard is not maintained any more. I have one program I wrote 
using it that I use often so I wanted to see it worked on 14.04. It will 
be a good learning experience to rewrite it for python 3 using something 
else.

Regards,  Jim






From marcus.luetolf at bluewin.ch  Thu Dec 24 16:38:25 2015
From: marcus.luetolf at bluewin.ch (=?utf-8?Q?marcus_l=C3=BCtolf?=)
Date: Thu, 24 Dec 2015 22:38:25 +0100
Subject: [Tutor] trouble with beautiful soup
In-Reply-To: <CAKs9Esvkndvp1Qmi5oTaF=rAB2CDXrCe68L28=8LPPed+mNvsg@mail.gmail.com>
References: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>
 <CAKs9Esvkndvp1Qmi5oTaF=rAB2CDXrCe68L28=8LPPed+mNvsg@mail.gmail.com>
Message-ID: <33db01d13e93$6e79b680$4b6d2380$@bluewin.ch>

dear pythonistas, 
Jos, Alex, Danny, Francois and Rodney

I am absolutely thrilled about your prompt responses to my problem on this Christmas' eve and I am somewhat ashamed by my typing error.
However, neither the correct typing of beautifulsoup nor the replacment of the 2nd line of my code by <from bs4 import beautiful soup>
relieved the trace back mentioned in my previous mail.
????
Bless you, Marcus.


-----Urspr?ngliche Nachricht-----
Von: Jos Kerc [mailto:joskerc at gmail.com] 
Gesendet: Donnerstag, 24. Dezember 2015 19:50
An: marcus l?tolf <marcus.luetolf at bluewin.ch>
Cc: tutor at python.org
Betreff: Re: [Tutor] trouble with beautiful soup

Hi, see below.

On Thu, Dec 24, 2015 at 6:21 PM, marcus l?tolf <marcus.luetolf at bluewin.ch> wrote:
> dear pythonistas,
> for hours I'am traying to use Beautiful Soup for scraping some websites as an exercise.
> But each time I run the code below:
>
>>>> import urllib
>>>> from BeautifulSpoup import *
>
>>>> url =  raw_input( 'Enter -')
>
>>>> html = urllib.urlopen(url).read()
>
>>>> soup = BeautifulSoup(html)
>>>> print soup
>
> I am getting the following trace back without beeing prompted for an input:
>
> Traceback (most recent call last):
>   File "C:/Python27/Beautiful Soup_ex1.py", line 2, in <module>
>     from beautifulspoup import *
> ImportError: No module named beautifulspoup


Change beautifulspoup to beautifulsoup It's just a typo...

>
> I have installed and unzipped etc. the latest file from www.crummy.com many times.
> If I click setup.py the command window appears only a fraction of a second.
> ??????
>
> Happy holidays and thanks for help, Marcus.
>

HTH & nice holidays too!
>
>
>
>
> ---
> Diese E-Mail wurde von Avast Antivirus-Software auf Viren gepr?ft.
> https://www.avast.com/antivirus
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor


---
Diese E-Mail wurde von Avast Antivirus-Software auf Viren gepr?ft.
https://www.avast.com/antivirus


From dyoo at hashcollision.org  Thu Dec 24 16:54:40 2015
From: dyoo at hashcollision.org (Danny Yoo)
Date: Thu, 24 Dec 2015 13:54:40 -0800
Subject: [Tutor] reading an input stream
In-Reply-To: <CAG7edPHOoqWVxfYsx-KDCo7JPxdSRZKBAE_yrWeRBh9dvazTvA@mail.gmail.com>
References: <CAG7edPHOoqWVxfYsx-KDCo7JPxdSRZKBAE_yrWeRBh9dvazTvA@mail.gmail.com>
Message-ID: <CAGZAPF47Y0gfzeKpjkn3nxa4PD6RRoujnvnJpmLXugq7cx=fPg@mail.gmail.com>

> I think what I need to do would be analogous to (pardon if I'm using the
> wrong terminology, at this poing in the discussion I am officially out of
> my depth) sending the input stream to a buffer(s) until  the ETX for that
> message comes in, shoot the buffer contents to the parser while accepting
> the next STX + message fragment into the buffer, or something analogous.

Yes, I agree.  It sounds like you have one process read the socket and
collect chunks of bytes delimited by the STX markers.  It can then
send those chunks to the XML parser.


We can imagine one process that reads the socket and spits out a list
of byte chunks:

    chunks = readDelimitedChunks(socket)

and another process that parses those chunks and does something with them:

    for chunk in chunks:
        ....


It would be nice if we could organize the program like this.  But one
problem is that chunks might not be finite!  The socket might keep on
returning bytes.  If it keeps returning bytes, we can't possibly
return a finite list of the chunked bytes.


What we really want is something like:

    chunkStream = readDelimitedChunks(socket)
    for chunk in chunkStream:
        ....

where chunkStream is itself like a socket: it should be something that
we can repeatedly read from as if it were potentially infinite.


We can actually do this, and it isn't too bad.  There's a mechanism in
Python called a generator that allows us to write function-like things
that consume streams of input and produce streams of output.  Here's a
brief introduction to them.

For example, here's a generator that knows how to produce an infinite
stream of numbers:

##############
def nums():
    n = 0
    while True:
        yield n
        n += 1
##############

What distinguishes a generator from a regular function?  The use of
"yield".  A "yield" is like a return, but rather than completely
escape out of the function with the return value, this generator will
remember what it was doing  at that time.  Why?  Because it can
*resume* itself when we try to get another value out of the generator.

Let's try it out:

#####################

>>> numStream = nums()
>>> numStream.next()
0
>>> numStream.next()
1
>>> numStream.next()
2
>>> numStream.next()
3
>>> numStream.next()
4
#####################

Every next() we call on a generator will restart it from where it left
off, until it reaches its next "yield".  That's how we get this
generator to return an infinite sequence of things.


That's how we produce infinite sequences.  And we can write another
generator that knows how to take a stream of numbers, and square each
one.

########################
def squaring(stream):
    for n in stream:
        yield n
########################


Let's try it.


########################

>>> numStream = nums()
>>> squaredNums = squaring(numStream)
>>> squaredNums.next()
0
>>> squaredNums.next()
1
>>> squaredNums.next()
4
>>> squaredNums.next()
9
>>> squaredNums.next()
16
########################


If you have experience with other programming languages, you may have
heard of the term "co-routine".  What we're doing with this should be
reminiscent of coroutine-style programming.  We have one generator
feeding input into the other, with program control bouncing back and
forth between the generators as necessary.


So that's a basic idea of generators.  It lets us write processes that
can deal with and produce streams of data.  In the context of sockets,
this is particularly helpful, because sockets can be considered a
stream of bytes.


Here's another toy example that's closer to the problem you're trying
to solve.  Let's say that we're working on a program to alphabetize
the words of a sentence.  Very useless, of course.  :P  We might pass
it in the input:

    this
    is
    a
    test
    of
    the
    emergency
    broadcast
    system

and expect to get back the following sentence:

     hist
     is
     a
     estt
     fo
     eht
     ceeegmnry
     aabcdorst
     emssty

We can imagine one process doing chunking, going from a sequence of
characters to a sequence of words:

###########################################
def extract_words(seq):
    """Yield the words in a sequence of characters."""
    buffer = []
    for ch in seq:
        if ch.isalpha():
            buffer.append(ch)
        elif buffer:
            yield ''.join(buffer)
            del buffer[:]
    # If we hit the end of the buffer, we still might
    # need to yield one more result.
    if buffer:
        yield ''.join(buffer)
###########################################


and a function that transforms words to their munged counterpart:

#########################
def transform(word):
    """"Munges a word into its alphabetized form."""
    chars = list(word)
    chars.sort()
    return ''.join(chars)
#########################

This forms the major components of a program that can do the munging
on a file... or a socket!


Here's the complete example:


#############################################
import sys

def extract_words(seq):
    """Yield the words in a sequence of characters."""
    buffer = []
    for ch in seq:
        if ch.isalpha():
            buffer.append(ch)
        elif buffer:
            yield ''.join(buffer)
            del buffer[:]
    # If we hit the end of the buffer, we still might
    # need to yield one more result.
    if buffer:
        yield ''.join(buffer)

def transform(word):
    """"Munges a word into its alphabetized form."""
   chars = list(word)
    chars.sort()
    return ''.join(chars)


def as_byte_seq(f):
    """Return the bytes of the file-like object f as a
    sequence."""
    while True:
        ch = f.read(1)
        if not ch: break
        yield ch


if __name__ == '__main__':
    for word in extract_words(as_byte_seq(sys.stdin)):
        print(transform(word))
############################################



If you have questions, please feel free to ask.  Good luck!

From dyoo at hashcollision.org  Thu Dec 24 17:01:04 2015
From: dyoo at hashcollision.org (Danny Yoo)
Date: Thu, 24 Dec 2015 14:01:04 -0800
Subject: [Tutor] trouble with beautiful soup
In-Reply-To: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>
References: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>
Message-ID: <CAGZAPF7Zur0dR2LSwL1ZOxaCPP1kTLGM+bAVghytHJqtfsQ-rg@mail.gmail.com>

> I have installed and unzipped etc. the latest file from www.crummy.com many times.
> If I click setup.py the command window appears only a fraction of a second.
> ??????

Ah, you're on Windows.  I missed this detail earlier.

Double-clicking setup.py isn't enough to install that module.  You
need to do something extra.  Here:

    http://stackoverflow.com/questions/12324601/how-to-install-a-python-module-via-its-setup-py-in-windows


You want to run the following at the Windows command prompt:

    python setup.py install

From ben+python at benfinney.id.au  Thu Dec 24 17:03:27 2015
From: ben+python at benfinney.id.au (Ben Finney)
Date: Fri, 25 Dec 2015 09:03:27 +1100
Subject: [Tutor] Using python 3 on Ubuntu 14.04
References: <n5f8uh$hib$1@ger.gmane.org>
 <645c9abe388549f947d7bdee0a020f1b@sonic.net>
 <CAM7omEv19Xfto-CjFHZKREaPYYauwseqDzjZSmfCPTS07GCH0w@mail.gmail.com>
 <n5fj46$1md$2@ger.gmane.org> <n5hnse$jt1$1@ger.gmane.org>
Message-ID: <85ziwzy05s.fsf@benfinney.id.au>

Jim Byrnes <jf_byrnes at comcast.net> writes:

> Thanks for all the info guys. I got myself confused because I thought
> that python 3 was the default for Ubuntu 14.04, but it is just
> installed by default.

Even if that were true, the ?python? command will likely still invoke
a Python 2 interpreter. Most systems that install a Python 3 interpreter
will install the command as ?python3?.

> I realize now that the modules need to be installed in the proper
> environment.

That also remains true when Python 3 is the default.

> I know Pythoncard is not maintained any more. I have one program I
> wrote using it that I use often so I wanted to see it worked on 14.04.
> It will be a good learning experience to rewrite it for python 3 using
> something else.

Have you considered using Python 3 and the standard Tkinter tookit?
<URL:https://docs.python.org/3/library/tkinter.html>
<URL:https://docs.python.org/3/library/tkinter.ttk.html>
<URL:http://www.tkdocs.com/>

-- 
 \           ?I?ve been an atheist ever since I heard there was only a |
  `\                     stairway to heaven.? ?Stella Young, 1982?2014 |
_o__)                                                                  |
Ben Finney


From wprins at gmail.com  Thu Dec 24 17:16:55 2015
From: wprins at gmail.com (Walter Prins)
Date: Thu, 24 Dec 2015 22:16:55 +0000
Subject: [Tutor] trouble with beautiful soup
In-Reply-To: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>
References: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>
Message-ID: <CANLXbfDaj7FEfLFozd_C2x_fw2_b=CFRV5qUWzMRrXhKXr5=4g@mail.gmail.com>

Hi,

On 24 December 2015 at 17:21, marcus l?tolf <marcus.luetolf at bluewin.ch>
wrote:

> I am getting the following trace back without beeing prompted for an input:
>
> Traceback (most recent call last):
>   File "C:/Python27/Beautiful Soup_ex1.py", line 2, in <module>
>     from beautifulspoup import *
> ImportError: No module named beautifulspoup
>
> I have installed and unzipped etc. the latest file from www.crummy.com
> many times.
> If I click setup.py the command window appears only a fraction of a second.
> ??????
>


Slow down right there.  It sounds like you're manually downloading the
module and then trying to install it by double clicking setup.py.  Am I
right?   If so, don't do that.  (Perhaps.)  Manually downloading and
installing modules is arguably not the easiest/preferred way.

I'll explain an alternate/easier way below.  But if you must and because
it's arguably also good to know how to do this a bit more manually, open a
command prompt, then enter the following commands:

cd <extraction folder>
python setup.py install

Obviously you need to substitute where you extract the module sources into
the above cd command.

Then pay careful attention to any error messages output when the setup
script runs and post these if the installation is not successful.

I'll further note that it's much easier to install python packages with the
package manager "pip".  To make this work you need to however get pip
itself installed first.  To do this, download the instructions on the
following page: https://pip.pypa.io/en/stable/installing/  (basically
download and run the get-pip.py script.)

Once it's installed you can install modules by simply typing:

pip install <pacakge>

In your case this would simply be:

pip install beautifulsoup

At which you should get output something like the following:

C:\Python27\Scripts>pip install beautifulsoup
You are using pip version 7.0.1, however version 7.1.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Collecting beautifulsoup
  Downloading BeautifulSoup-3.2.1.tar.gz
Installing collected packages: beautifulsoup
  Running setup.py install for beautifulsoup
Successfully installed beautifulsoup-3.2.1

C:\Python27\Scripts>

You can issue the pip command from any folder, providing your
"C:\Python27\Scripts" folder is on your system path.  While it might be by
default, I don't want to assume it, and if you have multiple versions of
Python then you need to careful to not make assumptions about which Python
and which pip is being run and should check or be explicit.

After installing a module the easiest way to sanity check the module is in
fact installed, is to immediately run the Python interpreter and try to
import the module:

C:\Python27\Scripts>cd ..

C:\Python27>python
Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import BeautifulSoup
>>> dir(BeautifulSoup)
['BeautifulSOAP', 'BeautifulSoup', 'BeautifulStoneSoup', 'CData',
'Comment', 'DEFAULT_OUTPUT_ENCODING', 'Declaration',
'ICantBelieveItsBeautifulSoup', 'MinimalSoup', 'NavigableString',
'PageElement', 'ProcessingInstruction', 'ResultSet', 'RobustHTMLParser',
'RobustInsanelyWackAssHTMLParser', 'RobustWackAssHTMLParser',
'RobustXMLParser', 'SGMLParseError', 'SGMLParser', 'SimplifyingSOAPParser',
'SoupStrainer', 'StopParsing', 'Tag', 'UnicodeDammit', '__author__',
'__builtins__', '__copyright__', '__doc__', '__file__', '__license__',
'__name__', '__package__', '__version__', '_match_css_class',
'buildTagMap', 'chardet', 'codecs', 'generators', 'markupbase',
'name2codepoint', 're', 'sgmllib', 'types']
>>> print BeautifulSoup.__version__
3.2.1

Note that the Python package name is case sensitive, and that the 3.2.1
version package name is BeautifulSoup whilst the 4.x package name is bs4.
Obviously this may also explain why you're having problems.

Merry Christmas,

Walter

From robertvstepp at gmail.com  Thu Dec 24 17:24:58 2015
From: robertvstepp at gmail.com (boB Stepp)
Date: Thu, 24 Dec 2015 16:24:58 -0600
Subject: [Tutor] OT: How to automate user interactions with GUI elements
 of closed-source programs?
In-Reply-To: <CAHVvXxTT=JaX-WuOEYJr4_E8-fJtjaxQA2O6HJfhXeEEN9siRw@mail.gmail.com>
References: <CANDiX9JWpVdqeq8NkbFF=uGtSZr-ri+44NGSFPzKdDP_TPDocQ@mail.gmail.com>
 <CAHVvXxTT=JaX-WuOEYJr4_E8-fJtjaxQA2O6HJfhXeEEN9siRw@mail.gmail.com>
Message-ID: <CANDiX9Ljw2F8kc9ZGVHc9QPuOFrnky=6-rfb57g4h=HaF+b6Kw@mail.gmail.com>

On Thu, Dec 24, 2015 at 11:34 AM, Oscar Benjamin
<oscar.j.benjamin at gmail.com> wrote:
>
> On 24 Dec 2015 14:55, "boB Stepp" <robertvstepp at gmail.com> wrote:

[...]

>> I find myself doing the same boring, repetitive tasks by hand, which
>> amounts to copying certain information from one program and putting it
>> into other programs.  None of these programs, to my knowledge, have a
>> publicly accessible API.  Are there ways to programmatically
>> accurately click the right buttons (or check boxes, radio buttons,
>> etc.), copy desired fields and then switch to another program and
>> paste the desired information into the desired fields, accurately
>> clicking all things that need to be clicked, etc.?  This is mostly a
>> Windows-based scenario, but if the techniques (if they exist) can be
>> abstracted to any OS I can find plenty of uses elsewhere as well!

[...]

> ...I googled "Python windows control mouse" and got:
>
> http://stackoverflow.com/questions/1181464/controlling-mouse-with-python

> Also this:
> https://pypi.python.org/pypi/PyAutoGUI

My last of several unsatisfactory searches was "how to
programmatically click a button in python", which turned up a bunch of
web scraping results.  Sigh--very weak Google-fu indeed!  ~(:>)

Thanks, Oscar!  PyAutoGUI looks very promising.  It looks like my next
problem will be figuring out how to find the pixel coordinates of the
GUI elements which I wish to manipulate.  This package mentions
screenshot functions which may be able to locate these coordinates
programattically, but from the example given

>>> import pyautogui
>>> button7location = pyautogui.locateOnScreen('button.png') # returns (left, top, width, height) of matching region
>>> button7location
(1416, 562, 50, 41)
>>> buttonx, buttony = pyautogui.center(button7location)
>>> buttonx, buttony
(1441, 582)
>>> pyautogui.click(buttonx, buttony)  # clicks the center of where the button was found

it is not clear to me (Yet!) how "button7location" is mapped to the
actual button on-screen, so that I will know which button is being
identified.  But it looks like there is some good documentation which
will hopefully make things clear soon!

Merry Christmas!

-- 
boB

From alan.gauld at btinternet.com  Thu Dec 24 18:38:56 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 24 Dec 2015 23:38:56 +0000
Subject: [Tutor] OT: How to automate user interactions with GUI elements
 of closed-source programs?
In-Reply-To: <CANDiX9JWpVdqeq8NkbFF=uGtSZr-ri+44NGSFPzKdDP_TPDocQ@mail.gmail.com>
References: <CANDiX9JWpVdqeq8NkbFF=uGtSZr-ri+44NGSFPzKdDP_TPDocQ@mail.gmail.com>
Message-ID: <n5hvmg$tau$1@ger.gmane.org>

On 24/12/15 14:54, boB Stepp wrote:

> publicly accessible API.  Are there ways to programmatically
> accurately click the right buttons (or check boxes, radio buttons,
> etc.), copy desired fields and then switch to another program and
> paste the desired information into the desired fields, accurately
> clicking all things that need to be clicked, etc.?  This is mostly a
> Windows-based scenario, but if the techniques (if they exist) can be
> abstracted to any OS I can find plenty of uses elsewhere as well!


To quote my recent book:
--------------------
The final option for GUI applications with no API is to interact with
the GUI itself by sending user event messages into the application. Such
events could include key-presses, mouse-clicks, and so forth. This
technique is known as robotics because you are simulating a human user
from your Python program. It is really an extension of the native code
access described in the previous section, but operating at a much
lower level.

This is a frustrating technique that is very error prone and also very
vulnerable to changes in the application being controlled?for example,
if an upgrade changes the screen layout, your code will likely break.
Because of the difficulty of writing the code, as well as the fragility
of the solution, you should avoid this unless every other possibility
has failed.
---------------------

And again
--------------------
...you reviewed the options available for scripting with their pros and
cons, including the last resort option for GUIs of sending OS events to
the application windows. This last option is fraught with difficulty and
should only ever be used when all other means have been explored and
exhausted.


So, as you see I don't recommend it unless you are absolutely sure
nothing else is possible.

The other things to check are (On Windows):

1) File export/import (CSV, JSON or XML maybe? or a Windows app
   such as Word/Excel?))
2) COM object model access via PyWin32
3) A C DLL exposed via ctypes
4) A Web front end or web service

If you really must go down the screen scraping robotics route and
you are thinking of upgrading to Windows 10 make sure you do that
first or you will almost certainly have to rewrite from scratch
(and after most every other upgrade of OS or app thereafter).
And don't even think of changing your system fonts - ever!

If you had a Mac things are usually easier because you can often
use osascript as an interface to AppleScript but on X Windows
things are just as messy as for windows...


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at btinternet.com  Thu Dec 24 18:48:30 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 24 Dec 2015 23:48:30 +0000
Subject: [Tutor] reading an input stream
In-Reply-To: <CAG7edPHOoqWVxfYsx-KDCo7JPxdSRZKBAE_yrWeRBh9dvazTvA@mail.gmail.com>
References: <CAG7edPHOoqWVxfYsx-KDCo7JPxdSRZKBAE_yrWeRBh9dvazTvA@mail.gmail.com>
Message-ID: <n5i08e$55n$1@ger.gmane.org>

On 24/12/15 18:54, richard kappler wrote:

> I think what I need to do would be analogous to (pardon if I'm using the
> wrong terminology, at this poing in the discussion I am officially out of
> my depth) sending the input stream to a buffer(s) until  the ETX for that
> message comes in, shoot the buffer contents to the parser while accepting
> the next STX + message fragment into the buffer, or something analogous.

You could use a Stringbuffer in memory. But simpler still is just to
append the bits in a file, one per incoming source. Any reason that
wouldn't work?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From robertvstepp at gmail.com  Thu Dec 24 22:13:46 2015
From: robertvstepp at gmail.com (boB Stepp)
Date: Thu, 24 Dec 2015 21:13:46 -0600
Subject: [Tutor] reading an input stream
In-Reply-To: <CAGZAPF47Y0gfzeKpjkn3nxa4PD6RRoujnvnJpmLXugq7cx=fPg@mail.gmail.com>
References: <CAG7edPHOoqWVxfYsx-KDCo7JPxdSRZKBAE_yrWeRBh9dvazTvA@mail.gmail.com>
 <CAGZAPF47Y0gfzeKpjkn3nxa4PD6RRoujnvnJpmLXugq7cx=fPg@mail.gmail.com>
Message-ID: <CANDiX9J2sGdhQgTod9d5Pwtm+owP7p89q=XpUaneBiz6qCubiA@mail.gmail.com>

On Thu, Dec 24, 2015 at 3:54 PM, Danny Yoo <dyoo at hashcollision.org> wrote:

I tried to follow your example:
>
> For example, here's a generator that knows how to produce an infinite
> stream of numbers:
>
> ##############
> def nums():
>     n = 0
>     while True:
>         yield n
>         n += 1
> ##############
>
> What distinguishes a generator from a regular function?  The use of
> "yield".  A "yield" is like a return, but rather than completely
> escape out of the function with the return value, this generator will
> remember what it was doing  at that time.  Why?  Because it can
> *resume* itself when we try to get another value out of the generator.
>
> Let's try it out:
>
> #####################
>
>>>> numStream = nums()
>>>> numStream.next()
> 0

But I got an exception:

Python 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 20:20:57) [MSC v.1600
64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> def nums():
    n = 0
    while True:
        yield n
        n += 1


>>> numStream = nums()
>>> numStream.next()
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    numStream.next()
AttributeError: 'generator' object has no attribute 'next'


If I instead do this:

>>> next(numStream)
0
>>> next(numStream)
1
>>> next(numStream)
2

Things work as you described.  Is your example from Python 2?  If yes,
is this something that changed between Python 2 and 3?  I have not
made it to generators yet, but you have now whetted my appetite!

TIA!
boB

From jf_byrnes at comcast.net  Thu Dec 24 22:15:27 2015
From: jf_byrnes at comcast.net (Jim Byrnes)
Date: Thu, 24 Dec 2015 21:15:27 -0600
Subject: [Tutor] Using python 3 on Ubuntu 14.04
In-Reply-To: <85ziwzy05s.fsf@benfinney.id.au>
References: <n5f8uh$hib$1@ger.gmane.org>
 <645c9abe388549f947d7bdee0a020f1b@sonic.net>
 <CAM7omEv19Xfto-CjFHZKREaPYYauwseqDzjZSmfCPTS07GCH0w@mail.gmail.com>
 <n5fj46$1md$2@ger.gmane.org> <n5hnse$jt1$1@ger.gmane.org>
 <85ziwzy05s.fsf@benfinney.id.au>
Message-ID: <n5iccg$3b3$1@ger.gmane.org>

On 12/24/2015 04:03 PM, Ben Finney wrote:
> Jim Byrnes <jf_byrnes at comcast.net> writes:
>
>> Thanks for all the info guys. I got myself confused because I thought
>> that python 3 was the default for Ubuntu 14.04, but it is just
>> installed by default.
>
> Even if that were true, the ?python? command will likely still invoke
> a Python 2 interpreter. Most systems that install a Python 3 interpreter
> will install the command as ?python3?.

Misunderstanding that was also part of my confusion.

>> I realize now that the modules need to be installed in the proper
>> environment.
>
> That also remains true when Python 3 is the default.

I realize that now.

>> I know Pythoncard is not maintained any more. I have one program I
>> wrote using it that I use often so I wanted to see it worked on 14.04.
>> It will be a good learning experience to rewrite it for python 3 using
>> something else.
>
> Have you considered using Python 3 and the standard Tkinter tookit?
> <URL:https://docs.python.org/3/library/tkinter.html>
> <URL:https://docs.python.org/3/library/tkinter.ttk.html>
> <URL:http://www.tkdocs.com/>
>

Yes, that is something I plan to look at once I get 14.04 all set up the 
way I want and it becomes my default system.

Thanks,  Jim



From cs at zip.com.au  Thu Dec 24 22:02:19 2015
From: cs at zip.com.au (Cameron Simpson)
Date: Fri, 25 Dec 2015 14:02:19 +1100
Subject: [Tutor] reading an input stream
In-Reply-To: <CAG7edPHOoqWVxfYsx-KDCo7JPxdSRZKBAE_yrWeRBh9dvazTvA@mail.gmail.com>
References: <CAG7edPHOoqWVxfYsx-KDCo7JPxdSRZKBAE_yrWeRBh9dvazTvA@mail.gmail.com>
Message-ID: <20151225030219.GA82530@cskk.homeip.net>

On 24Dec2015 13:54, richard kappler <richkappler at gmail.com> wrote:
>I have to create a script that reads  xml data over a tcp socket, parses it
>and outputs it to console. Not so bad, most of which I already know how to
>do. I know how to set up the socket, though I am using a file for
>development and testing, am using lxml and have created an xslt that does
>what I want with the xml, and it outputs it to console.
>
>What I'm not really sure of, each xml 'message' is preceeded by an STX
>(\x02) and ends with an ETX (\x03). These 'messages' (Danny, are you noting
>I don't say -lines- anymore? :-)  ) need to be parsed and output whole as
>opposed to partial.
>
>My concern is, there will actually be numerous machines sending data to the
>tcp socket, so it's entirely likely the messages will come in fragmented
>and the fragments will need to be held until complete so they can be sent
>on whole to the parser. While this is the job of tcp, my script needs to
>
>I think what I need to do would be analogous to (pardon if I'm using the
>wrong terminology, at this poing in the discussion I am officially out of
>my depth) sending the input stream to a buffer(s) until  the ETX for that
>message comes in, shoot the buffer contents to the parser while accepting
>the next STX + message fragment into the buffer, or something analogous.
>
>Any guidance here?

Since a TCP stream runs from one machine to another (may be the same machine); 
presumably your actually have multiple TCP streams to manage, and at the same 
time as otherwise you could just process one until EOF, then the next and so 
on. Correct?

My personal inclination would start a Thread for each stream, and have that 
thread simple read the stream extracting XML chunks, and then .put each chunk 
on a Queue used by whatever does stuff with the XML (accept chunk, parse, etc).  
If you need to know where the chunk came from, .put a tuple with the chunk and 
some context information.

Does that help you move forward?

Cheers,
Cameron Simpson <cs at zip.com.au>

From dyoo at hashcollision.org  Thu Dec 24 22:26:33 2015
From: dyoo at hashcollision.org (Danny Yoo)
Date: Thu, 24 Dec 2015 19:26:33 -0800
Subject: [Tutor] reading an input stream
In-Reply-To: <CANDiX9J2sGdhQgTod9d5Pwtm+owP7p89q=XpUaneBiz6qCubiA@mail.gmail.com>
References: <CAG7edPHOoqWVxfYsx-KDCo7JPxdSRZKBAE_yrWeRBh9dvazTvA@mail.gmail.com>
 <CAGZAPF47Y0gfzeKpjkn3nxa4PD6RRoujnvnJpmLXugq7cx=fPg@mail.gmail.com>
 <CANDiX9J2sGdhQgTod9d5Pwtm+owP7p89q=XpUaneBiz6qCubiA@mail.gmail.com>
Message-ID: <CAGZAPF4Skhkt6wd7cDAOX9+-QX7mSV67K0O614pGSmiZmU1nwQ@mail.gmail.com>

>>>> numStream.next()
> Traceback (most recent call last):
>   File "<pyshell#3>", line 1, in <module>
>     numStream.next()
> AttributeError: 'generator' object has no attribute 'next'
>
>
> If I instead do this:
>
>>>> next(numStream)
> 0
>>>> next(numStream)
> 1
>>>> next(numStream)
> 2
>
> Things work as you described.  Is your example from Python 2?  If yes,
> is this something that changed between Python 2 and 3?  I have not
> made it to generators yet, but you have now whetted my appetite!


Hi BoB,

Ah, yes, thank you!  Yes, I was using Python 2.  I'll have to set up
Python 3 on my server and get some more experience with it during the
break, then!

Let me double check the docs... ok, yeah, I should be using the next()
function, since that's available in Python 2 as well.  Reference:
https://docs.python.org/2/library/functions.html#next

From robertvstepp at gmail.com  Thu Dec 24 22:46:02 2015
From: robertvstepp at gmail.com (boB Stepp)
Date: Thu, 24 Dec 2015 21:46:02 -0600
Subject: [Tutor] OT: How to automate user interactions with GUI elements
 of closed-source programs?
In-Reply-To: <n5hvmg$tau$1@ger.gmane.org>
References: <CANDiX9JWpVdqeq8NkbFF=uGtSZr-ri+44NGSFPzKdDP_TPDocQ@mail.gmail.com>
 <n5hvmg$tau$1@ger.gmane.org>
Message-ID: <CANDiX9JrxMMJhZ5boRq58zTXf_zWykqC_FroJJb9LwK-TxQR5Q@mail.gmail.com>

On Thu, Dec 24, 2015 at 5:38 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:


> To quote my recent book:

[...]

> This is a frustrating technique that is very error prone and also very
> vulnerable to changes in the application being controlled?for example,
> if an upgrade changes the screen layout, your code will likely break.
> Because of the difficulty of writing the code, as well as the fragility
> of the solution, you should avoid this unless every other possibility
> has failed.

After reading the docs on PyAutoGUI 0.9.31, I've been playing around
with it and investigating some of these "fragilities".  If I decide to
go this route it appears that I need to have the main window I'd be
working with maximized to full screen.  Otherwise, any coordinates to
position the mouse cursor could very well be incorrect.  It would be
better to use any and all keyboard shortcuts available in the
application I'm working with, as these should have reproducible
behavior.  Trying to use the package's image location functions for
"commonly" named buttons (such as "OK" or "Cancel") could easily be
iffy since it searches the entire monitor screen, which might trigger
the wrong button.  However, PyAutoGUI does have a region-defining tool
that can limit the area of screen real estate being searched.  Since I
don't have a dual-monitor setup at home, I cannot test what would
happen in that situation.  I notice that multiple monitors is on the
package author's TODO list.  Etc.  Definitely not software nirvana
here!

I've been trying to think of what things I can abstract out of the
possible different environments.  The only thing that has occurred to
me so far is do my mapping of a given software application window in
terms of relative coordinates.  This way I can detect the current
monitor viewing size and then compute the needed absolute mouse
coordinates.

> The other things to check are (On Windows):
>
> 1) File export/import (CSV, JSON or XML maybe? or a Windows app
>    such as Word/Excel?))

On one of the software packages I work with every day, there are
limited text file exports.  Unfortunately, they don't contain all of
the information I need, though they do contain most of it.

> 2) COM object model access via PyWin32

I used to have a very little bit of COM knowledge, but that has long
since been forgotten.  I don't know now what possibilities that might
open up for me in accessing one of these commercial applications.

> 3) A C DLL exposed via ctypes

Oscar very briefly mentioned taking this type of approach once upon a
time.  This is also something I currently know little about and don't
know what possibilities it might give me.

> 4) A Web front end or web service

This is a total no go for the software I use at work.

> If you really must go down the screen scraping robotics route and
> you are thinking of upgrading to Windows 10 make sure you do that
> first or you will almost certainly have to rewrite from scratch
> (and after most every other upgrade of OS or app thereafter).
> And don't even think of changing your system fonts - ever!
>

I am at the mercy of my IS department re possible upgrades and they
often don't give notice of coming upgrades!

Thanks, Alan!

Merry Christmas!
boB

From eryksun at gmail.com  Thu Dec 24 23:05:55 2015
From: eryksun at gmail.com (eryk sun)
Date: Thu, 24 Dec 2015 22:05:55 -0600
Subject: [Tutor] reading an input stream
In-Reply-To: <CANDiX9J2sGdhQgTod9d5Pwtm+owP7p89q=XpUaneBiz6qCubiA@mail.gmail.com>
References: <CAG7edPHOoqWVxfYsx-KDCo7JPxdSRZKBAE_yrWeRBh9dvazTvA@mail.gmail.com>
 <CAGZAPF47Y0gfzeKpjkn3nxa4PD6RRoujnvnJpmLXugq7cx=fPg@mail.gmail.com>
 <CANDiX9J2sGdhQgTod9d5Pwtm+owP7p89q=XpUaneBiz6qCubiA@mail.gmail.com>
Message-ID: <CACL+1atoBiOzkOFOR3T0OMfTp11tCmORB6QUknOkD31t2L_z5A@mail.gmail.com>

On Thu, Dec 24, 2015 at 9:13 PM, boB Stepp <robertvstepp at gmail.com> wrote:
> AttributeError: 'generator' object has no attribute 'next'

The iterator protocol was added in Python 2.2 (circa 2001) as a
generalization for use in "for" loops, but the language didn't have
built-in next() at the time. Instead the method to get the next item
from an iterator was defined without double underscores. You'd simply
call it.next() to manually get the next item of iterator "it".

Python 3 added built-in next() and changed the method name to
"__next__". The built-in function was backported to 2.6 to have a
common idiom even though the method is still named "next" in Python 2.

The name change in Python 3  reflects that "__next__" is a special
method that's looked up on the type (in CPython it's the tp_iternext
field of the PyTypeObject). You can't simply add a bound next method
to an instance to make Python think it's an iterator. The same applies
in Python 2, but the name "next" doesn't suggest that this is the
case.

For example, let's start out with a normal Python 2 iterator that
simply iterates a count from some initial value.

    class Iterator(object):
        def __init__(self, start):
            self.value = start - 1
        def __iter__(self):
            return self
        def next(self):
            self.value += 1
            return self.value

    >>> it = Iterator(0)
    >>> it.next()
    0
    >>> next(it)
    1

Now store the bound next method directly on the instance

    >>> it.next = it.next
    >>> it.next.__self__ is it
    True

and remove the method from the class:

    >>> del Iterator.next

The bound method still works:

    >>> it.next()
    2

But the interpreter doesn't look for "next" on the instance:

    >>> next(it)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: Iterator object is not an iterator

    >>> for i in it:
    ...     if i == 3: break
    ...
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: iter() returned non-iterator of type 'Iterator'

Since "next" is a special method, it should have the special name
"__next__". So let it be written. So let it be done... in Python 3.

From dexternet89 at mail.ru  Fri Dec 25 04:12:51 2015
From: dexternet89 at mail.ru (=?UTF-8?B?RGltYSBLdWxpaw==?=)
Date: Fri, 25 Dec 2015 12:12:51 +0300
Subject: [Tutor] =?utf-8?q?mutiply_file_download?=
Message-ID: <1451034771.874566158@f197.i.mail.ru>

 Hi to all.
Can you tell me, how can I make an asynchronous file downloading?
I have a list of links from where to get files, but I'd like to save time and make all downloads parallel.

At the moment I make download as:
import urllib
urls={"skype.msi": "http://www.skype.com/go/getskype-msi",
      "java.exe": "http://javadl.sun.com/webapps/download/AutoDL?BundleId=113219",
      "acrobat_reader.exe":"http://ardownload.adobe.com/pub/adobe/reader/win/AcrobatDC/1500920069/AcroRdrDC1500920069_en_US.exe"}
Dir = "c:\\download\\"
for key, val in urls.items():
    urllib.urlretrieve(val,Dir+key)
    print key+" was downloaded to "+Dir

How can i download files in parallel streams?
Thanks in advance.



-- 
Dima Kulik

From marcus.luetolf at bluewin.ch  Fri Dec 25 07:32:58 2015
From: marcus.luetolf at bluewin.ch (=?utf-8?Q?marcus_l=C3=BCtolf?=)
Date: Fri, 25 Dec 2015 13:32:58 +0100
Subject: [Tutor] trouble with beautiful soup
In-Reply-To: <CAKs9Esvkndvp1Qmi5oTaF=rAB2CDXrCe68L28=8LPPed+mNvsg@mail.gmail.com>
References: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>
 <CAKs9Esvkndvp1Qmi5oTaF=rAB2CDXrCe68L28=8LPPed+mNvsg@mail.gmail.com>
Message-ID: <013601d13f10$6636d070$32a47150$@bluewin.ch>

dear pythonistas, dear contributors Danny and Walter,

I tried all instructions given to my without any success:
If I type the install commands in the command line - even after having installed pip - I invariably get the notion that beautifulsoup is not found.
If I run the directory C:\Python27\Lib, beautifulsoup is not listed, also not if I look into IDLE Python 27/ Open Module.
And without surprise the command

C:\Python27>python
Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import BeautifulSoup

returns ...no module found. 

On the other hand I find listed  
beautifulsoup4-4.4.1 in IDLE Python 27/ Lib   and 
pip  in IDLE Python 27/Lib/site-packages.

I think something must be wrong with my Python installation but I don't know what and how to fix it.
????

Thanks and regards, Marcus.
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

dear pythonistas, 
Jos, Alex, Danny, Francois and Rodney

I am absolutely thrilled about your prompt responses to my problem on this Christmas' eve and I am somewhat ashamed by my typing error.
However, neither the correct typing of beautifulsoup nor the replacment of the 2nd line of my code by <from bs4 import beautiful soup>
relieved the trace back mentioned in my previous mail.
????
Bless you, Marcus.


-----Urspr?ngliche Nachricht-----
Von: Jos Kerc [mailto:joskerc at gmail.com] 
Gesendet: Donnerstag, 24. Dezember 2015 19:50
An: marcus l?tolf <marcus.luetolf at bluewin.ch>
Cc: tutor at python.org
Betreff: Re: [Tutor] trouble with beautiful soup

Hi, see below.

On Thu, Dec 24, 2015 at 6:21 PM, marcus l?tolf <marcus.luetolf at bluewin.ch> wrote:
> dear pythonistas,
> for hours I'am traying to use Beautiful Soup for scraping some websites as an exercise.
> But each time I run the code below:
>
>>>> import urllib
>>>> from BeautifulSpoup import *
>
>>>> url =  raw_input( 'Enter -')
>
>>>> html = urllib.urlopen(url).read()
>
>>>> soup = BeautifulSoup(html)
>>>> print soup
>
> I am getting the following trace back without beeing prompted for an input:
>
> Traceback (most recent call last):
>   File "C:/Python27/Beautiful Soup_ex1.py", line 2, in <module>
>     from beautifulspoup import *
> ImportError: No module named beautifulspoup


Change beautifulspoup to beautifulsoup It's just a typo...

>
> I have installed and unzipped etc. the latest file from www.crummy.com many times.
> If I click setup.py the command window appears only a fraction of a second.
> ??????
>
> Happy holidays and thanks for help, Marcus.
>

HTH & nice holidays too!
>
>
>
>
> ---
> Diese E-Mail wurde von Avast Antivirus-Software auf Viren gepr?ft.
> https://www.avast.com/antivirus
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor


---
Diese E-Mail wurde von Avast Antivirus-Software auf Viren gepr?ft.
https://www.avast.com/antivirus


From alan.gauld at btinternet.com  Fri Dec 25 13:29:11 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 25 Dec 2015 18:29:11 +0000
Subject: [Tutor] trouble with beautiful soup
In-Reply-To: <013601d13f10$6636d070$32a47150$@bluewin.ch>
References: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>
 <CAKs9Esvkndvp1Qmi5oTaF=rAB2CDXrCe68L28=8LPPed+mNvsg@mail.gmail.com>
 <013601d13f10$6636d070$32a47150$@bluewin.ch>
Message-ID: <n5k1tn$c85$1@ger.gmane.org>

On 25/12/15 12:32, marcus l?tolf wrote:
> dear pythonistas, dear contributors Danny and Walter,
> 
> I tried all instructions given to my without any success:
> If I type the install commands in the command line 

Which command line are you using? The pip command is not
a python command but a shell one. You need to run it from
the CMD prompt.

Did you try that? and if so what exact message did
you get? Can you show us a cut n paste of the session
please?



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From wprins at gmail.com  Fri Dec 25 15:28:14 2015
From: wprins at gmail.com (Walter Prins)
Date: Fri, 25 Dec 2015 20:28:14 +0000
Subject: [Tutor] trouble with beautiful soup
In-Reply-To: <013601d13f10$6636d070$32a47150$@bluewin.ch>
References: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>
 <CAKs9Esvkndvp1Qmi5oTaF=rAB2CDXrCe68L28=8LPPed+mNvsg@mail.gmail.com>
 <013601d13f10$6636d070$32a47150$@bluewin.ch>
Message-ID: <CANLXbfAcjTqqHHwa3q7yHGrvVs2FZMLUcmmqVb3zGVAo=GyooQ@mail.gmail.com>

Hi

On 25 December 2015 at 12:32, marcus l?tolf <marcus.luetolf at bluewin.ch>
wrote:

> dear pythonistas, dear contributors Danny and Walter,
>
> I tried all instructions given to my without any success:
> If I type the install commands in the command line - even after having
> installed pip - I invariably get the notion that beautifulsoup is not found.
> If I run the directory C:\Python27\Lib, beautifulsoup is not listed, also
> not if I look into IDLE Python 27/ Open Module.
> And without surprise the command
>
> C:\Python27>python
> Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)]
> on win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import BeautifulSoup
>
> returns ...no module found.
>
> On the other hand I find listed
> beautifulsoup4-4.4.1 in IDLE Python 27/ Lib   and
> pip  in IDLE Python 27/Lib/site-packages.
>
>
The above implies you have BeautifulSoup 4 installed.

As mentioned previously, for BeautifulSoup 4, the package name is "bt4", so
you would do

import bt4

to test it.

Only if you have BeautifulSoup 3.x installed, would "import BeautifulSoup"
work.

What exactly is output by pip when you run (from a cmd.exe command shell
window):

pip install beautifulsoup

?

Cheers

Walter

From wprins at gmail.com  Fri Dec 25 21:12:38 2015
From: wprins at gmail.com (Walter Prins)
Date: Sat, 26 Dec 2015 02:12:38 +0000
Subject: [Tutor] trouble with beautiful soup
In-Reply-To: <CANLXbfAcjTqqHHwa3q7yHGrvVs2FZMLUcmmqVb3zGVAo=GyooQ@mail.gmail.com>
References: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>
 <CAKs9Esvkndvp1Qmi5oTaF=rAB2CDXrCe68L28=8LPPed+mNvsg@mail.gmail.com>
 <013601d13f10$6636d070$32a47150$@bluewin.ch>
 <CANLXbfAcjTqqHHwa3q7yHGrvVs2FZMLUcmmqVb3zGVAo=GyooQ@mail.gmail.com>
Message-ID: <CANLXbfDKXgHzK_DjGA0e_mHG9raFPn8vYvj05sGZjxKZG78jYQ@mail.gmail.com>

Hi,

On 25 December 2015 at 20:28, Walter Prins <wprins at gmail.com> wrote:

> As mentioned previously, for BeautifulSoup 4, the package name is "bt4",
> so you would do
>
> import bt4
>
> to test it.
>

Of course, that should have been "bs4" not "bt4".  Apologies.

W

From alan.gauld at btinternet.com  Sat Dec 26 05:58:20 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 26 Dec 2015 10:58:20 +0000
Subject: [Tutor] mutiply file download
In-Reply-To: <1451034771.874566158@f197.i.mail.ru>
References: <1451034771.874566158@f197.i.mail.ru>
Message-ID: <n5lrsc$got$1@ger.gmane.org>

On 25/12/15 09:12, Dima Kulik wrote:
>  Hi to all.
> Can you tell me, how can I make an asynchronous file downloading?

You can use threading to start parallel tasks.
There is a how-to tutorial on threading on the python
web site.

Another option if you use Python 3.4 is the async modules.

> I have a list of links from where to get files, but I'd like 
> to save time and make all downloads parallel.

Remember that you probably only have one network connection
so all the data still has to come through that one connection.
While running two streams in parallel will probably be
effective more than that may not give you much advantage,
certainly it will be a case of diminishing returns.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From tahir.hafiz at gmail.com  Sat Dec 26 07:59:45 2015
From: tahir.hafiz at gmail.com (Tahir Hafiz)
Date: Sat, 26 Dec 2015 12:59:45 +0000
Subject: [Tutor] the products of an element of a list
Message-ID: <CALmb6fvkDerD3e7y_hqB8PJDn07RoVOEEQYOx4ZmyfjVx9f29Q@mail.gmail.com>

Finally getting round to doing some more python.
Stuck on a little online exercise:
"Define a function prod(L) which returns the product of the elements in a
list L."

Let's say L = [1, 2, 3, 4]

I have done this so far but it's not quite working:



def prod(L):

   sum = 1
   for i in L:


      sum = sum * i


      return sum


Code seems to print the right value in REPL (i.e. 24) just a for loop
though !?!
Think I am not seeing something obvious.


Cheers,
Tahir

From steve at pearwood.info  Sat Dec 26 08:32:47 2015
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 27 Dec 2015 00:32:47 +1100
Subject: [Tutor] the products of an element of a list
In-Reply-To: <CALmb6fvkDerD3e7y_hqB8PJDn07RoVOEEQYOx4ZmyfjVx9f29Q@mail.gmail.com>
References: <CALmb6fvkDerD3e7y_hqB8PJDn07RoVOEEQYOx4ZmyfjVx9f29Q@mail.gmail.com>
Message-ID: <20151226133246.GN23700@ando.pearwood.info>

On Sat, Dec 26, 2015 at 12:59:45PM +0000, Tahir Hafiz wrote:
> Finally getting round to doing some more python.
> Stuck on a little online exercise:
> "Define a function prod(L) which returns the product of the elements in a
> list L."
> 
> Let's say L = [1, 2, 3, 4]
> 
> I have done this so far but it's not quite working:
> 
> def prod(L):
>    sum = 1
>    for i in L:
>       sum = sum * i
>       return sum

The variable "sum" is a bad name for the variable. "sum" means the 
values are added, not multiplied, so the variable name is misleading.

But the actual bug in the function is that the last line, "return sum", 
is indented too far. That makes it part of the for-loop. So when you 
call prod(1, 2, 3, 4]) the function does:

let sum = 1
let i = 1  # first item in L
sum = sum * i  # 1*1 = 1
return sum  # exits the loop and the function, returning 1

You need to adjust the indentation of the last line so that it doesn't 
return until after the loop has completely finished.


-- 
Steve

From __peter__ at web.de  Sat Dec 26 08:42:39 2015
From: __peter__ at web.de (Peter Otten)
Date: Sat, 26 Dec 2015 14:42:39 +0100
Subject: [Tutor] the products of an element of a list
References: <CALmb6fvkDerD3e7y_hqB8PJDn07RoVOEEQYOx4ZmyfjVx9f29Q@mail.gmail.com>
Message-ID: <n5m5gh$l64$1@ger.gmane.org>

Tahir Hafiz wrote:

> Finally getting round to doing some more python.
> Stuck on a little online exercise:
> "Define a function prod(L) which returns the product of the elements in a
> list L."
> 
> Let's say L = [1, 2, 3, 4]
> 
> I have done this so far but it's not quite working:
> 
> 
> 
> def prod(L):
> 
>    sum = 1
>    for i in L:
> 
> 
>       sum = sum * i
> 
> 
>       return sum
> 
> 
> Code seems to print the right value in REPL (i.e. 24) just a for loop
> though !?!
> Think I am not seeing something obvious.

Look at the indentation. When does execution of the function end? Where 
should it? 

If you don't see it yet use another example list, one that doesn't start 
with 1. 

Example: what does

>>> prod([2, 3, 4])

return? Is the for loop entered? If yes, for how many iterations?



From tahir.hafiz at gmail.com  Sat Dec 26 10:10:35 2015
From: tahir.hafiz at gmail.com (Tahir Hafiz)
Date: Sat, 26 Dec 2015 15:10:35 +0000
Subject: [Tutor] the products of an element of a list
In-Reply-To: <n5m5gh$l64$1@ger.gmane.org>
References: <CALmb6fvkDerD3e7y_hqB8PJDn07RoVOEEQYOx4ZmyfjVx9f29Q@mail.gmail.com>
 <n5m5gh$l64$1@ger.gmane.org>
Message-ID: <CALmb6ftfCU1bpN31Qrb+SS13ujwPuRATgk8sEY6fVp7M5JKi9A@mail.gmail.com>

Thanks Steven and Peter, I de-dented and changed the variable name and it
works now.
Cheers,
Tahir

On Sat, Dec 26, 2015 at 1:42 PM, Peter Otten <__peter__ at web.de> wrote:

> Tahir Hafiz wrote:
>
> > Finally getting round to doing some more python.
> > Stuck on a little online exercise:
> > "Define a function prod(L) which returns the product of the elements in a
> > list L."
> >
> > Let's say L = [1, 2, 3, 4]
> >
> > I have done this so far but it's not quite working:
> >
> >
> >
> > def prod(L):
> >
> >    sum = 1
> >    for i in L:
> >
> >
> >       sum = sum * i
> >
> >
> >       return sum
> >
> >
> > Code seems to print the right value in REPL (i.e. 24) just a for loop
> > though !?!
> > Think I am not seeing something obvious.
>
> Look at the indentation. When does execution of the function end? Where
> should it?
>
> If you don't see it yet use another example list, one that doesn't start
> with 1.
>
> Example: what does
>
> >>> prod([2, 3, 4])
>
> return? Is the for loop entered? If yes, for how many iterations?
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From marcus.luetolf at bluewin.ch  Sat Dec 26 06:23:44 2015
From: marcus.luetolf at bluewin.ch (=?utf-8?Q?marcus_l=C3=BCtolf?=)
Date: Sat, 26 Dec 2015 12:23:44 +0100
Subject: [Tutor] trouble with beautiful soup
In-Reply-To: <CANLXbfDKXgHzK_DjGA0e_mHG9raFPn8vYvj05sGZjxKZG78jYQ@mail.gmail.com>
References: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>	<CAKs9Esvkndvp1Qmi5oTaF=rAB2CDXrCe68L28=8LPPed+mNvsg@mail.gmail.com>	<013601d13f10$6636d070$32a47150$@bluewin.ch>	<CANLXbfAcjTqqHHwa3q7yHGrvVs2FZMLUcmmqVb3zGVAo=GyooQ@mail.gmail.com>
 <CANLXbfDKXgHzK_DjGA0e_mHG9raFPn8vYvj05sGZjxKZG78jYQ@mail.gmail.com>
Message-ID: <0cf801d13fcf$e48d7130$ada85390$@bluewin.ch>

Hi Walter, dear pythonistas,

thank you ! 
replacing ?beautifulsoup? by ?bs4? in my code (2nd line) does not relieve the trace back I get.

 

In my directory C:\Python27\Lib I find the folder ?beautifulsoup4-4-4-1? in first place and the file ?setup.py? further down 

Upon opening ?beautifulsoup4-4-4-1?,  ?bs4? appears as another folder among others and some  .py files.

(C:\Python27\Lib\beautifoulsoup4-4-4-1\bs4\)



2 days ago I watched a youtube video about installing beautifulsoup. There, the bs4 folder appeared direct in the Lib folder :

C:\Python27\Lib\bs4\.

 

Could this cause my trouble ?


By the way, I am using W10 64 bit as OS.


Regards, Marcus.

 

Von: Walter Prins [mailto:wprins at gmail.com] 
Gesendet: Samstag, 26. Dezember 2015 03:13
An: marcus l?tolf <marcus.luetolf at bluewin.ch>
Cc: python mail list <tutor at python.org>
Betreff: Re: [Tutor] trouble with beautiful soup

 

Hi,

 

On 25 December 2015 at 20:28, Walter Prins <wprins at gmail.com <mailto:wprins at gmail.com> > wrote:

As mentioned previously, for BeautifulSoup 4, the package name is "bt4", so you would do 

 

import bt4

 

to test it.  

 

Of course, that should have been "bs4" not "bt4".  Apologies.

 

W

 



---
Diese E-Mail wurde von Avast Antivirus-Software auf Viren gepr?ft.
https://www.avast.com/antivirus

From dyoo at hashcollision.org  Sat Dec 26 15:59:41 2015
From: dyoo at hashcollision.org (Danny Yoo)
Date: Sat, 26 Dec 2015 12:59:41 -0800
Subject: [Tutor] trouble with beautiful soup
In-Reply-To: <0cf801d13fcf$e48d7130$ada85390$@bluewin.ch>
References: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>
 <CAKs9Esvkndvp1Qmi5oTaF=rAB2CDXrCe68L28=8LPPed+mNvsg@mail.gmail.com>
 <013601d13f10$6636d070$32a47150$@bluewin.ch>
 <CANLXbfAcjTqqHHwa3q7yHGrvVs2FZMLUcmmqVb3zGVAo=GyooQ@mail.gmail.com>
 <CANLXbfDKXgHzK_DjGA0e_mHG9raFPn8vYvj05sGZjxKZG78jYQ@mail.gmail.com>
 <0cf801d13fcf$e48d7130$ada85390$@bluewin.ch>
Message-ID: <CAGZAPF7eR28MPLNThYB67mccMNYg_R3zbPTeCWGDPUAurEtQoQ@mail.gmail.com>

On Sat, Dec 26, 2015 at 3:23 AM, marcus l?tolf
<marcus.luetolf at bluewin.ch> wrote:
> Hi Walter, dear pythonistas,
>
> thank you !
> replacing ?beautifulsoup? by ?bs4? in my code (2nd line) does not relieve the trace back I get.
>
>
>
> In my directory C:\Python27\Lib I find the folder ?beautifulsoup4-4-4-1? in first place and the file ?setup.py? further down
>
> Upon opening ?beautifulsoup4-4-4-1?,  ?bs4? appears as another folder among others and some  .py files.
>
> (C:\Python27\Lib\beautifoulsoup4-4-4-1\bs4\)


Ah.  This looks incorrect.  It appears that somehow the contents of
the zip file was directly copied into Python27\Lib.  This will not
work because the directory layout structure of the zip file includes
much more than what Python needs.  The zip file is structurally
organized so that you need to follow a specific procedure to install
the library.


To be clear: you should *not* be trying to directly copy files into
Python27\Lib.  Trying to do it by hand is error-prone, as you are
finding.


Please respond to Alan Gauld's recent response, where he said:

    Which command line are you using? The pip command is not a python
command but a shell one. You need to run it from
the CMD prompt.

    Did you try that? and if so what exact message did you get? Can
you show us a cut n paste of the session please?


Please respond to this, because it is crucial to understand what you
have done.  I don't think you've actually followed the earlier
instructions to run 'python setup.py install' at the Windows command
prompt.



> 2 days ago I watched a youtube video about installing beautifulsoup. There, the bs4 folder appeared direct in the Lib folder :
>
> C:\Python27\Lib\bs4\.
>
> Could this cause my trouble ?

The structure here is what I would have expected.  I strongly suggest
you try reinstalling the bs4 library by carefully following the
installation instructions.


---

By the way, as a meta-comment: please try to refer with explicit
hyperlinks if you talk about an external resource such as a YouTube
video.  When you mention "I watched a YouTube video about ...", then
it's very helpful if you can mention the specific hyperlink to that
video.  Here is one reason why it's helpful: it allows one of us to
confirm your observation.  Perhaps you might have misunderstood what
the video was showing?

Without references, we're at the mercy of hearsay.  Misinterpreting
what we observe is a common mistake that all of us humans make.
(This is not limited just in the programming domain, of course.)
Rather than ignore that human weakness, we can and should try to
anticipate and compensate.  By pointing with references, we allow
others to confirm our observations independently.  This is why
references are so important.   Reference-friendly systems like the WWW
are under-appreciated treasures.

---


Hope that makes sense.  Good luck to you!

From breamoreboy at yahoo.co.uk  Sat Dec 26 16:38:14 2015
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sat, 26 Dec 2015 21:38:14 +0000
Subject: [Tutor] trouble with beautiful soup
In-Reply-To: <0cf801d13fcf$e48d7130$ada85390$@bluewin.ch>
References: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>
 <CAKs9Esvkndvp1Qmi5oTaF=rAB2CDXrCe68L28=8LPPed+mNvsg@mail.gmail.com>
 <013601d13f10$6636d070$32a47150$@bluewin.ch>
 <CANLXbfAcjTqqHHwa3q7yHGrvVs2FZMLUcmmqVb3zGVAo=GyooQ@mail.gmail.com>
 <CANLXbfDKXgHzK_DjGA0e_mHG9raFPn8vYvj05sGZjxKZG78jYQ@mail.gmail.com>
 <0cf801d13fcf$e48d7130$ada85390$@bluewin.ch>
Message-ID: <n5n1cn$ojb$1@ger.gmane.org>

On 26/12/2015 11:23, marcus l?tolf wrote:
> replacing ?beautifulsoup? by ?bs4? in my code (2nd line) does not relieve the trace back I get.
> >
> In my directory C:\Python27\Lib I find the folder ?beautifulsoup4-4-4-1? in first place and the file ?setup.py? further down
>
> Upon opening ?beautifulsoup4-4-4-1?,  ?bs4? appears as another folder among others and some  .py files.
>
> (C:\Python27\Lib\beautifoulsoup4-4-4-1\bs4\)

Please don't type stuff out as it leads to mistakes, use cut and paste.

>
> 2 days ago I watched a youtube video about installing beautifulsoup. There, the bs4 folder appeared direct in the Lib folder :
>
> C:\Python27\Lib\bs4\.
>
> Could this cause my trouble ?

Yes as a normal installation of a third party module involves the 
site-packages directory.  Or is this another typing error?

>
> By the way, I am using W10 64 bit as OS.
>
> Regards, Marcus.
>

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

Mark Lawrence


From lordrip at gmail.com  Sun Dec 27 17:35:54 2015
From: lordrip at gmail.com (=?UTF-8?Q?Ricardo_Mart=C3=ADnez?=)
Date: Sun, 27 Dec 2015 23:35:54 +0100
Subject: [Tutor] Install issues with wxPython in OSX 10.11 El Capitan
Message-ID: <CAMtNk+totYO6sft8TxqcLfK0th0COuWpjAoE7cmQhzkht8JGuw@mail.gmail.com>

Hi to everyone, this is my first post to the list, I have problems
installing wxPython in OSX El Capitan, the install end with a message that
indicates that there's nothing to install, I have installed Python 2.7 by
default and 3 by myself, and I'd like to know another graphic library to
use in OSX and Windows, thanks a lot.

From alan.gauld at btinternet.com  Sun Dec 27 19:24:02 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 28 Dec 2015 00:24:02 +0000
Subject: [Tutor] Install issues with wxPython in OSX 10.11 El Capitan
In-Reply-To: <CAMtNk+totYO6sft8TxqcLfK0th0COuWpjAoE7cmQhzkht8JGuw@mail.gmail.com>
References: <CAMtNk+totYO6sft8TxqcLfK0th0COuWpjAoE7cmQhzkht8JGuw@mail.gmail.com>
Message-ID: <n5pvf1$j6h$1@ger.gmane.org>

On 27/12/15 22:35, Ricardo Mart?nez wrote:
> Hi to everyone, this is my first post to the list, I have problems
> installing wxPython in OSX El Capitan, the install end with a message that
> indicates that there's nothing to install,

You need to tell us exactly what you did. Your message is far too vague
to even guess what's happening.

What did you download(exact url please)?
How did you install it?
What exact error message do you get (cut 'n paste not summarize)?
What were you doing when it happened (ie what messages did you get just
before the install 'ends')?

Also, you realize wxPython is for Python 2.x only?

>  I have installed Python 2.7 by
> default and 3 by myself, and I'd like to know another graphic library

Tkinter is the standard GUI toolkit that comes with Python
(although the default install on MacOS may not have it). It works
with both 2.x and 3.x although there are some minor changes
between versions.

You can also use Apple's Cocoa framework if you are only deploying
on Mac. You can even use the Mac development tools (XCode etc) to
build the GUI and write the code. Check the MacPython community web
pages for details and a tutorial.

> use in OSX and Windows, thanks a lot.

But if you want Windows as well then TkInter (or wxPython on 2.x)
is probably the simplest option. You can also use PyQt/Side which
is a very powerful tool but also more complex to use.

A lot depends on whether you have any experience of building
GUIs in other languages. If so you will pick up any of them
easily, if not it will be fairly hard going initially regardless
of toolkit.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From pjw9387 at gmail.com  Mon Dec 28 04:52:35 2015
From: pjw9387 at gmail.com (Jinwoo Park)
Date: Mon, 28 Dec 2015 09:52:35 +0000
Subject: [Tutor] Can you help me importing the dataset?
Message-ID: <CAAHvpYxy6vNNX_SzM3-untvL2Kuj6-+twSer8rbcGKNHfdVSyQ@mail.gmail.com>

Hello!

I am using python for my project and I got stuck on importing a data.
My data was generated from other program called Madgraph5 and it is .lhe
file.
I thought using usecols or skiprows would've worked, but this data is very
messy and there are many "<...>"s in between the data (numbers) that I need
(I attached a screen shot).
Also, for numbers, I need to separate rows based on beginning numbers.

Can you help me separating my data based on beginning numbers please?
Or can you tell me where I can find the answer?

Thank you!

From alan.gauld at btinternet.com  Mon Dec 28 05:18:06 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 28 Dec 2015 10:18:06 +0000
Subject: [Tutor] Can you help me importing the dataset?
In-Reply-To: <CAAHvpYxy6vNNX_SzM3-untvL2Kuj6-+twSer8rbcGKNHfdVSyQ@mail.gmail.com>
References: <CAAHvpYxy6vNNX_SzM3-untvL2Kuj6-+twSer8rbcGKNHfdVSyQ@mail.gmail.com>
Message-ID: <n5r28u$i58$1@ger.gmane.org>

On 28/12/15 09:52, Jinwoo Park wrote:

> I am using python for my project and I got stuck on importing a data.
> My data was generated from other program called Madgraph5 and it is .lhe
> file.

Never heard of it can you show us a very small example of
what the data looks like?

> I thought using usecols or skiprows would've worked, but this data is very
> messy and there are many "<...>"s in between the data (numbers) that I need

Have you written any code? Let us see it.
Which module are you using?

> (I attached a screen shot).

It didn't reach us (or not me at least). Tutor is a text based mailing
list, if you want to post the screenshot somewhere you can send a url
link. Better still would be to cut n paste the content into a mail.

> Also, for numbers, I need to separate rows based on beginning numbers.

I don't understand what that means, can you show us
a before/after example?

> Can you help me separating my data based on beginning numbers please?
> Or can you tell me where I can find the answer?

We'd need a lot more information to understand the problem first.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From totaibhattacharya at gmail.com  Mon Dec 28 06:20:05 2015
From: totaibhattacharya at gmail.com (sutanu bhattacharya)
Date: Mon, 28 Dec 2015 16:50:05 +0530
Subject: [Tutor] Read from large text file,
 find string save 1st string of each line where it appeared.
Message-ID: <CAMqgpdokoE5T0hcH2yBTNnPGxbU_a2p4VGkcmzmEGgZU2Sza5g@mail.gmail.com>

{'115160371': [45349980, 22477811, 40566595, 26947037, 16178191, 12984002,
20087719, 19771564, 61746245, 17467721, 32233776, 31052980, 70768904,
16113331, 12414642]} <tutor at python.org>

suppose 61746245 <tutor at python.org> is my searching string. so o/p will be
115160371 <tutor at python.org> (1st string). Area in between third bracket ([
]) is the searching area...


kindly help me to solve this problem..

-- 
Sutanu Bhattacharya

From joel.goldstick at gmail.com  Mon Dec 28 08:30:25 2015
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Mon, 28 Dec 2015 08:30:25 -0500
Subject: [Tutor] Read from large text file,
 find string save 1st string of each line where it appeared.
In-Reply-To: <CAMqgpdokoE5T0hcH2yBTNnPGxbU_a2p4VGkcmzmEGgZU2Sza5g@mail.gmail.com>
References: <CAMqgpdokoE5T0hcH2yBTNnPGxbU_a2p4VGkcmzmEGgZU2Sza5g@mail.gmail.com>
Message-ID: <CAPM-O+wUU2O8k=h8gXZD=9v1qdKY47wA63m2hXXsP7gU9UB05Q@mail.gmail.com>

On Mon, Dec 28, 2015 at 6:20 AM, sutanu bhattacharya <
totaibhattacharya at gmail.com> wrote:

> {'115160371': [45349980, 22477811, 40566595, 26947037, 16178191, 12984002,
> 20087719, 19771564, 61746245, 17467721, 32233776, 31052980, 70768904,
> 16113331, 12414642]} <tutor at python.org>
>
> suppose 61746245 <tutor at python.org> is my searching string. so o/p will be
> 115160371 <tutor at python.org> (1st string). Area in between third bracket
> ([
> ]) is the searching area...
>
>
> kindly help me to solve this problem..
>
> --
> Sutanu Bhattacharya
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

def problem(6174625):
    return 115160371

You haven't really described your problem, so above is a solution for what
you asked.  What have you tried so far, and what was your result?

-- 
Joel Goldstick
http://joelgoldstick.com/stats/birthdays

From breamoreboy at yahoo.co.uk  Mon Dec 28 09:34:00 2015
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Mon, 28 Dec 2015 14:34:00 +0000
Subject: [Tutor] Read from large text file,
 find string save 1st string of each line where it appeared.
In-Reply-To: <CAMqgpdokoE5T0hcH2yBTNnPGxbU_a2p4VGkcmzmEGgZU2Sza5g@mail.gmail.com>
References: <CAMqgpdokoE5T0hcH2yBTNnPGxbU_a2p4VGkcmzmEGgZU2Sza5g@mail.gmail.com>
Message-ID: <n5rh99$ph4$1@ger.gmane.org>

On 28/12/2015 11:20, sutanu bhattacharya wrote:
> {'115160371': [45349980, 22477811, 40566595, 26947037, 16178191, 12984002,
> 20087719, 19771564, 61746245, 17467721, 32233776, 31052980, 70768904,
> 16113331, 12414642]} <tutor at python.org>
>
> suppose 61746245 <tutor at python.org> is my searching string. so o/p will be
> 115160371 <tutor at python.org> (1st string). Area in between third bracket ([
> ]) is the searching area...
>
>
> kindly help me to solve this problem..
>

We will help when you show us the code that you've written.  What OS and 
Python version are you using?

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

Mark Lawrence


From steve at pearwood.info  Mon Dec 28 11:12:30 2015
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 29 Dec 2015 03:12:30 +1100
Subject: [Tutor] Read from large text file,
 find string save 1st string of each line where it appeared.
In-Reply-To: <CAMqgpdokoE5T0hcH2yBTNnPGxbU_a2p4VGkcmzmEGgZU2Sza5g@mail.gmail.com>
References: <CAMqgpdokoE5T0hcH2yBTNnPGxbU_a2p4VGkcmzmEGgZU2Sza5g@mail.gmail.com>
Message-ID: <20151228161230.GS23700@ando.pearwood.info>

On Mon, Dec 28, 2015 at 04:50:05PM +0530, sutanu bhattacharya wrote:
> {'115160371': [45349980, 22477811, 40566595, 26947037, 16178191, 12984002,
> 20087719, 19771564, 61746245, 17467721, 32233776, 31052980, 70768904,
> 16113331, 12414642]} <tutor at python.org>
> 
> suppose 61746245 <tutor at python.org> is my searching string. so o/p will be
> 115160371 <tutor at python.org> (1st string). Area in between third bracket ([
> ]) is the searching area...

I don't understand the question.

What is "o/p"?

What do you mean, "searching string"? The string you are searching 
*for*, or the string you are searching *in*?

You have something that looks like a dictionary { } followed by an email 
address. What does that mean?

If you expect any useful answers, you will have to give a more careful 
question. Please show some sample data, and expected result, using 
valid Python syntax.

For example:

text = """This is a large string.
It contains many lines of text.
And some numbers: 22477811, 40566595, 26947037
And more numbers: 32233776, 31052980, 70768904
And lots more text.
"""
target = "233"

expected result: "32233776"





-- 
Steve

From cc.fezeribe at gmail.com  Mon Dec 28 07:34:36 2015
From: cc.fezeribe at gmail.com (cicy felix)
Date: Mon, 28 Dec 2015 13:34:36 +0100
Subject: [Tutor] Algorithm
In-Reply-To: <CADKweVZ1g5P9XokmjBVjgZ9Hc6yhvjXmbUZR24Y0ctDVzt2-9g@mail.gmail.com>
References: <CADKweVbjVnaiAJ7_xpfaYmR3cN4ZBw4woE5Zew-Q0MwnbX=HPg@mail.gmail.com>
 <CADKweVbAPzqN_-mSo2wgUNtM-Em+SGm94-v5WaqCDTmCOEOR0w@mail.gmail.com>
 <CADKweVbLKi=o0oOt+0RmPdu51Q+pgWvDLccHj02JBigxExt6Pg@mail.gmail.com>
 <CADKweVZ1g5P9XokmjBVjgZ9Hc6yhvjXmbUZR24Y0ctDVzt2-9g@mail.gmail.com>
Message-ID: <CADKweVY9gwEA_cofrrLtgc_+Lm4ss6HaU2C+9aOsi+X_KsKoAQ@mail.gmail.com>

Hello there!
Thank you for the good work you are doing at helping newbies to python.
Please I'd like clarification with the exercise below:

  Create a function get_algorithm_result to implement the algorithm below
Get a list of numbers L1, L2, L3....LN as argument
Assume L1 is the largest,  Largest = L1
Take next number Li from the list and do the following
If Largest is less than Li
   Largest = Li
 If Li is last number from  the list then
  return Largest and come out
 Else repeat same process starting from step 3

This what I've come up with:

def get_algorithm_result( numlist ):
 largest = numlist[0]
 i = 1
 while ( i < len(numlist) ):
   if ( largest < numlist[i]):
     largest = numlist[i]
     i = i + 1
     return largest
     numlist1 = [1,2,3,4,5]
     numlist2 = [10,20,30,40,50]
     largest = get_algorithm_result(numlist1)
     print largest
     largest = get_algorithm_result(numlist2)
     print largest

And I keep getting this error :
  .  test_maximum_number_two
Failure in line 15, in test_maximum_number_two    self.assertEqual(result,
"zoo", msg="Incorrect number") AssertionError: Incorrect number
Using unittest

I look forward to your response,
Thank you!

From nnamdi.anyanwu at gmail.com  Mon Dec 28 09:59:46 2015
From: nnamdi.anyanwu at gmail.com (Nnamdi Anyanwu)
Date: Mon, 28 Dec 2015 09:59:46 -0500
Subject: [Tutor]  Read from large text file,
 find string save 1st string of each line where it appeared.
In-Reply-To: <n5rh99$ph4$1@ger.gmane.org>
References: <CAMqgpdokoE5T0hcH2yBTNnPGxbU_a2p4VGkcmzmEGgZU2Sza5g@mail.gmail.com>
 <n5rh99$ph4$1@ger.gmane.org>
Message-ID: <CAM7omEvk1iwe8cA+MJcMsbK8Z1SUQDpkR5AAjLn106SMOFAfuA@mail.gmail.com>

I think what he's looking for is something similar to
grep 6174625 | awk -F ":" {print $1}

I don't know if there is a more efficient Python built-in used to search
for the line containing 6174625 (grep in python) other than simply
iterating though the entire file, with a for loop, line-by-line. You'd also
need to decide whether you want to print all lines containing the
searched-for string or just the first occurence. You can then use the split
method to return the first string on the line, using the semi-colon as the
delimiter.


for line in open("file.txt"):

    if "6174625" in line:

        return line.split(":")[0]


On Mon, Dec 28, 2015 at 6:20 AM, sutanu bhattacharya <
totaibhattacharya at gmail.com> wrote:

> {'115160371': [45349980, 22477811, 40566595, 26947037, 16178191, 12984002,
> 20087719, 19771564, 61746245, 17467721, 32233776, 31052980, 70768904,
> 16113331, 12414642]} <tutor at python.org>
>
> suppose 61746245 <tutor at python.org> is my searching string. so o/p will be
> 115160371 <tutor at python.org> (1st string). Area in between third bracket
> ([
> ]) is the searching area...
>
>
> kindly help me to solve this problem..
>
> --
> Sutanu Bhattacharya
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

def problem(6174625):
    return 115160371

You haven't really described your problem, so above is a solution for what
you asked.  What have you tried so far, and what was your result?

--
Joel Goldstick
http://joelgoldstick.com/stats/birthdays
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

From totaibhattacharya at gmail.com  Mon Dec 28 10:56:19 2015
From: totaibhattacharya at gmail.com (sutanu bhattacharya)
Date: Mon, 28 Dec 2015 21:26:19 +0530
Subject: [Tutor] Fwd:  Read from large text file,
 find string save 1st string of each line where it appeared.
In-Reply-To: <CAPM-O+xnh9ORyt9W3r3X4A8J+=WPnQnFXNs=6U3MJVEe3V1d0Q@mail.gmail.com>
References: <CAMqgpdokoE5T0hcH2yBTNnPGxbU_a2p4VGkcmzmEGgZU2Sza5g@mail.gmail.com>
 <CAPM-O+wUU2O8k=h8gXZD=9v1qdKY47wA63m2hXXsP7gU9UB05Q@mail.gmail.com>
 <CAMqgpdqdQYv3_VB0Psq1HxXGyLKpfM+3=xhXs3sWrCO9vQdKUg@mail.gmail.com>
 <CAPM-O+xnh9ORyt9W3r3X4A8J+=WPnQnFXNs=6U3MJVEe3V1d0Q@mail.gmail.com>
Message-ID: <CAMqgpdqETMBVh4SbG93QM4QBWc4n+_gvokVc+nPqXJjEeE+yzg@mail.gmail.com>

suppose 115160371 is my facebook id. 6174625 is the id of one of my
friends. If i give an id ,the output will be the id of those people who are
friend of 6174625.


---------- Forwarded message ----------
From: Joel Goldstick <joel.goldstick at gmail.com>
Date: Mon, Dec 28, 2015 at 9:20 PM
Subject: Re: [Tutor] Read from large text file, find string save 1st string
of each line where it appeared.
To: sutanu bhattacharya <totaibhattacharya at gmail.com>


Please don't write me.  Write to the mailing list

On Mon, Dec 28, 2015 at 10:43 AM, sutanu bhattacharya <
totaibhattacharya at gmail.com> wrote:

> Hi Joel,
>
> suppose 115160371 is my facebook id. 6174625 is the id of one of my
> friends. If i give an id ,the output will be the id of those people who are
> friend of 6174625.
>
> thanking you,
> Sutanu
>
>
>
> On Mon, Dec 28, 2015 at 7:00 PM, Joel Goldstick <joel.goldstick at gmail.com>
> wrote:
>
>>
>>
>> On Mon, Dec 28, 2015 at 6:20 AM, sutanu bhattacharya <
>> totaibhattacharya at gmail.com> wrote:
>>
>>> {'115160371': [45349980, 22477811, 40566595, 26947037, 16178191,
>>> 12984002,
>>> 20087719, 19771564, 61746245, 17467721, 32233776, 31052980, 70768904,
>>> 16113331, 12414642]} <tutor at python.org>
>>>
>>> suppose 61746245 <tutor at python.org> is my searching string. so o/p will
>>> be
>>> 115160371 <tutor at python.org> (1st string). Area in between third
>>> bracket ([
>>> ]) is the searching area...
>>>
>>>
>>> kindly help me to solve this problem..
>>>
>>> --
>>> Sutanu Bhattacharya
>>> _______________________________________________
>>> Tutor maillist  -  Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> https://mail.python.org/mailman/listinfo/tutor
>>>
>>
>> def problem(6174625):
>>     return 115160371
>>
>> You haven't really described your problem, so above is a solution for
>> what you asked.  What have you tried so far, and what was your result?
>>
>> --
>> Joel Goldstick
>> http://joelgoldstick.com/stats/birthdays
>>
>
>
>
> --
> Sutanu Bhattacharya
>
>
>


-- 
Joel Goldstick
http://joelgoldstick.com/stats/birthdays



-- 
Sutanu Bhattacharya

From joel.goldstick at gmail.com  Mon Dec 28 12:32:39 2015
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Mon, 28 Dec 2015 12:32:39 -0500
Subject: [Tutor] Algorithm
In-Reply-To: <CADKweVY9gwEA_cofrrLtgc_+Lm4ss6HaU2C+9aOsi+X_KsKoAQ@mail.gmail.com>
References: <CADKweVbjVnaiAJ7_xpfaYmR3cN4ZBw4woE5Zew-Q0MwnbX=HPg@mail.gmail.com>
 <CADKweVbAPzqN_-mSo2wgUNtM-Em+SGm94-v5WaqCDTmCOEOR0w@mail.gmail.com>
 <CADKweVbLKi=o0oOt+0RmPdu51Q+pgWvDLccHj02JBigxExt6Pg@mail.gmail.com>
 <CADKweVZ1g5P9XokmjBVjgZ9Hc6yhvjXmbUZR24Y0ctDVzt2-9g@mail.gmail.com>
 <CADKweVY9gwEA_cofrrLtgc_+Lm4ss6HaU2C+9aOsi+X_KsKoAQ@mail.gmail.com>
Message-ID: <CAPM-O+zAXB84Z4K_BeZCYcxozGoLR3cC6mdrOyAePc=zbgYrHQ@mail.gmail.com>

On Mon, Dec 28, 2015 at 7:34 AM, cicy felix <cc.fezeribe at gmail.com> wrote:

> Hello there!
> Thank you for the good work you are doing at helping newbies to python.
> Please I'd like clarification with the exercise below:
>
>   Create a function get_algorithm_result to implement the algorithm below
> Get a list of numbers L1, L2, L3....LN as argument
> Assume L1 is the largest,  Largest = L1
> Take next number Li from the list and do the following
> If Largest is less than Li
>    Largest = Li
>  If Li is last number from  the list then
>   return Largest and come out
>  Else repeat same process starting from step 3
>
> This what I've come up with:
>
> def get_algorithm_result( numlist ):
>  largest = numlist[0]
>  i = 1
>  while ( i < len(numlist) ):
>    if ( largest < numlist[i]):
>      largest = numlist[i]
>      i = i + 1
>      return largest
>

I believe the code following should not be indented as that makes it part
of your function


>      numlist1 = [1,2,3,4,5]
>      numlist2 = [10,20,30,40,50]
>      largest = get_algorithm_result(numlist1)
>      print largest
>      largest = get_algorithm_result(numlist2)
>      print largest
>
> And I keep getting this error :
>   .  test_maximum_number_two
> Failure in line 15, in test_maximum_number_two    self.assertEqual(result,
> "zoo", msg="Incorrect number") AssertionError: Incorrect number
> Using unittest
>
> Can you show your unittest code?


> I look forward to your response,
> Thank you!
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
http://joelgoldstick.com/stats/birthdays

From alan.gauld at btinternet.com  Mon Dec 28 12:46:25 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 28 Dec 2015 17:46:25 +0000
Subject: [Tutor] Algorithm
In-Reply-To: <CADKweVY9gwEA_cofrrLtgc_+Lm4ss6HaU2C+9aOsi+X_KsKoAQ@mail.gmail.com>
References: <CADKweVbjVnaiAJ7_xpfaYmR3cN4ZBw4woE5Zew-Q0MwnbX=HPg@mail.gmail.com>
 <CADKweVbAPzqN_-mSo2wgUNtM-Em+SGm94-v5WaqCDTmCOEOR0w@mail.gmail.com>
 <CADKweVbLKi=o0oOt+0RmPdu51Q+pgWvDLccHj02JBigxExt6Pg@mail.gmail.com>
 <CADKweVZ1g5P9XokmjBVjgZ9Hc6yhvjXmbUZR24Y0ctDVzt2-9g@mail.gmail.com>
 <CADKweVY9gwEA_cofrrLtgc_+Lm4ss6HaU2C+9aOsi+X_KsKoAQ@mail.gmail.com>
Message-ID: <n5rshh$fec$1@ger.gmane.org>

On 28/12/15 12:34, cicy felix wrote:

>   Create a function get_algorithm_result to implement the algorithm below
> Get a list of numbers L1, L2, L3....LN as argument
> Assume L1 is the largest,  Largest = L1
> Take next number Li from the list and do the following
> If Largest is less than Li
>    Largest = Li
>  If Li is last number from  the list then
>   return Largest and come out
>  Else repeat same process starting from step 3

OK, That seems fairly clear. Although it does
seem to imply a while loop which is maybe not
the best option here.(see below)

> This what I've come up with:

Thanks for showing us the code, but there are several
issues with it

> def get_algorithm_result( numlist ):
>  largest = numlist[0]
>  i = 1
>  while ( i < len(numlist) ):
>    if ( largest < numlist[i]):
>      largest = numlist[i]
>      i = i + 1

Notice that you only increase i if the if test is true.
If largest >= numlist[i] then your loop will simply go
round and round forever. The normal way in Python to
process all elements in a list is to use a for loop.

In your case that would look an awful lot simpler.
Try it.

>      return largest
>      numlist1 = [1,2,3,4,5]
>      numlist2 = [10,20,30,40,50]

I've no idea what you think these numbers are for,
they are not mentioned in your problem description.

>      largest = get_algorithm_result(numlist1)

This should(if it worked properly) return 5

>      print largest

So this (should) always print 5

>      largest = get_algorithm_result(numlist2)

and his should(if it worked properly) return 50

>      print largest

and this should print 50.

Two largests - isn't that a bit confusing?
Especially since neither number may be in your
original list of numbers.

> And I keep getting this error :
>   .  test_maximum_number_two
> Failure in line 15, in test_maximum_number_two    self.assertEqual(result,
> "zoo", msg="Incorrect number") AssertionError: Incorrect number
> Using unittest


Since you don't show us any code involving test_maximum_number_two
or even maximum_number_two() we can't help you there.

But it does seem to me that you are over complicating things.
Even if you stick with a while loop, just follow the algorithm
you were given and it should work.

One final point. You are printing the results but your problem states
that you should write a function that *returns* the largest. Not one
that prints it.

In general this is what functions should always do - return
values not print them. It makes them much more reusable and flexible.
You can always print the output later using:

print get_algorithm_result(numlist)


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at btinternet.com  Mon Dec 28 12:48:57 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 28 Dec 2015 17:48:57 +0000
Subject: [Tutor] Algorithm
In-Reply-To: <CAPM-O+zAXB84Z4K_BeZCYcxozGoLR3cC6mdrOyAePc=zbgYrHQ@mail.gmail.com>
References: <CADKweVbjVnaiAJ7_xpfaYmR3cN4ZBw4woE5Zew-Q0MwnbX=HPg@mail.gmail.com>
 <CADKweVbAPzqN_-mSo2wgUNtM-Em+SGm94-v5WaqCDTmCOEOR0w@mail.gmail.com>
 <CADKweVbLKi=o0oOt+0RmPdu51Q+pgWvDLccHj02JBigxExt6Pg@mail.gmail.com>
 <CADKweVZ1g5P9XokmjBVjgZ9Hc6yhvjXmbUZR24Y0ctDVzt2-9g@mail.gmail.com>
 <CADKweVY9gwEA_cofrrLtgc_+Lm4ss6HaU2C+9aOsi+X_KsKoAQ@mail.gmail.com>
 <CAPM-O+zAXB84Z4K_BeZCYcxozGoLR3cC6mdrOyAePc=zbgYrHQ@mail.gmail.com>
Message-ID: <n5rsm8$fec$2@ger.gmane.org>

On 28/12/15 17:32, Joel Goldstick wrote:

> I believe the code following should not be indented as that makes it part
> of your function
> 
> 
>>      numlist1 = [1,2,3,4,5]
>>      numlist2 = [10,20,30,40,50]
>>      largest = get_algorithm_result(numlist1)
>>      print largest

Ah, that makes sense. I couldn't think what the OP was trying
to do with those lines.

If they are outside the function then it all makes perfect sense.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From marcus.luetolf at bluewin.ch  Mon Dec 28 12:24:45 2015
From: marcus.luetolf at bluewin.ch (=?utf-8?Q?marcus_l=C3=BCtolf?=)
Date: Mon, 28 Dec 2015 18:24:45 +0100
Subject: [Tutor] trouble with beautiful soup
In-Reply-To: <CAGZAPF7eR28MPLNThYB67mccMNYg_R3zbPTeCWGDPUAurEtQoQ@mail.gmail.com>
References: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>
 <CAKs9Esvkndvp1Qmi5oTaF=rAB2CDXrCe68L28=8LPPed+mNvsg@mail.gmail.com>
 <013601d13f10$6636d070$32a47150$@bluewin.ch>
 <CANLXbfAcjTqqHHwa3q7yHGrvVs2FZMLUcmmqVb3zGVAo=GyooQ@mail.gmail.com>
 <CANLXbfDKXgHzK_DjGA0e_mHG9raFPn8vYvj05sGZjxKZG78jYQ@mail.gmail.com>
 <0cf801d13fcf$e48d7130$ada85390$@bluewin.ch>
 <CAGZAPF7eR28MPLNThYB67mccMNYg_R3zbPTeCWGDPUAurEtQoQ@mail.gmail.com>
Message-ID: <0d5701d14194$a821fce0$f865f6a0$@bluewin.ch>

Dear Pythonistas
Hi Danny,

I am grateful for your precise instruchtions.
Yes ideed, I tried all of the steps mentioned below which I shoudn't have done fumling around with this task now  for hours and days.
I even tried to do it on may laptop using W7 64bit and after deleting and reinstalling Python27.
The youtube video  I was referring to was : https://www.youtube.com/watch?v=0snOcBQ3I0g.

Now for pip: I found pip in C:\Python27\Lib\site-packages. But if I type in pip or pip.exe I get (in german): The command "pip" is  either typed wrong or could not be found (I can't cut and paste from the command window).
As you might have noticed English is not my natural language and this can lead sometimes to interpretation errors.

Regards, Marcus.
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-----Urspr?ngliche Nachricht-----
Von: Danny Yoo [mailto:dyoo at hashcollision.org] 
Gesendet: Samstag, 26. Dezember 2015 22:00
An: marcus l?tolf <marcus.luetolf at bluewin.ch>
Cc: python mail list <tutor at python.org>
Betreff: Re: [Tutor] trouble with beautiful soup

On Sat, Dec 26, 2015 at 3:23 AM, marcus l?tolf <marcus.luetolf at bluewin.ch> wrote:
> Hi Walter, dear pythonistas,
>
> thank you !
> replacing ?beautifulsoup? by ?bs4? in my code (2nd line) does not relieve the trace back I get.
>
>
>
> In my directory C:\Python27\Lib I find the folder 
> ?beautifulsoup4-4-4-1? in first place and the file ?setup.py? further 
> down
>
> Upon opening ?beautifulsoup4-4-4-1?,  ?bs4? appears as another folder among others and some  .py files.
>
> (C:\Python27\Lib\beautifoulsoup4-4-4-1\bs4\)


Ah.  This looks incorrect.  It appears that somehow the contents of the zip file was directly copied into Python27\Lib.  This will not work because the directory layout structure of the zip file includes much more than what Python needs.  The zip file is structurally organized so that you need to follow a specific procedure to install the library.


To be clear: you should *not* be trying to directly copy files into Python27\Lib.  Trying to do it by hand is error-prone, as you are finding.


Please respond to Alan Gauld's recent response, where he said:

    Which command line are you using? The pip command is not a python command but a shell one. You need to run it from the CMD prompt.

    Did you try that? and if so what exact message did you get? Can you show us a cut n paste of the session please?


Please respond to this, because it is crucial to understand what you have done.  I don't think you've actually followed the earlier instructions to run 'python setup.py install' at the Windows command prompt.



> 2 days ago I watched a youtube video about installing beautifulsoup. There, the bs4 folder appeared direct in the Lib folder :
>
> C:\Python27\Lib\bs4\.
>
> Could this cause my trouble ?

The structure here is what I would have expected.  I strongly suggest you try reinstalling the bs4 library by carefully following the installation instructions.


---

By the way, as a meta-comment: please try to refer with explicit hyperlinks if you talk about an external resource such as a YouTube video.  When you mention "I watched a YouTube video about ...", then it's very helpful if you can mention the specific hyperlink to that video.  Here is one reason why it's helpful: it allows one of us to confirm your observation.  Perhaps you might have misunderstood what the video was showing?

Without references, we're at the mercy of hearsay.  Misinterpreting what we observe is a common mistake that all of us humans make.
(This is not limited just in the programming domain, of course.) Rather than ignore that human weakness, we can and should try to anticipate and compensate.  By pointing with references, we allow others to confirm our observations independently.  This is why
references are so important.   Reference-friendly systems like the WWW
are under-appreciated treasures.

---


Hope that makes sense.  Good luck to you!


---
Diese E-Mail wurde von Avast Antivirus-Software auf Viren gepr?ft.
https://www.avast.com/antivirus


From alan.gauld at btinternet.com  Mon Dec 28 13:41:55 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 28 Dec 2015 18:41:55 +0000
Subject: [Tutor] trouble with beautiful soup
In-Reply-To: <0d5701d14194$a821fce0$f865f6a0$@bluewin.ch>
References: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>
 <CAKs9Esvkndvp1Qmi5oTaF=rAB2CDXrCe68L28=8LPPed+mNvsg@mail.gmail.com>
 <013601d13f10$6636d070$32a47150$@bluewin.ch>
 <CANLXbfAcjTqqHHwa3q7yHGrvVs2FZMLUcmmqVb3zGVAo=GyooQ@mail.gmail.com>
 <CANLXbfDKXgHzK_DjGA0e_mHG9raFPn8vYvj05sGZjxKZG78jYQ@mail.gmail.com>
 <0cf801d13fcf$e48d7130$ada85390$@bluewin.ch>
 <CAGZAPF7eR28MPLNThYB67mccMNYg_R3zbPTeCWGDPUAurEtQoQ@mail.gmail.com>
 <0d5701d14194$a821fce0$f865f6a0$@bluewin.ch>
Message-ID: <n5rvpj$2ga$1@ger.gmane.org>

On 28/12/15 17:24, marcus l?tolf wrote:
> ... (I can't cut and paste from the command window).
> 

Actually you can :-)

The secret is in the drop down menu from the icon
in the top left corner of the window. You should find
an Edit option which has a sub menu that allows you
to select/copy text.

You can make it even easier by going into the CMD
window options and selecting the QuickEdit option
and applying it to all sessions. That allows you
to select text using the mouse and copy using a
shortcut key(I can't recall which - return maybe?)

You can then paste your copied text into a mail
message (or anything else).

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From breamoreboy at yahoo.co.uk  Mon Dec 28 14:22:58 2015
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Mon, 28 Dec 2015 19:22:58 +0000
Subject: [Tutor] trouble with beautiful soup
In-Reply-To: <0d5701d14194$a821fce0$f865f6a0$@bluewin.ch>
References: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>
 <CAKs9Esvkndvp1Qmi5oTaF=rAB2CDXrCe68L28=8LPPed+mNvsg@mail.gmail.com>
 <013601d13f10$6636d070$32a47150$@bluewin.ch>
 <CANLXbfAcjTqqHHwa3q7yHGrvVs2FZMLUcmmqVb3zGVAo=GyooQ@mail.gmail.com>
 <CANLXbfDKXgHzK_DjGA0e_mHG9raFPn8vYvj05sGZjxKZG78jYQ@mail.gmail.com>
 <0cf801d13fcf$e48d7130$ada85390$@bluewin.ch>
 <CAGZAPF7eR28MPLNThYB67mccMNYg_R3zbPTeCWGDPUAurEtQoQ@mail.gmail.com>
 <0d5701d14194$a821fce0$f865f6a0$@bluewin.ch>
Message-ID: <n5s274$829$1@ger.gmane.org>

On 28/12/2015 17:24, marcus l?tolf wrote:
> Dear Pythonistas
> Hi Danny,
>
> I am grateful for your precise instruchtions.
> Yes ideed, I tried all of the steps mentioned below which I shoudn't have done fumling around with this task now  for hours and days.
> I even tried to do it on may laptop using W7 64bit and after deleting and reinstalling Python27.
> The youtube video  I was referring to was : https://www.youtube.com/watch?v=0snOcBQ3I0g.
>
> Now for pip: I found pip in C:\Python27\Lib\site-packages. But if I type in pip or pip.exe I get (in german): The command "pip" is  either typed wrong or could not be found (I can't cut and paste from the command window).
> As you might have noticed English is not my natural language and this can lead sometimes to interpretation errors.
>
> Regards, Marcus.

c:\Python27\Scripts>dir pip*
  Volume in drive C has no label.
  Volume Serial Number is AE77-B408

  Directory of c:\Python27\Scripts

20/09/2015  20:22            98,124 pip.exe
20/09/2015  20:22            98,124 pip2.7.exe
20/09/2015  20:22            98,124 pip2.exe
                3 File(s)        294,372 bytes
                0 Dir(s)  869,655,580,672 bytes free

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

Mark Lawrence




From breamoreboy at yahoo.co.uk  Mon Dec 28 14:24:47 2015
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Mon, 28 Dec 2015 19:24:47 +0000
Subject: [Tutor] Fwd: Read from large text file,
 find string save 1st string of each line where it appeared.
In-Reply-To: <CAMqgpdqETMBVh4SbG93QM4QBWc4n+_gvokVc+nPqXJjEeE+yzg@mail.gmail.com>
References: <CAMqgpdokoE5T0hcH2yBTNnPGxbU_a2p4VGkcmzmEGgZU2Sza5g@mail.gmail.com>
 <CAPM-O+wUU2O8k=h8gXZD=9v1qdKY47wA63m2hXXsP7gU9UB05Q@mail.gmail.com>
 <CAMqgpdqdQYv3_VB0Psq1HxXGyLKpfM+3=xhXs3sWrCO9vQdKUg@mail.gmail.com>
 <CAPM-O+xnh9ORyt9W3r3X4A8J+=WPnQnFXNs=6U3MJVEe3V1d0Q@mail.gmail.com>
 <CAMqgpdqETMBVh4SbG93QM4QBWc4n+_gvokVc+nPqXJjEeE+yzg@mail.gmail.com>
Message-ID: <n5s2ah$829$2@ger.gmane.org>

On 28/12/2015 15:56, sutanu bhattacharya wrote:
> suppose 115160371 is my facebook id. 6174625 is the id of one of my
> friends. If i give an id ,the output will be the id of those people who are
> friend of 6174625.
>
>
> ---------- Forwarded message ----------
> From: Joel Goldstick <joel.goldstick at gmail.com>
> Date: Mon, Dec 28, 2015 at 9:20 PM
> Subject: Re: [Tutor] Read from large text file, find string save 1st string
> of each line where it appeared.
> To: sutanu bhattacharya <totaibhattacharya at gmail.com>
>
>
> Please don't write me.  Write to the mailing list
>
> On Mon, Dec 28, 2015 at 10:43 AM, sutanu bhattacharya <
> totaibhattacharya at gmail.com> wrote:
>
>> Hi Joel,
>>
>> suppose 115160371 is my facebook id. 6174625 is the id of one of my
>> friends. If i give an id ,the output will be the id of those people who are
>> friend of 6174625.
>>
>> thanking you,
>> Sutanu
>>
>>
>>
>> On Mon, Dec 28, 2015 at 7:00 PM, Joel Goldstick <joel.goldstick at gmail.com>
>> wrote:
>>
>>>
>>>
>>> On Mon, Dec 28, 2015 at 6:20 AM, sutanu bhattacharya <
>>> totaibhattacharya at gmail.com> wrote:
>>>
>>>> {'115160371': [45349980, 22477811, 40566595, 26947037, 16178191,
>>>> 12984002,
>>>> 20087719, 19771564, 61746245, 17467721, 32233776, 31052980, 70768904,
>>>> 16113331, 12414642]} <tutor at python.org>
>>>>
>>>> suppose 61746245 <tutor at python.org> is my searching string. so o/p will
>>>> be
>>>> 115160371 <tutor at python.org> (1st string). Area in between third
>>>> bracket ([
>>>> ]) is the searching area...
>>>>
>>>>
>>>> kindly help me to solve this problem..
>>>>
>>>> --
>>>> Sutanu Bhattacharya
>>>> _______________________________________________
>>>> Tutor maillist  -  Tutor at python.org
>>>> To unsubscribe or change subscription options:
>>>> https://mail.python.org/mailman/listinfo/tutor
>>>>
>>>
>>> def problem(6174625):
>>>      return 115160371
>>>
>>> You haven't really described your problem, so above is a solution for
>>> what you asked.  What have you tried so far, and what was your result?
>>>
>>> --
>>> Joel Goldstick
>>> http://joelgoldstick.com/stats/birthdays
>>>
>>
>>
>>
>> --
>> Sutanu Bhattacharya
>>
>>
>>
>
>

Suppose that you stop top posting?  Then it would be far easier for 
people to follow the thread.

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

Mark Lawrence


From wprins at gmail.com  Mon Dec 28 16:33:30 2015
From: wprins at gmail.com (Walter Prins)
Date: Mon, 28 Dec 2015 21:33:30 +0000
Subject: [Tutor] Read from large text file,
 find string save 1st string of each line where it appeared.
In-Reply-To: <CAMqgpdokoE5T0hcH2yBTNnPGxbU_a2p4VGkcmzmEGgZU2Sza5g@mail.gmail.com>
References: <CAMqgpdokoE5T0hcH2yBTNnPGxbU_a2p4VGkcmzmEGgZU2Sza5g@mail.gmail.com>
Message-ID: <CANLXbfCodjbqyCjt6tBKo2xuWrge3=kKA8Bcc11Uk2jy=Bs62Q@mail.gmail.com>

Hi Sutanu,

On 28 December 2015 at 11:20, sutanu bhattacharya <
totaibhattacharya at gmail.com> wrote:

> {'115160371': [45349980, 22477811, 40566595, 26947037, 16178191, 12984002,
> 20087719, 19771564, 61746245, 17467721, 32233776, 31052980, 70768904,
> 16113331, 12414642]} <tutor at python.org>
>
> suppose 61746245 <tutor at python.org> is my searching string. so o/p will be
> 115160371 <tutor at python.org> (1st string). Area in between third bracket
> ([
> ]) is the searching area...
>

We are not mind readers, and as others have said, you need to provide more
of a description of what you're trying to accomplish and what version of
Python, OS etc you are using.

But, assuming Windows, Python 2.x, and assuming what described as
"searching a string" is in fact more of a looking up id's in lists of id's
held as the values in a Python dict, then simplistically/directly you could
do something as follows:

--------example.py-----------
friendsmap1 = {
       115160371: [45349980, 22477811, 40566595, 26947037, 16178191,
12984002,
                   20087719, 19771564, 61746245, 17467721, 32233776,
31052980,
                   70768904, 16113331, 12414642],
       45349980:  [22477811, 40566595, 26947037, 16178191],
       16178191:  [61746245, 17467721, 32233776, 31052980],
       31052980:  [22477811, 40566595, 32233776, 31052980]
     }

friendsmap2 = {
       16178191:  [61746245, 17467721, 32233776, 31052980],
       31052980:  [22477811, 40566595, 32233776, 31052980]
     }

def friendswith(friendsmap, friendid):
    res = [key for key, value in friendsmap.items() if friendid in value]
    return res

# Examples:
print friendswith(friendsmap1, 61746245)
print friendswith(friendsmap1, 26947037)
print friendswith(friendsmap2, 61746245)

--------example.py-----------

--------output-----------
[115160371, 16178191]
[115160371, 45349980]
[16178191]



Walter

From cs at zip.com.au  Mon Dec 28 17:36:44 2015
From: cs at zip.com.au (Cameron Simpson)
Date: Tue, 29 Dec 2015 09:36:44 +1100
Subject: [Tutor] Read from large text file,
 find string save 1st string of each line where it appeared.
In-Reply-To: <20151228161230.GS23700@ando.pearwood.info>
References: <20151228161230.GS23700@ando.pearwood.info>
Message-ID: <20151228223644.GA94862@cskk.homeip.net>

On 29Dec2015 03:12, Steven D'Aprano <steve at pearwood.info> wrote:
>On Mon, Dec 28, 2015 at 04:50:05PM +0530, sutanu bhattacharya wrote:
>> suppose 61746245 <tutor at python.org> is my searching string. so o/p will be
[...]
>
>I don't understand the question.
>What is "o/p"?

"output"

Cheers,
Cameron Simpson <cs at zip.com.au>

From 261100nc at gmail.com  Tue Dec 29 11:52:24 2015
From: 261100nc at gmail.com (Nathan Clark)
Date: Tue, 29 Dec 2015 16:52:24 +0000
Subject: [Tutor] Python trouble
Message-ID: <CAMJWdXvb4dbMAUS1NVVKBnRk7yCXFs1qcjz=f-nQMAyum6oL9Q@mail.gmail.com>

This is a  fibonnaci sequence generator, the colon causes a syntax error


#set variables
num_1 = 1
num_2 = 2
count = 0
terms = int(input("How many terms of the fibonnaci sequence would you
like?")


#function
while terms != count :
    num_3 =num_1+num_2
    print (num_3)
    num_1=num_2
    num_2 = num_3
    count=count+1
else:
    print ("finished")

From alan.gauld at btinternet.com  Tue Dec 29 12:04:24 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 29 Dec 2015 17:04:24 +0000
Subject: [Tutor] Python trouble
In-Reply-To: <CAMJWdXvb4dbMAUS1NVVKBnRk7yCXFs1qcjz=f-nQMAyum6oL9Q@mail.gmail.com>
References: <CAMJWdXvb4dbMAUS1NVVKBnRk7yCXFs1qcjz=f-nQMAyum6oL9Q@mail.gmail.com>
Message-ID: <n5ueeo$lr4$1@ger.gmane.org>

On 29/12/15 16:52, Nathan Clark wrote:
> This is a  fibonnaci sequence generator, the colon causes a syntax error


Please always post the full error text.
It contains much useful information.


> terms = int(input("How many terms of the fibonnaci sequence would you
> like?")

Count the parentheses...

> while terms != count :

The syntax error is marked against this line because is where
Python first finds something it can't recognise but the actual
error is further back. That's why, with syntax errors, you should
always check a line or two before the marked error point.
In particular always check for mis-matched quotes,
brackets/parens or indentation errors - these are the
most common mistakes.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From joel.goldstick at gmail.com  Tue Dec 29 12:54:40 2015
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Tue, 29 Dec 2015 12:54:40 -0500
Subject: [Tutor] Python trouble
In-Reply-To: <CAMJWdXvb4dbMAUS1NVVKBnRk7yCXFs1qcjz=f-nQMAyum6oL9Q@mail.gmail.com>
References: <CAMJWdXvb4dbMAUS1NVVKBnRk7yCXFs1qcjz=f-nQMAyum6oL9Q@mail.gmail.com>
Message-ID: <CAPM-O+w=aC+ch7jiTVA7a-sJjM-Y6sdLB-6Fe7-zEpnx2ORozw@mail.gmail.com>

On Tue, Dec 29, 2015 at 11:52 AM, Nathan Clark <261100nc at gmail.com> wrote:

> This is a  fibonnaci sequence generator, the colon causes a syntax error
>
>
> #set variables
> num_1 = 1
> num_2 = 2
> count = 0
> terms = int(input("How many terms of the fibonnaci sequence would you
> like?")
>
>
> #function
> while terms != count :
>     num_3 =num_1+num_2
>     print (num_3)
>     num_1=num_2
>     num_2 = num_3
>

this can be simplified to
       num_1, num_2 = num_2, num_3


>     count=count+1
> else:
>     print ("finished")
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


-- 
Joel Goldstick
http://joelgoldstick.com/stats/birthdays

From lordrip at gmail.com  Tue Dec 29 13:29:27 2015
From: lordrip at gmail.com (=?UTF-8?Q?Ricardo_Mart=C3=ADnez?=)
Date: Tue, 29 Dec 2015 19:29:27 +0100
Subject: [Tutor] Python trouble (Nathan Clark)
Message-ID: <CAMtNk+tto957vN5ff0rSTbe_Tf0GmcuDa2YPTtqObMwrBC9EtQ@mail.gmail.com>

Hi, the problem is in the line that says:

terms = int(input("How many terms of the fibonnaci sequence would you
like?")

is missing a closing ')'
take a look:

terms = int(input("How many terms of the fibonnaci sequence would you
like?"))

Hope you help.

From wuzzyluzy at gmail.com  Tue Dec 29 12:00:02 2015
From: wuzzyluzy at gmail.com (Satya Luzy)
Date: Wed, 30 Dec 2015 00:00:02 +0700
Subject: [Tutor] MemoryError
Message-ID: <CAAMZLuxyOHYWP6oYo6KRBqAVAK_3RpWtPbSBpv=CO=idU_w_Uw@mail.gmail.com>

Hello,
I am currently working on a program to find the prime factor of n, in which
n is a big integer. Using the Continued Fraction factorization method (I
will provide the source code below, please don't mind the variables). It
works perfectly when factorizing below 10 digits numbers. In my code below
you will see on how I tried to factorize 94152743499601547, but get this
message instead :
---------------------------------------------------------------------------------------------------------------------
*Traceback (most recent call last):*
*  File "C:/Users/Satya/PycharmProjects/untitled2/fact.py", line 94, in
<module>*
*    faktorisasi(n)*
*  File "C:/Users/Satya/PycharmProjects/untitled2/fact.py", line 92, in
faktorisasi*
*    faktorisasi_default(n,j,boundary)*
*  File "C:/Users/Satya/PycharmProjects/untitled2/fact.py", line 55, in
faktorisasi_default*
*    Q.append(((n*kelipatan)-(p[i]**2))/Q[i-1])*
*MemoryError*

*Process finished with exit code 1*
--------------------------------------------------------------------------------------------------------------------
It has undergone the boundary value of 51200 and j value of 12. It has been
running for more than 5 hours before it suddenly stop.
Please let me know how to fix the memory error,
Thanks before.
Sincerely.
--------------------------------------------------------------------------------------------------------------------
[CODE]

import fractions
import math

n = 94152743499601547 #untuk difaktorkan
flag = True
faktor_1 = 1    #deklarasi asal
faktor_2 = 1

# CFRAC
def cfract(n,boundary):
   coeff = 1
   floor_part = floor_ = math.floor(math.sqrt(n))
   denom = n - floor_part ** 2
   result = []
   result.append(int(floor_))

   if float(denom)!=0:
      for i in range(boundary-1):
         try:
            floor_ = math.floor((math.sqrt(n) + floor_part) / float(denom))
         except ZeroDivisionError: # perfect square
            return result

         if denom != 1:
            result.append(int(floor_))
         floor_part = denom * floor_ - floor_part
         coeff = denom
         denom = n - floor_part ** 2
         common_div = fractions.gcd(coeff, denom)
         coeff /= common_div
         denom /= common_div

         if denom == 1:
            result.append(int(floor_part + result[0]))
   return result

def faktorisasi_default(n,kelipatan,boundary):
    global faktor_1,faktor_2,flag

    q = cfract(n*kelipatan,boundary)
    p = []
    Q = []
    A = []
    p.append(0)
    p.append(q[0])
    Q.append(1)
    A.append(0)
    A.append(1)
    A.append(q[0])
    Q.append(((n*kelipatan)-(p[1]**2))/Q[0])

# i = 2
    for i in range(2,len(q)):
        p.append((q[i-1]*Q[i-1])-p[i-1])
        Q.append(((n*kelipatan)-(p[i]**2))/Q[i-1])
        A.append((q[i-1]*A[i]+A[i-1])%(n*kelipatan))
    #tabel sudah selesai

    temp = 0        # nilai Q yg ganda
    temp2 = 0
    tempA1 = 0      # nilai A dari Q1
    tempA2 = 0      # nilai A dari Q2

    for i in range(0,len(Q)):
        for j in range(i+1,len(Q)):
            if flag and Q[i]==Q[j]:
                print Q[i]
                print Q[j]
                temp = Q[i]
                tempA1 = A[i+1]
                tempA2 = A[j+1]

                temp2 = tempA1*tempA2 % n # nilai base

                if temp2 > Q[i]:
                    faktor_1 = int(fractions.gcd(temp2+temp,n))
                    faktor_2 = int(fractions.gcd(temp2-temp,n))

                    if faktor_1 != 1 and faktor_2 != 1:
                        flag = False

def faktorisasi(n):
    global flag
    j=1 #kelipatan
    boundary=50 #iterasi CFRAC
    faktorisasi_default(n,j,boundary)
    while (flag):
       j+=1
       boundary*=2
       print "Nilai boundary : %d" %boundary
       print "Nilai j : %d" %j
       faktorisasi_default(n,j,boundary)

faktorisasi(n)
print faktor_1
print faktor_2

From richkappler at gmail.com  Tue Dec 29 15:14:08 2015
From: richkappler at gmail.com (richard kappler)
Date: Tue, 29 Dec 2015 15:14:08 -0500
Subject: [Tutor] reading an input stream
In-Reply-To: <CAGZAPF47Y0gfzeKpjkn3nxa4PD6RRoujnvnJpmLXugq7cx=fPg@mail.gmail.com>
References: <CAG7edPHOoqWVxfYsx-KDCo7JPxdSRZKBAE_yrWeRBh9dvazTvA@mail.gmail.com>
 <CAGZAPF47Y0gfzeKpjkn3nxa4PD6RRoujnvnJpmLXugq7cx=fPg@mail.gmail.com>
Message-ID: <CAG7edPFKyb1iC0ChQJAMpNRwE75nDQSM9NOakQ+As01nnutTQQ@mail.gmail.com>

Sorry it took so long to respond, just getting back from the holidays. You
all have given me much to think about. I've read all the messages through
once, now I need to go trough them again and try to apply the ideas. I'll
be posting other questions as I run into problems. BTW, Danny, best
explanation of generators I've heard, well done and thank you.

regards, Richard

On Thu, Dec 24, 2015 at 4:54 PM, Danny Yoo <dyoo at hashcollision.org> wrote:

> > I think what I need to do would be analogous to (pardon if I'm using the
> > wrong terminology, at this poing in the discussion I am officially out of
> > my depth) sending the input stream to a buffer(s) until  the ETX for that
> > message comes in, shoot the buffer contents to the parser while accepting
> > the next STX + message fragment into the buffer, or something analogous.
>
> Yes, I agree.  It sounds like you have one process read the socket and
> collect chunks of bytes delimited by the STX markers.  It can then
> send those chunks to the XML parser.
>
>
> We can imagine one process that reads the socket and spits out a list
> of byte chunks:
>
>     chunks = readDelimitedChunks(socket)
>
> and another process that parses those chunks and does something with them:
>
>     for chunk in chunks:
>         ....
>
>
> It would be nice if we could organize the program like this.  But one
> problem is that chunks might not be finite!  The socket might keep on
> returning bytes.  If it keeps returning bytes, we can't possibly
> return a finite list of the chunked bytes.
>
>
> What we really want is something like:
>
>     chunkStream = readDelimitedChunks(socket)
>     for chunk in chunkStream:
>         ....
>
> where chunkStream is itself like a socket: it should be something that
> we can repeatedly read from as if it were potentially infinite.
>
>
> We can actually do this, and it isn't too bad.  There's a mechanism in
> Python called a generator that allows us to write function-like things
> that consume streams of input and produce streams of output.  Here's a
> brief introduction to them.
>
> For example, here's a generator that knows how to produce an infinite
> stream of numbers:
>
> ##############
> def nums():
>     n = 0
>     while True:
>         yield n
>         n += 1
> ##############
>
> What distinguishes a generator from a regular function?  The use of
> "yield".  A "yield" is like a return, but rather than completely
> escape out of the function with the return value, this generator will
> remember what it was doing  at that time.  Why?  Because it can
> *resume* itself when we try to get another value out of the generator.
>
> Let's try it out:
>
> #####################
>
> >>> numStream = nums()
> >>> numStream.next()
> 0
> >>> numStream.next()
> 1
> >>> numStream.next()
> 2
> >>> numStream.next()
> 3
> >>> numStream.next()
> 4
> #####################
>
> Every next() we call on a generator will restart it from where it left
> off, until it reaches its next "yield".  That's how we get this
> generator to return an infinite sequence of things.
>
>
> That's how we produce infinite sequences.  And we can write another
> generator that knows how to take a stream of numbers, and square each
> one.
>
> ########################
> def squaring(stream):
>     for n in stream:
>         yield n
> ########################
>
>
> Let's try it.
>
>
> ########################
>
> >>> numStream = nums()
> >>> squaredNums = squaring(numStream)
> >>> squaredNums.next()
> 0
> >>> squaredNums.next()
> 1
> >>> squaredNums.next()
> 4
> >>> squaredNums.next()
> 9
> >>> squaredNums.next()
> 16
> ########################
>
>
> If you have experience with other programming languages, you may have
> heard of the term "co-routine".  What we're doing with this should be
> reminiscent of coroutine-style programming.  We have one generator
> feeding input into the other, with program control bouncing back and
> forth between the generators as necessary.
>
>
> So that's a basic idea of generators.  It lets us write processes that
> can deal with and produce streams of data.  In the context of sockets,
> this is particularly helpful, because sockets can be considered a
> stream of bytes.
>
>
> Here's another toy example that's closer to the problem you're trying
> to solve.  Let's say that we're working on a program to alphabetize
> the words of a sentence.  Very useless, of course.  :P  We might pass
> it in the input:
>
>     this
>     is
>     a
>     test
>     of
>     the
>     emergency
>     broadcast
>     system
>
> and expect to get back the following sentence:
>
>      hist
>      is
>      a
>      estt
>      fo
>      eht
>      ceeegmnry
>      aabcdorst
>      emssty
>
> We can imagine one process doing chunking, going from a sequence of
> characters to a sequence of words:
>
> ###########################################
> def extract_words(seq):
>     """Yield the words in a sequence of characters."""
>     buffer = []
>     for ch in seq:
>         if ch.isalpha():
>             buffer.append(ch)
>         elif buffer:
>             yield ''.join(buffer)
>             del buffer[:]
>     # If we hit the end of the buffer, we still might
>     # need to yield one more result.
>     if buffer:
>         yield ''.join(buffer)
> ###########################################
>
>
> and a function that transforms words to their munged counterpart:
>
> #########################
> def transform(word):
>     """"Munges a word into its alphabetized form."""
>     chars = list(word)
>     chars.sort()
>     return ''.join(chars)
> #########################
>
> This forms the major components of a program that can do the munging
> on a file... or a socket!
>
>
> Here's the complete example:
>
>
> #############################################
> import sys
>
> def extract_words(seq):
>     """Yield the words in a sequence of characters."""
>     buffer = []
>     for ch in seq:
>         if ch.isalpha():
>             buffer.append(ch)
>         elif buffer:
>             yield ''.join(buffer)
>             del buffer[:]
>     # If we hit the end of the buffer, we still might
>     # need to yield one more result.
>     if buffer:
>         yield ''.join(buffer)
>
> def transform(word):
>     """"Munges a word into its alphabetized form."""
>    chars = list(word)
>     chars.sort()
>     return ''.join(chars)
>
>
> def as_byte_seq(f):
>     """Return the bytes of the file-like object f as a
>     sequence."""
>     while True:
>         ch = f.read(1)
>         if not ch: break
>         yield ch
>
>
> if __name__ == '__main__':
>     for word in extract_words(as_byte_seq(sys.stdin)):
>         print(transform(word))
> ############################################
>
>
>
> If you have questions, please feel free to ask.  Good luck!
>



-- 

All internal models of the world are approximate. ~ Sebastian Thrun

From alan.gauld at btinternet.com  Tue Dec 29 20:26:55 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 30 Dec 2015 01:26:55 +0000
Subject: [Tutor] MemoryError
In-Reply-To: <CAAMZLuxyOHYWP6oYo6KRBqAVAK_3RpWtPbSBpv=CO=idU_w_Uw@mail.gmail.com>
References: <CAAMZLuxyOHYWP6oYo6KRBqAVAK_3RpWtPbSBpv=CO=idU_w_Uw@mail.gmail.com>
Message-ID: <n5vbsu$e84$1@ger.gmane.org>

On 29/12/15 17:00, Satya Luzy wrote:
> Hello,
> I am currently working on a program to find the prime factor of n, in which
> n is a big integer. Using the Continued Fraction factorization method 

To be honest this is probably a bit beyond the scope of the tutor
list which is aimed at questions about the Python language and
standard library. However I'll make a few observations (and assume
your logic is OK since you did test it on some smaller data first)


> ---------------------------------------------------------------------------------------------------------------------
> *Traceback (most recent call last):*
> *  File "C:/Users/Satya/PycharmProjects/untitled2/fact.py", line 94, in
> <module>*
> *    faktorisasi(n)*
> *  File "C:/Users/Satya/PycharmProjects/untitled2/fact.py", line 92, in
> faktorisasi*
> *    faktorisasi_default(n,j,boundary)*
> *  File "C:/Users/Satya/PycharmProjects/untitled2/fact.py", line 55, in
> faktorisasi_default*
> *    Q.append(((n*kelipatan)-(p[i]**2))/Q[i-1])*
> *MemoryError*

There's not much of a clue in the error message but there are several
things we can note about your code, which if cleaned up would make
it easier to test/debug and also might reduce the memory consumption.
I don't know if any of these suggestions will help with the memory error
but clarity of code can only help think about the problem.

First you communicate between functions with globals, it would be better
to return values. (For example the flag that only exists to
be set in the faktorisasi_default code so that it influences the
faktorisasi while loop.)

Second you have a lot of loops that all appear to be looping over
the same basic data set. Is it possible to combine the processing
of those loops in some way? Alternatively could you
refactor the code to break the loops into separate functions
so that the higher level algorithm is clearer?

Third you have a lot of intermediate variables that seem to add
little value but clutter the code. (see below)


> import fractions
> import math
> 
> n = 94152743499601547 #untuk difaktorkan
> flag = True
> faktor_1 = 1    #deklarasi asal
> faktor_2 = 1
> 
> # CFRAC
> def cfract(n,boundary):
>    coeff = 1
>    floor_part = floor_ = math.floor(math.sqrt(n))
>    denom = n - floor_part ** 2
>    result = []
>    result.append(int(floor_))
> 
>    if float(denom)!=0:
>       for i in range(boundary-1):
>          try:
>             floor_ = math.floor((math.sqrt(n) + floor_part) / float(denom))
>          except ZeroDivisionError: # perfect square
>             return result
> 
>          if denom != 1:
>             result.append(int(floor_))
>          floor_part = denom * floor_ - floor_part
>          coeff = denom
>          denom = n - floor_part ** 2
>          common_div = fractions.gcd(coeff, denom)
>          coeff /= common_div
>          denom /= common_div
> 
>          if denom == 1:
>             result.append(int(floor_part + result[0]))
>    return result
> 
> def faktorisasi_default(n,kelipatan,boundary):
>     global faktor_1,faktor_2,flag
> 
>     q = cfract(n*kelipatan,boundary)
>     p = []
>     Q = []
>     A = []
>     p.append(0)
>     p.append(q[0])
>     Q.append(1)
>     A.append(0)
>     A.append(1)
>     A.append(q[0])
>     Q.append(((n*kelipatan)-(p[1]**2))/Q[0])

You could combine these lines to include the initial values
directly as:

p = [0, q[0]]
Q = [1, ((n*kelipatan)-(p[1]**2))/Q[0]]
A = [0,1]

Also since it appears more than once you could assign

def f(n,k):
   return ((n*k)-(p[1]**2))/Q[0]

Where you can hopefully think of a better name than 'f'...

> 
> # i = 2
>     for i in range(2,len(q)):
>         p.append((q[i-1]*Q[i-1])-p[i-1])
>         Q.append(((n*kelipatan)-(p[i]**2))/Q[i-1])
>         A.append((q[i-1]*A[i]+A[i-1])%(n*kelipatan))
>     #tabel sudah selesai
> 
>     temp = 0        # nilai Q yg ganda
>     temp2 = 0
>     tempA1 = 0      # nilai A dari Q1
>     tempA2 = 0      # nilai A dari Q2

Since you don;t use these before assigning them below you
don't really need to initialise them here in the middle
of your algorithm. Just create them by assigning to them
later.

>     for i in range(0,len(Q)):
>         for j in range(i+1,len(Q)):

These loops look suspicious to me. They both loop over the
same data range and look like they do an awful lot of work
on the same basic data. Could they be rationalised? I may
be wrong, I haven't a clue about what the algorithm is
supposed to do. It just feels odd somehow.

>             if flag and Q[i]==Q[j]:
>                 print Q[i]
>                 print Q[j]
>                 temp = Q[i]
>                 tempA1 = A[i+1]
>                 tempA2 = A[j+1]
> 
>                 temp2 = tempA1*tempA2 % n # nilai base

Do you really gain anything with the tempA variables?
Why not just use

                  temp2 = A[i+1] * A[j+1] % n

>                 if temp2 > Q[i]:
>                     faktor_1 = int(fractions.gcd(temp2+temp,n))
>                     faktor_2 = int(fractions.gcd(temp2-temp,n))
> 
>                     if faktor_1 != 1 and faktor_2 != 1:
>                         flag = False
> 

This is where I mentioned the flag being used to communicate between
functions.

Could you not return False here since the loop will do no more work
after the flag is set (but may continue to iterate for quite some time)
If the outer loop completes without returning False then you can
return true.... I think...


> def faktorisasi(n):
>     global flag
>     j=1 #kelipatan
>     boundary=50 #iterasi CFRAC
>     faktorisasi_default(n,j,boundary)
>     while (flag):

This would then become

while faktorisasi_default(n,j,boundary):
        j+=1
        boundary*=2
        print "Nilai boundary : %d" %boundary
        print "Nilai j : %d" %j


As I say I don't know if any of that will help with the
memory error but it should improve clarity at least a little.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From steve at pearwood.info  Tue Dec 29 20:51:49 2015
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 30 Dec 2015 12:51:49 +1100
Subject: [Tutor] MemoryError
In-Reply-To: <CAAMZLuxyOHYWP6oYo6KRBqAVAK_3RpWtPbSBpv=CO=idU_w_Uw@mail.gmail.com>
References: <CAAMZLuxyOHYWP6oYo6KRBqAVAK_3RpWtPbSBpv=CO=idU_w_Uw@mail.gmail.com>
Message-ID: <20151230015149.GU23700@ando.pearwood.info>

On Wed, Dec 30, 2015 at 12:00:02AM +0700, Satya Luzy wrote:
> Hello,
> I am currently working on a program to find the prime factor of n, in which
> n is a big integer. Using the Continued Fraction factorization method (I
> will provide the source code below, please don't mind the variables). 

Are you referring to this?

http://mathworld.wolfram.com/ContinuedFractionFactorizationAlgorithm.html

> It
> works perfectly when factorizing below 10 digits numbers. In my code below
> you will see on how I tried to factorize 94152743499601547, but get this
> message instead :
> ---------------------------------------------------------------------------------------------------------------------
> *Traceback (most recent call last):*
> *  File "C:/Users/Satya/PycharmProjects/untitled2/fact.py", line 94, in
> <module>*
> *    faktorisasi(n)*
> *  File "C:/Users/Satya/PycharmProjects/untitled2/fact.py", line 92, in
> faktorisasi*
> *    faktorisasi_default(n,j,boundary)*
> *  File "C:/Users/Satya/PycharmProjects/untitled2/fact.py", line 55, in
> faktorisasi_default*
> *    Q.append(((n*kelipatan)-(p[i]**2))/Q[i-1])*
> *MemoryError*
> 
> *Process finished with exit code 1*
> --------------------------------------------------------------------------------------------------------------------
> It has undergone the boundary value of 51200 and j value of 12. It has been
> running for more than 5 hours before it suddenly stop.
> Please let me know how to fix the memory error,

Install lots more memory.

But really, the problem here is not the MemoryError, that is just the 
symptom. Five hours to factorise a 17 digit number is a sign that either 
your code has a bug, or that the algorithm is too inefficient. If it 
works for 10 digit numbers, I can guess that it probably doesn't have a 
bug) but the algorithm, or at least your implementation of it, is too 
inefficient. I can factorise that number in under 6 seconds:

py> print(pyprimes.factors.factorise(94152743499601547))
[6784787, 13877037481]

so it is certainly possible to do better.

Unfortunately factorisation is a hard problem, and algorithms which work 
in theory (as a mathematical process) may be too slow to be practical on 
even the fastest computer. For example, my factorise function can 
factorise 94152743499601547 in six seconds, but it might take weeks to 
factorise 8864739108501786973334779656429353 into [94152743499601627, 
94152743499601739].

So it may simply be that your code is perfectly correct, but is not 
efficient enough to deal with 17 digit numbers. For example, I see that 
your faktorisasi_default function keeps three lists, p, Q and A, which 
can grow very large. Large enough that you run out of memory.

I haven't studied either the factorization algorithm or your code enough 
to tell whether you can make it more efficient. I would need to 
understand the algorithm better to do that.



-- 
Steve

From dyoo at hashcollision.org  Tue Dec 29 21:00:05 2015
From: dyoo at hashcollision.org (Danny Yoo)
Date: Tue, 29 Dec 2015 18:00:05 -0800
Subject: [Tutor] MemoryError
In-Reply-To: <n5vbsu$e84$1@ger.gmane.org>
References: <CAAMZLuxyOHYWP6oYo6KRBqAVAK_3RpWtPbSBpv=CO=idU_w_Uw@mail.gmail.com>
 <n5vbsu$e84$1@ger.gmane.org>
Message-ID: <CAGZAPF66Rp+tBR=A_ad+=b4eQU7ZRQbHwURwfCNKf7h2wLPZ1g@mail.gmail.com>

> To be honest this is probably a bit beyond the scope of the tutor
> list which is aimed at questions about the Python language and
> standard library. However I'll make a few observations (and assume
> your logic is OK since you did test it on some smaller data first)


Just to add to Alan's comments:  a MemoryError means that your program
is keeping so many things in memory that it has exhausted this
large-but-limited resource.  Typically, when this happens, a
programmer studies their program to see whether they really do need to
keep all the held values at once.

Perhaps the approach itself is doing more than it needs to do.
Unfortunately, without a deep understanding of the approach you are
taking, we can't say anything concrete about this.  From briefly
picking through:

    https://math.dartmouth.edu/~carlp/PDF/implementation.pdf

it does sound like you *have* to do several clever tricks to make this
work in practice: that paper is all about techniques for making CFRAC
work on real computers.  This does not look trivial.

I don't think this is appropriate for Python-tutor, unfortunately.

From martin at linux-ip.net  Tue Dec 29 21:29:00 2015
From: martin at linux-ip.net (Martin A. Brown)
Date: Tue, 29 Dec 2015 18:29:00 -0800
Subject: [Tutor] MemoryError
In-Reply-To: <CAAMZLuxyOHYWP6oYo6KRBqAVAK_3RpWtPbSBpv=CO=idU_w_Uw@mail.gmail.com>
References: <CAAMZLuxyOHYWP6oYo6KRBqAVAK_3RpWtPbSBpv=CO=idU_w_Uw@mail.gmail.com>
Message-ID: <alpine.LSU.2.11.1512291805040.20208@qnttre.jbaqresebt.arg>


Hello there Satya,

>I am currently working on a program to find the prime factor of n, in which
>n is a big integer. Using the Continued Fraction factorization method (I
>will provide the source code below, please don't mind the variables).

I do not know the Continued Fraction factorization method.  (I admit 
to not looking it up and simply examining your code.)

>It works perfectly when factorizing below 10 digits numbers.

Are you certain?  All 10 digit numbers?  Or just the 10 digit 
numbers you tried?  I ask because....  Well, please see my second 
point below.

>In my code below you will see on how I tried to factorize 
>94152743499601547, but get this message instead :

Alan, Steven and Danny have other useful comments.  I will not 
repeat those.

You may find it a bit easier to diagnose which data structure is 
exploding in size by logging/printing the contents of the lists p, Q 
and A, which you maintain in the function faktorisasi_default().

I made a few small modifications to your code (see below) so that I 
could run it on smaller numbers.  Here are some comments:

  * I adjusted the variables accepted in faktorisasi_default so that
    there is no need for using a 'global' variable.  I don't like 
    using globals if it is possible to avoid.  In pure mathematical 
    functions, it is usually possible to avoid using a global.  If 
    you need an intermediate work product from the function (in 
    addition to the result), then simply return the intermediate 
    work product along with the result.

  * See below my (slight) modifications to your code.  Now, you can 
    see how I'm running the program to perform some more diagnosis.
    I think you have some sort of recursion termination problem in 
    your functions which are implementing your factoring.  In 
    short, determining I don't think that faktorisasi_default knows 
    when to stop.  Here's how I drew this conclusion:

      python wuzzyluzy.py 18      # -- stops with four lines of output
      python wuzzyluzy.py 12275   # -- stops with four lines of output
      python wuzzyluzy.py 262144  # -- stops with many lines of output
      python wuzzyluzy.py 17      # -- never stops
      python wuzzyluzy.py 19      # -- never stops

Good luck in your hunt for the wily factors,

-Martin



import fractions
import math

# CFRAC
def cfract(n, boundary):
   coeff = 1
   floor_part = floor_ = math.floor(math.sqrt(n))
   denom = n - floor_part ** 2
   result = []
   result.append(int(floor_))

   if float(denom)!=0:
      for i in range(boundary-1):
         try:
            floor_ = math.floor((math.sqrt(n) + floor_part) / float(denom))
         except ZeroDivisionError: # perfect square
            return result

         if denom != 1:
            result.append(int(floor_))
         floor_part = denom * floor_ - floor_part
         coeff = denom
         denom = n - floor_part ** 2
         common_div = fractions.gcd(coeff, denom)
         coeff /= common_div
         denom /= common_div

         if denom == 1:
            result.append(int(floor_part + result[0]))
   return result

def faktorisasi_default(n, kelipatan, boundary, faktor_1, faktor_2, flag):
    q = cfract(n*kelipatan, boundary)
    p = [0, q[0]]
    Q = [1]
    A = [0, 1, q[0]]
    Q.append(((n*kelipatan)-(p[1]**2))/Q[0])
    # i = 2
    for i in range(2,len(q)):
        p.append((q[i-1]*Q[i-1])-p[i-1])
        Q.append(((n*kelipatan)-(p[i]**2))/Q[i-1])
        A.append((q[i-1]*A[i]+A[i-1])%(n*kelipatan))
    #tabel sudah selesai

    for i in range(0,len(Q)):
        for j in range(i+1,len(Q)):
            if flag and Q[i]==Q[j]:
                print Q[i]
                print Q[j]
                temp = Q[i]
                tempA1 = A[i+1]
                tempA2 = A[j+1]

                temp2 = tempA1*tempA2 % n # nilai base

                if temp2 > Q[i]:
                    faktor_1 = int(fractions.gcd(temp2+temp, n))
                    faktor_2 = int(fractions.gcd(temp2-temp, n))

                    if faktor_1 != 1 and faktor_2 != 1:
                        flag = False

    return faktor_1, faktor_2, flag

def faktorisasi(n):
    flag = True
    faktor_1, faktor_2 = 1, 1
    j=1 #kelipatan
    boundary=50 #iterasi CFRAC
    faktor_1, faktor_2, flag = faktorisasi_default(n, j, boundary, faktor_1, faktor_2, flag)
    while (flag):
       j+=1
       boundary*=2
       print "Nilai boundary : %d" %boundary
       print "Nilai j : %d" %j
       faktor_1, faktor_2, flag = faktorisasi_default(n, j, boundary, faktor_1, faktor_2, flag)
    return faktor_1, faktor_2

if __name__ == '__main__':
    import sys
    if len(sys.argv) > 1:
        n = int(sys.argv[1])
    else:
        n = 94152743499601547 #untuk difaktorkan
    faktor_1, faktor_2 = faktorisasi(n)
    print faktor_1
    print faktor_2


-- 
Martin A. Brown
http://linux-ip.net/

From robertvstepp at gmail.com  Tue Dec 29 23:38:11 2015
From: robertvstepp at gmail.com (boB Stepp)
Date: Tue, 29 Dec 2015 22:38:11 -0600
Subject: [Tutor] OT: How best to use Git for multi-directory projects?
Message-ID: <CANDiX9JeQ2X5xfvo_1xYne6-KcCpzSao5NV=ovWi-quR0xPZpw@mail.gmail.com>

I have two situations that I wish to use Git for:  1) Multi-directory
Python projects and 2) learning Python from various books which
inevitably have suggested exercises to program solutions for.

For (1) I might have multiple projects going simultaneously.  Say
something like:

project1/
....source/
....tests/
....data/
....etc

project2/
....etc

projectn/
....etc

My thoughts are that each project should have its own .git file.  If
this is correct, then I further think that there should be a single
.git file to track everything in each project folder at its top level
and use git add . at the project folder level to add anything that has
been added anywhere in any subfolder of the project folder.  Am I
thinking correctly in this?

For (2) I first want to state publicly:

New Year's Resolution:

I WILL study--in parallel--the following three books from cover to
cover, doing ALL non-trivial exercises:
    "Think Python, 2nd Edition" by Allen Downey
    "Introduction to Computation and Programming Using Python, Revised
and Expanded Edition" by John V. Guttag
    "Python Crash Course" by Eric Matthes

I hope that by saying this openly I will actually DO what I mean to
do!  I am tired of "Easter-egging" Python, able to use lots of
different features, but with no thorough understanding/mastery of
anything.  The first two books are to get down basic intro to CSc
topics which have probably evolved since the mid- to late-seventies
when I took my basic CSc courses, while the third hopefully will fill
in Python language features and syntax that the first two books skip.

But to the questions.  This seems essentially parallel to (1) in
regards to using Git.  I want to track all of the programming work I
do for these 3 books.  I anticipate a directory structure similar to:

StudyBooks/
    Book1/
        Ch1/
            example1.py
            example2.py
            exercise1.py
            etc
        Ch2/
        etc

    Book2/
etc.

Since I will be studying these 3 books in parallel, would it make
sense to track everything with a single .git file at the level of
StudyBooks directory?

Hoping to more effectively use Git in the new year!

-- 
boB

From martin at linux-ip.net  Wed Dec 30 00:32:32 2015
From: martin at linux-ip.net (Martin A. Brown)
Date: Tue, 29 Dec 2015 21:32:32 -0800
Subject: [Tutor] OT: How best to use Git for multi-directory projects?
In-Reply-To: <CANDiX9JeQ2X5xfvo_1xYne6-KcCpzSao5NV=ovWi-quR0xPZpw@mail.gmail.com>
References: <CANDiX9JeQ2X5xfvo_1xYne6-KcCpzSao5NV=ovWi-quR0xPZpw@mail.gmail.com>
Message-ID: <alpine.LSU.2.11.1512292050250.20208@qnttre.jbaqresebt.arg>


Hello there boB,

Hey, wait a second!  What time zone are you in?  You can't have 2016 
resolutions already.  Not even the New Zealanders are there yet!

>I have two situations that I wish to use Git for:  1) Multi-directory
>Python projects and 2) learning Python from various books which
>inevitably have suggested exercises to program solutions for.
>
>For (1) I might have multiple projects going simultaneously.  Say
>something like:

[snip]

>My thoughts are that each project should have its own .git file.

N.B. this is not a Python question, but ... do you mean .git 
directory?

>If this is correct, then I further think that there should be a 
>single .git file to track everything in each project folder at its 
>top level and use git add . at the project folder level to add 
>anything that has been added anywhere in any subfolder of the 
>project folder.  Am I thinking correctly in this?

>For (2) I first want to state publicly:
>
>New Year's Resolution:
>
>I WILL study--in parallel--the following three books from cover to
>cover, doing ALL non-trivial exercises:
>    "Think Python, 2nd Edition" by Allen Downey
>    "Introduction to Computation and Programming Using Python, Revised and Expanded Edition" by John V. Guttag
>    "Python Crash Course" by Eric Matthes

(Side note:  I do not know any of these three books.)

Reading cover to cover is one way to go about it.  I think that it 
helps to balance such thorough and complete study of books with the 
direct experience of writing software.

Also, I might suggest one other reference and technique--it is more 
a generic strategy for continuous learning, here applied to 
increasing your Python proficiency.

Pick one standard library module per week (or day) and read the 
whole page of documentation.  Pick a module that is relevant to some 
problem you are solving and study each function of the module.  

Alternate between the common ones (in my world:  sys, os, time, 
math, string, re, random, csv, httplib, urllib) and some others 
(hashlib, difflib, sched, bz2, itertools, multiprocessing).  Of 
course, start by tailoring your module choice to your tasks.

>But to the questions.  This seems essentially parallel to (1) in 
>regards to using Git.  I want to track all of the programming work 
>I do for these 3 books.  I anticipate a directory structure similar 
>to:
>
>StudyBooks/
>    Book1/
>        Ch1/
>            example1.py
>            example2.py
>            exercise1.py
>            etc
>        Ch2/
>        etc
>
>    Book2/
>etc.
>
>Since I will be studying these 3 books in parallel, would it make
>sense to track everything with a single .git file at the level of
>StudyBooks directory?

I'm accustomed to keeping a single git repository for each distinct 
project or program I'm working on.  In the context of Python, I 
create a separate git repository for each distribution that I may 
release.  (So, if I am going to write a new "setup.py", then it is 
time for a new git repository.)

To apply this approach to your case, I would make a different git 
repository for each StudyBook.

There are different strategies depending on what you are doing with 
the software and the environment in which you are working.

Good luck and have fun with Python in 2016, since you have arrived 
there before the rest of us,

-Martin

P.S. Two questions:  should I buy some some YHOO stock and should I
   sell my Euros?

-- 
Martin A. Brown
http://linux-ip.net/

From steve at pearwood.info  Wed Dec 30 01:36:27 2015
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 30 Dec 2015 17:36:27 +1100
Subject: [Tutor] MemoryError
In-Reply-To: <CAAMZLuxyOHYWP6oYo6KRBqAVAK_3RpWtPbSBpv=CO=idU_w_Uw@mail.gmail.com>
References: <CAAMZLuxyOHYWP6oYo6KRBqAVAK_3RpWtPbSBpv=CO=idU_w_Uw@mail.gmail.com>
Message-ID: <20151230063627.GV23700@ando.pearwood.info>

On Wed, Dec 30, 2015 at 12:00:02AM +0700, Satya Luzy wrote:
> Hello,
> I am currently working on a program to find the prime factor of n, in which
> n is a big integer. Using the Continued Fraction factorization method (I
> will provide the source code below, please don't mind the variables).
[...]

I have had a bit more time available to look at this, and I don't think 
your code is correct. I changed the value of n from 94152743499601547 to 
18. Factorising 18 should give [2, 3, 3], but your code prints:

1
1
18
2


before ending. I tried it again with n = 459, which should factorise 
to [3, 3, 3, 17], but your code prints:

1
1
1
1
1
1
1
1
1
1
18
18
459
9

Then I added an extra line to the faktorisasi_default function, at the 
very end:

print 'q =', q, 'p =', p, 'Q =', Q, 'A =', A

and ran it again with n = 459 and got these results:

q = [21, 2, 2, 1, 4, 21, 4, 1, 2, 2, 42, 
         2, 2, 1, 4, 21, 4, 1, 2, 2, 42, 
         2, 2, 1, 4, 21, 4, 1, 2, 2, 42, 
         2, 2, 1, 4, 21, 4, 1, 2, 2, 42, 
         2, 2, 1, 4, 21, 4, 1, 2, 2, 42] 
p = [0, 21, 15, 11, 15, 21, 
        21, 15, 11, 15, 21, 
        21, 15, 11, 15, 21, 
        21, 15, 11, 15, 21, 
        21, 15, 11, 15, 21, 
        21, 15, 11, 15, 21, 
        21, 15, 11, 15, 21, 
        21, 15, 11, 15, 21, 
        21, 15, 11, 15, 21, 
        21, 15, 11, 15, 21] 
Q = [1, 18, 13, 26, 9, 2, 9, 26, 13, 18, 1, 
        18, 13, 26, 9, 2, 9, 26, 13, 18, 1, 
        18, 13, 26, 9, 2, 9, 26, 13, 18, 1, 
        18, 13, 26, 9, 2, 9, 26, 13, 18, 1, 
        18, 13, 26, 9, 2, 9, 26, 13, 18, 1] 
A = [0, 1, 21, 43, 107, 150, 248, 309, 107, 416, 21, 458, 
            438, 416, 352, 309, 211, 150, 352, 43, 438, 
        1, 21, 43, 107, 150, 248, 309, 107, 416, 21, 458, 
            438, 416, 352, 309, 211, 150, 352, 43, 438, 
        1, 21, 43, 107, 150, 248, 309, 107, 416, 21, 458]

(reformatted to make them easier to read). So you can see the problem: 
to factorise a 3 digit number, you have recorded over 200 numbers. 
And the numbers have repeating patterns, as you can see above.

I don't know if this is expected by the algorithm, or if you have made a 
programming error, but this looks very suspicious to me. At the very 
least, if you know that these repeating patterns are expected, there is 
no need to keep growing the lists and making them bigger and bigger, you 
can just build the pattern once.



-- 
Steve

From wuzzyluzy at gmail.com  Wed Dec 30 01:26:34 2015
From: wuzzyluzy at gmail.com (Satya Luzy)
Date: Wed, 30 Dec 2015 13:26:34 +0700
Subject: [Tutor] MemoryError
In-Reply-To: <alpine.LSU.2.11.1512291805040.20208@qnttre.jbaqresebt.arg>
References: <CAAMZLuxyOHYWP6oYo6KRBqAVAK_3RpWtPbSBpv=CO=idU_w_Uw@mail.gmail.com>
 <alpine.LSU.2.11.1512291805040.20208@qnttre.jbaqresebt.arg>
Message-ID: <CAAMZLuw3oi9Pif_uOfSd=EAu_aKcZgwp28qg0T2D1t6EdV6_vw@mail.gmail.com>

Dear everyone, thank you for all of your support.
To Alan :
It is true that my code still need some improvement on the efficiency part,
and thanks for pointing out which part that needs to be improved. Speaking
of the nested loops, with my ability, I don't think I could simplify it, as
the nested loops is meant to look for a same value that occured twice or
more in the table (that's how the algorithm works, in my learning).
Really appreciate it :)

To Steven :
Well, I used a Laptop with i5 processor and 6GB of RAM in Windows 8 64-bit.
Wouldn't that be enough?
Either way, it is true that my method is not the best factorization method
nowadays. It was best used in the 70's. And I'm here to just do a research.
So it's not really surprising that it will not be that fast to have the
process done. I'm just having a problem because the process is interrupted
with MemoryError.

To Danny :
I'm sorry for the unfavored topic. Yeah I have understood the method and I
was just trying to convert it into code. By the way, I'm using the
references of (Mollin, Public Key Cryptography).

To Martin :
It is also true that I forgot to mention that the tested 10-digit numbers
are the non-prime numbers (Yeah, seems like I will have to add a primality
test before running the factorization). I was just too desperate to use the
global variable (lol). Yeah, I will try my best to avoid using it in the
future time. In my codes, the output of having 4 or more lines are to be
expected, for the first two lines are value of Q that is being compared due
to the same value and take the value associated with Q, which is A. Q is
printed and A is not. Then the last 2 lines are the actual factor. Thank
you for improving my code.


By the way, did a little bit of searching, does my 64-bit Operating System
has less performance because it is used for a 32-bit activity?

Really glad to have this community.
Have a good day!


On Wed, Dec 30, 2015 at 9:29 AM, Martin A. Brown <martin at linux-ip.net>
wrote:

>
> Hello there Satya,
>
> >I am currently working on a program to find the prime factor of n, in
> which
> >n is a big integer. Using the Continued Fraction factorization method (I
> >will provide the source code below, please don't mind the variables).
>
> I do not know the Continued Fraction factorization method.  (I admit
> to not looking it up and simply examining your code.)
>
> >It works perfectly when factorizing below 10 digits numbers.
>
> Are you certain?  All 10 digit numbers?  Or just the 10 digit
> numbers you tried?  I ask because....  Well, please see my second
> point below.
>
> >In my code below you will see on how I tried to factorize
> >94152743499601547, but get this message instead :
>
> Alan, Steven and Danny have other useful comments.  I will not
> repeat those.
>
> You may find it a bit easier to diagnose which data structure is
> exploding in size by logging/printing the contents of the lists p, Q
> and A, which you maintain in the function faktorisasi_default().
>
> I made a few small modifications to your code (see below) so that I
> could run it on smaller numbers.  Here are some comments:
>
>   * I adjusted the variables accepted in faktorisasi_default so that
>     there is no need for using a 'global' variable.  I don't like
>     using globals if it is possible to avoid.  In pure mathematical
>     functions, it is usually possible to avoid using a global.  If
>     you need an intermediate work product from the function (in
>     addition to the result), then simply return the intermediate
>     work product along with the result.
>
>   * See below my (slight) modifications to your code.  Now, you can
>     see how I'm running the program to perform some more diagnosis.
>     I think you have some sort of recursion termination problem in
>     your functions which are implementing your factoring.  In
>     short, determining I don't think that faktorisasi_default knows
>     when to stop.  Here's how I drew this conclusion:
>
>       python wuzzyluzy.py 18      # -- stops with four lines of output
>       python wuzzyluzy.py 12275   # -- stops with four lines of output
>       python wuzzyluzy.py 262144  # -- stops with many lines of output
>       python wuzzyluzy.py 17      # -- never stops
>       python wuzzyluzy.py 19      # -- never stops
>
> Good luck in your hunt for the wily factors,
>
> -Martin
>
>
>
> import fractions
> import math
>
> # CFRAC
> def cfract(n, boundary):
>    coeff = 1
>    floor_part = floor_ = math.floor(math.sqrt(n))
>    denom = n - floor_part ** 2
>    result = []
>    result.append(int(floor_))
>
>    if float(denom)!=0:
>       for i in range(boundary-1):
>          try:
>             floor_ = math.floor((math.sqrt(n) + floor_part) / float(denom))
>          except ZeroDivisionError: # perfect square
>             return result
>
>          if denom != 1:
>             result.append(int(floor_))
>          floor_part = denom * floor_ - floor_part
>          coeff = denom
>          denom = n - floor_part ** 2
>          common_div = fractions.gcd(coeff, denom)
>          coeff /= common_div
>          denom /= common_div
>
>          if denom == 1:
>             result.append(int(floor_part + result[0]))
>    return result
>
> def faktorisasi_default(n, kelipatan, boundary, faktor_1, faktor_2, flag):
>     q = cfract(n*kelipatan, boundary)
>     p = [0, q[0]]
>     Q = [1]
>     A = [0, 1, q[0]]
>     Q.append(((n*kelipatan)-(p[1]**2))/Q[0])
>     # i = 2
>     for i in range(2,len(q)):
>         p.append((q[i-1]*Q[i-1])-p[i-1])
>         Q.append(((n*kelipatan)-(p[i]**2))/Q[i-1])
>         A.append((q[i-1]*A[i]+A[i-1])%(n*kelipatan))
>     #tabel sudah selesai
>
>     for i in range(0,len(Q)):
>         for j in range(i+1,len(Q)):
>             if flag and Q[i]==Q[j]:
>                 print Q[i]
>                 print Q[j]
>                 temp = Q[i]
>                 tempA1 = A[i+1]
>                 tempA2 = A[j+1]
>
>                 temp2 = tempA1*tempA2 % n # nilai base
>
>                 if temp2 > Q[i]:
>                     faktor_1 = int(fractions.gcd(temp2+temp, n))
>                     faktor_2 = int(fractions.gcd(temp2-temp, n))
>
>                     if faktor_1 != 1 and faktor_2 != 1:
>                         flag = False
>
>     return faktor_1, faktor_2, flag
>
> def faktorisasi(n):
>     flag = True
>     faktor_1, faktor_2 = 1, 1
>     j=1 #kelipatan
>     boundary=50 #iterasi CFRAC
>     faktor_1, faktor_2, flag = faktorisasi_default(n, j, boundary,
> faktor_1, faktor_2, flag)
>     while (flag):
>        j+=1
>        boundary*=2
>        print "Nilai boundary : %d" %boundary
>        print "Nilai j : %d" %j
>        faktor_1, faktor_2, flag = faktorisasi_default(n, j, boundary,
> faktor_1, faktor_2, flag)
>     return faktor_1, faktor_2
>
> if __name__ == '__main__':
>     import sys
>     if len(sys.argv) > 1:
>         n = int(sys.argv[1])
>     else:
>         n = 94152743499601547 #untuk difaktorkan
>     faktor_1, faktor_2 = faktorisasi(n)
>     print faktor_1
>     print faktor_2
>
>
> --
> Martin A. Brown
> http://linux-ip.net/
>

From wuzzyluzy at gmail.com  Wed Dec 30 02:35:18 2015
From: wuzzyluzy at gmail.com (Satya Luzy)
Date: Wed, 30 Dec 2015 14:35:18 +0700
Subject: [Tutor] MemoryError
In-Reply-To: <20151230063627.GV23700@ando.pearwood.info>
References: <CAAMZLuxyOHYWP6oYo6KRBqAVAK_3RpWtPbSBpv=CO=idU_w_Uw@mail.gmail.com>
 <20151230063627.GV23700@ando.pearwood.info>
Message-ID: <CAAMZLux+1QK0heOX0MdVDwvPyKdQz40b8bieKETFhOfFSr7JuQ@mail.gmail.com>

Thanks for testing out more of the program.
Yes, as you can see, I'm using the continued fraction method on n, which in
your case is 459.
During the continued fraction process (referring to function
cfract(n,boundary)), I set the boundary to store only 50 value of the first
iteration. The result of that function can be in a short pattern, just like
what you have seen:
[21, 2, 2, 1, 4, 21, 4, 1, 2, 2, 42,
      2, 2, 1, 4, 21, 4, 1, 2, 2, 42,
      2, 2, 1, 4, 21, 4, 1, 2, 2, 42,
      2, 2, 1, 4, 21, 4, 1, 2, 2, 42,
      2, 2, 1, 4, 21, 4, 1, 2, 2, 42]
In this case, the algorithm may get nothing or fail in this step because of
q (not Q) value. Thus, variable j is introduced.
When it comes to this, my code will move to faktorisasi function.
Fulfilling a mathematical rule where 459 = k.459 (mod n). The k is
multiplication, which is represented by j. Thus my program when it failed
on the first try, it will increase both the boundary and k or j until it
found the match. In faktorisasi_default function, it is creating one table
that consists of q,P,Q,A. The j variable is for the next table generation.

I will try more cases on my unfinished program.
Meanwhile, please bear with my amateurishness.
Thanks

On Wed, Dec 30, 2015 at 1:36 PM, Steven D'Aprano <steve at pearwood.info>
wrote:

> On Wed, Dec 30, 2015 at 12:00:02AM +0700, Satya Luzy wrote:
> > Hello,
> > I am currently working on a program to find the prime factor of n, in
> which
> > n is a big integer. Using the Continued Fraction factorization method (I
> > will provide the source code below, please don't mind the variables).
> [...]
>
> I have had a bit more time available to look at this, and I don't think
> your code is correct. I changed the value of n from 94152743499601547 to
> 18. Factorising 18 should give [2, 3, 3], but your code prints:
>
> 1
> 1
> 18
> 2
>
>
> before ending. I tried it again with n = 459, which should factorise
> to [3, 3, 3, 17], but your code prints:
>
> 1
> 1
> 1
> 1
> 1
> 1
> 1
> 1
> 1
> 1
> 18
> 18
> 459
> 9
>
> Then I added an extra line to the faktorisasi_default function, at the
> very end:
>
> print 'q =', q, 'p =', p, 'Q =', Q, 'A =', A
>
> and ran it again with n = 459 and got these results:
>
> q = [21, 2, 2, 1, 4, 21, 4, 1, 2, 2, 42,
>          2, 2, 1, 4, 21, 4, 1, 2, 2, 42,
>          2, 2, 1, 4, 21, 4, 1, 2, 2, 42,
>          2, 2, 1, 4, 21, 4, 1, 2, 2, 42,
>          2, 2, 1, 4, 21, 4, 1, 2, 2, 42]
> p = [0, 21, 15, 11, 15, 21,
>         21, 15, 11, 15, 21,
>         21, 15, 11, 15, 21,
>         21, 15, 11, 15, 21,
>         21, 15, 11, 15, 21,
>         21, 15, 11, 15, 21,
>         21, 15, 11, 15, 21,
>         21, 15, 11, 15, 21,
>         21, 15, 11, 15, 21,
>         21, 15, 11, 15, 21]
> Q = [1, 18, 13, 26, 9, 2, 9, 26, 13, 18, 1,
>         18, 13, 26, 9, 2, 9, 26, 13, 18, 1,
>         18, 13, 26, 9, 2, 9, 26, 13, 18, 1,
>         18, 13, 26, 9, 2, 9, 26, 13, 18, 1,
>         18, 13, 26, 9, 2, 9, 26, 13, 18, 1]
> A = [0, 1, 21, 43, 107, 150, 248, 309, 107, 416, 21, 458,
>             438, 416, 352, 309, 211, 150, 352, 43, 438,
>         1, 21, 43, 107, 150, 248, 309, 107, 416, 21, 458,
>             438, 416, 352, 309, 211, 150, 352, 43, 438,
>         1, 21, 43, 107, 150, 248, 309, 107, 416, 21, 458]
>
> (reformatted to make them easier to read). So you can see the problem:
> to factorise a 3 digit number, you have recorded over 200 numbers.
> And the numbers have repeating patterns, as you can see above.
>
> I don't know if this is expected by the algorithm, or if you have made a
> programming error, but this looks very suspicious to me. At the very
> least, if you know that these repeating patterns are expected, there is
> no need to keep growing the lists and making them bigger and bigger, you
> can just build the pattern once.
>
>
>
> --
> Steve
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From xupeng.psu at gmail.com  Wed Dec 30 00:55:43 2015
From: xupeng.psu at gmail.com (Tom Xu)
Date: Wed, 30 Dec 2015 00:55:43 -0500
Subject: [Tutor] How to plot amount of lines but the amount is a input
Message-ID: <CAOsEKozDz+8O9Z1s1LEYd5W_C3aTZtNsEfnb-6uxA8+RKaKjeQ@mail.gmail.com>

Dear Pythoneers,

I want to draw several curves in one graph, but the amount of curves is not
a fixed number.
My homework is below:
---
import matplotlib.pyplot as plt
import math

if __name__=='__main__':
    try:
        n=int(input('how many curves? '))
        ulist=[]
        thetalist=[]
        for i in range(n):
            ulist.append(float(input('Enter velocity: ')))
            thetalist.append(float(input('Enter angle: ')))
    except ValueError:
        print('invalid input')
    else:
        generateFr(?????)

def generateFr(u, theta):
    theta=math.radians(theta)
    g=9.8

    tflight=2*u*math.sin(theta)/g
    intervals=frange(0, tflight, 0.001)

    x=[]
    y=[]
    for t in intervals:
        x.append(u*math.cos(theta)*t)
        y.append(u*math.sin(theta)*t - 0.5*g*t*t)
    drawgraph(x, y)

def frange(start, final, increment):
    numbers=[]
    while start<final:
        numbers.append(start)
        start+=increment
    return numbers

def drawgraph(x, y):
    plt.plot(x, y)
    plt.xlabel('x-coordinate')
    plt.ylabel('y-coordinate')
    plt.title('Projectile motion')

From xupeng.psu at gmail.com  Wed Dec 30 01:04:00 2015
From: xupeng.psu at gmail.com (Tom Xu)
Date: Wed, 30 Dec 2015 01:04:00 -0500
Subject: [Tutor] How to plot amount of lines but the amount is a input
In-Reply-To: <CAOsEKozDz+8O9Z1s1LEYd5W_C3aTZtNsEfnb-6uxA8+RKaKjeQ@mail.gmail.com>
References: <CAOsEKozDz+8O9Z1s1LEYd5W_C3aTZtNsEfnb-6uxA8+RKaKjeQ@mail.gmail.com>
Message-ID: <CAOsEKoxUnLD4T-7nGFVcRxMFv52Z6_hnjmcsb_1vkoM3jHk6kQ@mail.gmail.com>

Dear Pythoneers,

sorry for bothering. I want to draw several curves in one graph, but the
amount of curves is not a fixed number.
My homework is below:
-------------------------------------------------------------------
import matplotlib.pyplot as plt
import math

if __name__=='__main__':
    try:
        n=int(input('how many curves? '))
        ulist=[]
        thetalist=[]
        for i in range(n):
            ulist.append(float(input('Enter velocity: ')))
            thetalist.append(float(input('Enter angle: ')))
    except ValueError:
        print('invalid input')
    else:
*        generateFr(?????) # here I want to draw several curves with
ulist[0], thetalist[0], ulist[1], thetalist[1]... ... ulist[n-1],
thetalist[n-1]*

def generateFr(u, theta):
    theta=math.radians(theta)
    g=9.8

    tflight=2*u*math.sin(theta)/g
    intervals=frange(0, tflight, 0.001)

    x=[]
    y=[]
    for t in intervals:
        x.append(u*math.cos(theta)*t)
        y.append(u*math.sin(theta)*t - 0.5*g*t*t)
    drawgraph(x, y)

def frange(start, final, increment):
    numbers=[]
    while start<final:
        numbers.append(start)
        start+=increment
    return numbers

def drawgraph(x, y):
    plt.plot(x, y)
    plt.xlabel('x-coordinate')
    plt.ylabel('y-coordinate')
    plt.title('Projectile motion')
------------------------------------------------------------------------------

Thank you very much. I hope I describe my question clearly.

Tom

From alan.gauld at btinternet.com  Wed Dec 30 05:15:12 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 30 Dec 2015 10:15:12 +0000
Subject: [Tutor] MemoryError
In-Reply-To: <CAAMZLuw3oi9Pif_uOfSd=EAu_aKcZgwp28qg0T2D1t6EdV6_vw@mail.gmail.com>
References: <CAAMZLuxyOHYWP6oYo6KRBqAVAK_3RpWtPbSBpv=CO=idU_w_Uw@mail.gmail.com>
 <alpine.LSU.2.11.1512291805040.20208@qnttre.jbaqresebt.arg>
 <CAAMZLuw3oi9Pif_uOfSd=EAu_aKcZgwp28qg0T2D1t6EdV6_vw@mail.gmail.com>
Message-ID: <n60arg$t9t$1@ger.gmane.org>

On 30/12/15 06:26, Satya Luzy wrote:
> Dear everyone, thank you for all of your support.
> To Alan :
> It is true that my code still need some improvement on the efficiency part,
> and thanks for pointing out which part that needs to be improved. 

My suggestions won't really do much for efficiency. They will
improve readability though. And that in turn makes it easier
to test/debug your code.

> By the way, did a little bit of searching, does my 64-bit Operating System
> has less performance because it is used for a 32-bit activity?

It may affect the amount of memory available.
Why not use 64 bit Python?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From marcus.luetolf at bluewin.ch  Wed Dec 30 06:00:07 2015
From: marcus.luetolf at bluewin.ch (=?utf-8?Q?marcus_l=C3=BCtolf?=)
Date: Wed, 30 Dec 2015 12:00:07 +0100
Subject: [Tutor] trouble with beautiful soup
In-Reply-To: <n5s274$829$1@ger.gmane.org>
References: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>
 <CAKs9Esvkndvp1Qmi5oTaF=rAB2CDXrCe68L28=8LPPed+mNvsg@mail.gmail.com>
 <013601d13f10$6636d070$32a47150$@bluewin.ch>
 <CANLXbfAcjTqqHHwa3q7yHGrvVs2FZMLUcmmqVb3zGVAo=GyooQ@mail.gmail.com>
 <CANLXbfDKXgHzK_DjGA0e_mHG9raFPn8vYvj05sGZjxKZG78jYQ@mail.gmail.com>
 <0cf801d13fcf$e48d7130$ada85390$@bluewin.ch>
 <CAGZAPF7eR28MPLNThYB67mccMNYg_R3zbPTeCWGDPUAurEtQoQ@mail.gmail.com>
 <0d5701d14194$a821fce0$f865f6a0$@bluewin.ch> <n5s274$829$1@ger.gmane.org>
Message-ID: <342be01d142f1$41c3d640$c54b82c0$@bluewin.ch>

Dear Pythonistas,
o.K., thats what I get from the command line:

Microsoft Windows [Version 10.0.10586]
(c) 2015 Microsoft Corporation. Alle Rechte vorbehalten.

C:\Users\marcus>c:\Python27\Scripts>dir pip*
Der Befehl "c:\Python27\Scripts" ist entweder falsch geschrieben oder
konnte nicht gefunden werden.

C:\Users\marcus>

As mentioned earlier, the error message is in german and says: The command "c:\Python27\Scripts" is either mistyped or could not be found.
With the cd command I get:

Microsoft Windows [Version 10.0.10586]
(c) 2015 Microsoft Corporation. Alle Rechte vorbehalten.

C:\Users\marcus>cd c:\Python27\Scripts> dir pip*
Die Syntax f?r den Dateinamen, Verzeichnisnamen oder die Datentr?gerbezeichnung ist falsch.

C:\Users\marcus>

The error message is also in german and says: The syntax for the filename, directory name or  drive name is wrong.
But if I use 2 steps I get:

C:\Users\marcus>cd c:\Python27\Scripts

c:\Python27\Scripts>dir pip*
 Datentr?ger in Laufwerk C: ist OS
 Volumeseriennummer: 4EE4-17CA

 Verzeichnis von c:\Python27\Scripts

25.12.2015  11:57            98.124 pip.exe
25.12.2015  11:57            98.124 pip2.7.exe
25.12.2015  11:57            98.124 pip2.exe
               3 Datei(en),        294.372 Bytes
               0 Verzeichnis(se), 411.226.550.272 Bytes frei

c:\Python27\Scripts>

How do I proceed from here ?
Thanks an regards, Marcus.

.........................................................................................................................................................................................................................................................................
-----Urspr?ngliche Nachricht-----
Von: Tutor [mailto:tutor-bounces+marcus.luetolf=bluewin.ch at python.org] Im Auftrag von Mark Lawrence
Gesendet: Montag, 28. Dezember 2015 20:23
An: tutor at python.org
Betreff: Re: [Tutor] trouble with beautiful soup

On 28/12/2015 17:24, marcus l?tolf wrote:
> Dear Pythonistas
> Hi Danny,
>
> I am grateful for your precise instruchtions.
> Yes ideed, I tried all of the steps mentioned below which I shoudn't have done fumling around with this task now  for hours and days.
> I even tried to do it on may laptop using W7 64bit and after deleting and reinstalling Python27.
> The youtube video  I was referring to was : https://www.youtube.com/watch?v=0snOcBQ3I0g.
>
> Now for pip: I found pip in C:\Python27\Lib\site-packages. But if I type in pip or pip.exe I get (in german): The command "pip" is  either typed wrong or could not be found (I can't cut and paste from the command window).
> As you might have noticed English is not my natural language and this can lead sometimes to interpretation errors.
>
> Regards, Marcus.

c:\Python27\Scripts>dir pip*
  Volume in drive C has no label.
  Volume Serial Number is AE77-B408

  Directory of c:\Python27\Scripts

20/09/2015  20:22            98,124 pip.exe
20/09/2015  20:22            98,124 pip2.7.exe
20/09/2015  20:22            98,124 pip2.exe
                3 File(s)        294,372 bytes
                0 Dir(s)  869,655,580,672 bytes free

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

Mark Lawrence



_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


---
Diese E-Mail wurde von Avast Antivirus-Software auf Viren gepr?ft.
https://www.avast.com/antivirus


From alan.gauld at btinternet.com  Wed Dec 30 06:26:45 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 30 Dec 2015 11:26:45 +0000
Subject: [Tutor] trouble with beautiful soup
In-Reply-To: <342be01d142f1$41c3d640$c54b82c0$@bluewin.ch>
References: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>
 <CAKs9Esvkndvp1Qmi5oTaF=rAB2CDXrCe68L28=8LPPed+mNvsg@mail.gmail.com>
 <013601d13f10$6636d070$32a47150$@bluewin.ch>
 <CANLXbfAcjTqqHHwa3q7yHGrvVs2FZMLUcmmqVb3zGVAo=GyooQ@mail.gmail.com>
 <CANLXbfDKXgHzK_DjGA0e_mHG9raFPn8vYvj05sGZjxKZG78jYQ@mail.gmail.com>
 <0cf801d13fcf$e48d7130$ada85390$@bluewin.ch>
 <CAGZAPF7eR28MPLNThYB67mccMNYg_R3zbPTeCWGDPUAurEtQoQ@mail.gmail.com>
 <0d5701d14194$a821fce0$f865f6a0$@bluewin.ch> <n5s274$829$1@ger.gmane.org>
 <342be01d142f1$41c3d640$c54b82c0$@bluewin.ch>
Message-ID: <n60f1k$tl1$1@ger.gmane.org>

On 30/12/15 11:00, marcus l?tolf wrote:
> Dear Pythonistas,
> o.K., thats what I get from the command line:
> 
> Microsoft Windows [Version 10.0.10586]
> (c) 2015 Microsoft Corporation. Alle Rechte vorbehalten.
> 
> C:\Users\marcus>c:\Python27\Scripts>dir pip*

OK, Thanks for the cut 'n paste that solves the mystery.

When you see

C:\some\path> somecommand

The bit up to the > is the OS prompt and you should NOT type that.
But it may tell you which folder you need to be in before you
do type it.

So, having seen the instruction above you would actually type

cd C:\some\path
somecommand

In your specific case you should type

cd C:\Python27\Scripts
dir pip*

Now try again and see if it works.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at btinternet.com  Wed Dec 30 06:35:19 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 30 Dec 2015 11:35:19 +0000
Subject: [Tutor] How to plot amount of lines but the amount is a input
In-Reply-To: <CAOsEKozDz+8O9Z1s1LEYd5W_C3aTZtNsEfnb-6uxA8+RKaKjeQ@mail.gmail.com>
References: <CAOsEKozDz+8O9Z1s1LEYd5W_C3aTZtNsEfnb-6uxA8+RKaKjeQ@mail.gmail.com>
Message-ID: <n60fhn$5bt$1@ger.gmane.org>

On 30/12/15 05:55, Tom Xu wrote:
> Dear Pythoneers,
> 
> I want to draw several curves in one graph, but the amount of curves is not
> a fixed number.

OK, But what exactly are you asking us to do?

> My homework is below:
> ---
> import matplotlib.pyplot as plt
> import math
> 
> if __name__=='__main__':
>     try:
>         n=int(input('how many curves? '))
>         ulist=[]
>         thetalist=[]
>         for i in range(n):
>             ulist.append(float(input('Enter velocity: ')))
>             thetalist.append(float(input('Enter angle: ')))
>     except ValueError:
>         print('invalid input')
>     else:
>         generateFr(?????)

You need to put the call to generateFr inside a loop that
iterates n times putting successive values from ulist and
thetalist into the function.


> def generateFr(u, theta):
>     theta=math.radians(theta)
>     g=9.8
> 
>     tflight=2*u*math.sin(theta)/g
>     intervals=frange(0, tflight, 0.001)
>     x=[]
>     y=[]
>     for t in intervals:
>         x.append(u*math.cos(theta)*t)
>         y.append(u*math.sin(theta)*t - 0.5*g*t*t)
>     drawgraph(x, y)
> 
> def frange(start, final, increment):
>     numbers=[]
>     while start<final:
>         numbers.append(start)
>         start+=increment
>     return numbers
> 
> def drawgraph(x, y):
>     plt.plot(x, y)
>     plt.xlabel('x-coordinate')
>     plt.ylabel('y-coordinate')
>     plt.title('Projectile motion')



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From joel.goldstick at gmail.com  Wed Dec 30 10:52:03 2015
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Wed, 30 Dec 2015 10:52:03 -0500
Subject: [Tutor] How to plot amount of lines but the amount is a input
In-Reply-To: <n60fhn$5bt$1@ger.gmane.org>
References: <CAOsEKozDz+8O9Z1s1LEYd5W_C3aTZtNsEfnb-6uxA8+RKaKjeQ@mail.gmail.com>
 <n60fhn$5bt$1@ger.gmane.org>
Message-ID: <CAPM-O+yLFYuk_fF6SWwfJ6oEJKUeAtuXPe6NxpqBrjMyB6+Duw@mail.gmail.com>

On Wed, Dec 30, 2015 at 6:35 AM, Alan Gauld <alan.gauld at btinternet.com>
wrote:

> On 30/12/15 05:55, Tom Xu wrote:
> > Dear Pythoneers,
> >
> > I want to draw several curves in one graph, but the amount of curves is
> not
> > a fixed number.
>
> OK, But what exactly are you asking us to do?
>
> > My homework is below:
> > ---
> > import matplotlib.pyplot as plt
> > import math
> >
> > if __name__=='__main__':
> >     try:
> >         n=int(input('how many curves? '))
> >         ulist=[]
> >         thetalist=[]
> >         for i in range(n):
> >             ulist.append(float(input('Enter velocity: ')))
> >             thetalist.append(float(input('Enter angle: ')))
> >     except ValueError:
> >         print('invalid input')
> >     else:
> >         generateFr(?????)
>
> You need to put the call to generateFr inside a loop that
> iterates n times putting successive values from ulist and
> thetalist into the function.
>
> Also, put the function definitions above the place where you call them.
Normally, the if __name__ stuff should be below your function definitions

>
> > def generateFr(u, theta):
> >     theta=math.radians(theta)
> >     g=9.8
> >
> >     tflight=2*u*math.sin(theta)/g
> >     intervals=frange(0, tflight, 0.001)
> >     x=[]
> >     y=[]
> >     for t in intervals:
> >         x.append(u*math.cos(theta)*t)
> >         y.append(u*math.sin(theta)*t - 0.5*g*t*t)
> >     drawgraph(x, y)
> >
> > def frange(start, final, increment):
> >     numbers=[]
> >     while start<final:
> >         numbers.append(start)
> >         start+=increment
> >     return numbers
> >
> > def drawgraph(x, y):
> >     plt.plot(x, y)
> >     plt.xlabel('x-coordinate')
> >     plt.ylabel('y-coordinate')
> >     plt.title('Projectile motion')
>
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
http://joelgoldstick.com/stats/birthdays

From marcus.luetolf at bluewin.ch  Thu Dec 31 08:19:41 2015
From: marcus.luetolf at bluewin.ch (=?utf-8?Q?marcus_l=C3=BCtolf?=)
Date: Thu, 31 Dec 2015 14:19:41 +0100
Subject: [Tutor] trouble with beautiful soup
In-Reply-To: <n5s274$829$1@ger.gmane.org>
References: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>
 <CAKs9Esvkndvp1Qmi5oTaF=rAB2CDXrCe68L28=8LPPed+mNvsg@mail.gmail.com>
 <013601d13f10$6636d070$32a47150$@bluewin.ch>
 <CANLXbfAcjTqqHHwa3q7yHGrvVs2FZMLUcmmqVb3zGVAo=GyooQ@mail.gmail.com>
 <CANLXbfDKXgHzK_DjGA0e_mHG9raFPn8vYvj05sGZjxKZG78jYQ@mail.gmail.com>
 <0cf801d13fcf$e48d7130$ada85390$@bluewin.ch>
 <CAGZAPF7eR28MPLNThYB67mccMNYg_R3zbPTeCWGDPUAurEtQoQ@mail.gmail.com>
 <0d5701d14194$a821fce0$f865f6a0$@bluewin.ch> <n5s274$829$1@ger.gmane.org>
Message-ID: <36d601d143cd$eb23e590$c16bb0b0$@bluewin.ch>

Dear Pythonistas,
finally I could install BeautifulSoup on my laptop. Please forget my most recent mail below.
But if I try the same procedure on my pc i get this and I have no idea why  this code I used for exercises gets into this command even after havin deleted all
Ma saved exercise codes referring to parsing the web:

Microsoft Windows [Version 10.0.10586]
(c) 2015 Microsoft Corporation. Alle Rechte vorbehalten.

C:\Users\marcus>cd c:\Python27\Scripts

c:\Python27\Scripts>pip install beutifulsoup
<h1>The First Page</h1>
<p>
If you like, you can switch to the
<a href="http://www.dr-chuck.com/page2.htm">
Second Page</a>.
</p>
Traceback (most recent call last):
  File "c:\python27\lib\runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "c:\python27\lib\runpy.py", line 72, in _run_code
    exec code in run_globals
  File "c:\Python27\Scripts\pip.exe\__main__.py", line 5, in <module>
  File "c:\python27\lib\site-packages\pip\__init__.py", line 15, in <module>
    from pip.vcs import git, mercurial, subversion, bazaar  # noqa
  File "c:\python27\lib\site-packages\pip\vcs\mercurial.py", line 10, in <module>
    from pip.download import path_to_url
  File "c:\python27\lib\site-packages\pip\download.py", line 38, in <module>
    from pip._vendor import requests, six
  File "c:\python27\lib\site-packages\pip\_vendor\requests\__init__.py", line 58, in <module>
    from . import utils
  File "c:\python27\lib\site-packages\pip\_vendor\requests\utils.py", line 26, in <module>
    from .compat import parse_http_list as _parse_list_header
  File "c:\python27\lib\site-packages\pip\_vendor\requests\compat.py", line 38, in <module>
    from urllib2 import parse_http_list
ImportError: cannot import name parse_http_list

c:\Python27\Scripts>









Dear Pythonistas,
o.K., thats what I get from the command line:

Microsoft Windows [Version 10.0.10586]
(c) 2015 Microsoft Corporation. Alle Rechte vorbehalten.

C:\Users\marcus>c:\Python27\Scripts>dir pip*
Der Befehl "c:\Python27\Scripts" ist entweder falsch geschrieben oder
konnte nicht gefunden werden.

C:\Users\marcus>

As mentioned earlier, the error message is in german and says: The command "c:\Python27\Scripts" is either mistyped or could not be found.
With the cd command I get:

Microsoft Windows [Version 10.0.10586]
(c) 2015 Microsoft Corporation. Alle Rechte vorbehalten.

C:\Users\marcus>cd c:\Python27\Scripts> dir pip*
Die Syntax f?r den Dateinamen, Verzeichnisnamen oder die Datentr?gerbezeichnung ist falsch.

C:\Users\marcus>

The error message is also in german and says: The syntax for the filename, directory name or  drive name is wrong.
But if I use 2 steps I get:

C:\Users\marcus>cd c:\Python27\Scripts

c:\Python27\Scripts>dir pip*
 Datentr?ger in Laufwerk C: ist OS
 Volumeseriennummer: 4EE4-17CA

 Verzeichnis von c:\Python27\Scripts

25.12.2015  11:57            98.124 pip.exe
25.12.2015  11:57            98.124 pip2.7.exe
25.12.2015  11:57            98.124 pip2.exe
               3 Datei(en),        294.372 Bytes
               0 Verzeichnis(se), 411.226.550.272 Bytes frei

c:\Python27\Scripts>

How do I proceed from here ?
Thanks an regards, Marcus.

.........................................................................................................................................................................................................................................................................
-----Urspr?ngliche Nachricht-----
Von: Tutor [mailto:tutor-bounces+marcus.luetolf=bluewin.ch at python.org] Im Auftrag von Mark Lawrence
Gesendet: Montag, 28. Dezember 2015 20:23
An: tutor at python.org
Betreff: Re: [Tutor] trouble with beautiful soup

On 28/12/2015 17:24, marcus l?tolf wrote:
> Dear Pythonistas
> Hi Danny,
>
> I am grateful for your precise instruchtions.
> Yes ideed, I tried all of the steps mentioned below which I shoudn't have done fumling around with this task now  for hours and days.
> I even tried to do it on may laptop using W7 64bit and after deleting and reinstalling Python27.
> The youtube video  I was referring to was : https://www.youtube.com/watch?v=0snOcBQ3I0g.
>
> Now for pip: I found pip in C:\Python27\Lib\site-packages. But if I type in pip or pip.exe I get (in german): The command "pip" is  either typed wrong or could not be found (I can't cut and paste from the command window).
> As you might have noticed English is not my natural language and this can lead sometimes to interpretation errors.
>
> Regards, Marcus.

c:\Python27\Scripts>dir pip*
  Volume in drive C has no label.
  Volume Serial Number is AE77-B408

  Directory of c:\Python27\Scripts

20/09/2015  20:22            98,124 pip.exe
20/09/2015  20:22            98,124 pip2.7.exe
20/09/2015  20:22            98,124 pip2.exe
                3 File(s)        294,372 bytes
                0 Dir(s)  869,655,580,672 bytes free

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

Mark Lawrence



_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


---
Diese E-Mail wurde von Avast Antivirus-Software auf Viren gepr?ft.
https://www.avast.com/antivirus


From breamoreboy at yahoo.co.uk  Thu Dec 31 10:52:45 2015
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Thu, 31 Dec 2015 15:52:45 +0000
Subject: [Tutor] trouble with beautiful soup
In-Reply-To: <36d601d143cd$eb23e590$c16bb0b0$@bluewin.ch>
References: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>
 <CAKs9Esvkndvp1Qmi5oTaF=rAB2CDXrCe68L28=8LPPed+mNvsg@mail.gmail.com>
 <013601d13f10$6636d070$32a47150$@bluewin.ch>
 <CANLXbfAcjTqqHHwa3q7yHGrvVs2FZMLUcmmqVb3zGVAo=GyooQ@mail.gmail.com>
 <CANLXbfDKXgHzK_DjGA0e_mHG9raFPn8vYvj05sGZjxKZG78jYQ@mail.gmail.com>
 <0cf801d13fcf$e48d7130$ada85390$@bluewin.ch>
 <CAGZAPF7eR28MPLNThYB67mccMNYg_R3zbPTeCWGDPUAurEtQoQ@mail.gmail.com>
 <0d5701d14194$a821fce0$f865f6a0$@bluewin.ch> <n5s274$829$1@ger.gmane.org>
 <36d601d143cd$eb23e590$c16bb0b0$@bluewin.ch>
Message-ID: <n63j10$pfa$1@ger.gmane.org>

Please don't top post, it makes following threads extremely difficult.


On 31/12/2015 13:19, marcus l?tolf wrote:
> Dear Pythonistas,
> finally I could install BeautifulSoup on my laptop. Please forget my most recent mail below.
> But if I try the same procedure on my pc i get this and I have no idea why  this code I used for exercises gets into this command even after havin deleted all
> Ma saved exercise codes referring to parsing the web:
>
> Microsoft Windows [Version 10.0.10586]
> (c) 2015 Microsoft Corporation. Alle Rechte vorbehalten.
>
> C:\Users\marcus>cd c:\Python27\Scripts
>
> c:\Python27\Scripts>pip install beutifulsoup

Whoops.

> Traceback (most recent call last):
>    File "c:\python27\lib\runpy.py", line 162, in _run_module_as_main
>      "__main__", fname, loader, pkg_name)
>    File "c:\python27\lib\runpy.py", line 72, in _run_code
>      exec code in run_globals
>    File "c:\Python27\Scripts\pip.exe\__main__.py", line 5, in <module>
>    File "c:\python27\lib\site-packages\pip\__init__.py", line 15, in <module>
>      from pip.vcs import git, mercurial, subversion, bazaar  # noqa
>    File "c:\python27\lib\site-packages\pip\vcs\mercurial.py", line 10, in <module>
>      from pip.download import path_to_url
>    File "c:\python27\lib\site-packages\pip\download.py", line 38, in <module>
>      from pip._vendor import requests, six
>    File "c:\python27\lib\site-packages\pip\_vendor\requests\__init__.py", line 58, in <module>
>      from . import utils
>    File "c:\python27\lib\site-packages\pip\_vendor\requests\utils.py", line 26, in <module>
>      from .compat import parse_http_list as _parse_list_header
>    File "c:\python27\lib\site-packages\pip\_vendor\requests\compat.py", line 38, in <module>
>      from urllib2 import parse_http_list
> ImportError: cannot import name parse_http_list
>
> c:\Python27\Scripts>
>

I get:-

c:\Python27\Scripts>pip install beutifulsoup
Collecting beutifulsoup
   Could not find a version that satisfies the requirement beutifulsoup 
(from versions: )
No matching distribution found for beutifulsoup

I'd guess that the answer from this 
http://stackoverflow.com/questions/17391289/tried-to-use-relative-imports-and-broke-my-import-paths 
applies.

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

Mark Lawrence


From alan.gauld at btinternet.com  Thu Dec 31 12:54:17 2015
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 31 Dec 2015 17:54:17 +0000
Subject: [Tutor] trouble with beautiful soup
In-Reply-To: <36d601d143cd$eb23e590$c16bb0b0$@bluewin.ch>
References: <270401d13e6f$8e92c390$abb84ab0$@bluewin.ch>
 <CAKs9Esvkndvp1Qmi5oTaF=rAB2CDXrCe68L28=8LPPed+mNvsg@mail.gmail.com>
 <013601d13f10$6636d070$32a47150$@bluewin.ch>
 <CANLXbfAcjTqqHHwa3q7yHGrvVs2FZMLUcmmqVb3zGVAo=GyooQ@mail.gmail.com>
 <CANLXbfDKXgHzK_DjGA0e_mHG9raFPn8vYvj05sGZjxKZG78jYQ@mail.gmail.com>
 <0cf801d13fcf$e48d7130$ada85390$@bluewin.ch>
 <CAGZAPF7eR28MPLNThYB67mccMNYg_R3zbPTeCWGDPUAurEtQoQ@mail.gmail.com>
 <0d5701d14194$a821fce0$f865f6a0$@bluewin.ch> <n5s274$829$1@ger.gmane.org>
 <36d601d143cd$eb23e590$c16bb0b0$@bluewin.ch>
Message-ID: <n63q49$3ru$1@ger.gmane.org>

On 31/12/15 13:19, marcus l?tolf wrote:

> c:\Python27\Scripts>pip install beutifulsoup

Is that really how you spell it?
Although I'd expect a different error if it isn't....

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos