From palani at vahaitech.com  Sat Jul  2 01:04:27 2016
From: palani at vahaitech.com (Palanikumar Gopalakrishnan)
Date: Sat, 2 Jul 2016 10:34:27 +0530
Subject: [Tutor] Help:python based framework show error
Message-ID: <CAN4mP=q1Rnwwq6xQNs11X6SXOtG=HvKjkdWSKht7eUT2zvP7dA@mail.gmail.com>

Hi dudes,
                I run the python based framework routersploit , it shows
the following error.

Traceback (most recent call last):
File "./rsf.py", line 11, in <module>
    routersploit()
File "./rsf.py", line 7, in routersploit
rsf = RoutersploitInterpreter()
File "/home/tester/routersploit/routersploit/interpreter.py", line
155, in __init__
super(RoutersploitInterpreter, self).__init__()
File "/home/tester/routersploit/routersploit/interpreter.py", line 25,
in __init__
self.setup()
File "/home/tester/routersploit/routersploit/interpreter.py", line 39, in setup
readline.read_history_file(self.history_file)
IOError: [Errno 13] Permission denied



Thanks in Advance

From steve at pearwood.info  Sat Jul  2 04:03:09 2016
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 2 Jul 2016 18:03:09 +1000
Subject: [Tutor] Help:python based framework show error
In-Reply-To: <CAN4mP=q1Rnwwq6xQNs11X6SXOtG=HvKjkdWSKht7eUT2zvP7dA@mail.gmail.com>
References: <CAN4mP=q1Rnwwq6xQNs11X6SXOtG=HvKjkdWSKht7eUT2zvP7dA@mail.gmail.com>
Message-ID: <20160702080308.GN27919@ando.pearwood.info>

On Sat, Jul 02, 2016 at 10:34:27AM +0530, Palanikumar Gopalakrishnan wrote:
> Hi dudes,
>                 I run the python based framework routersploit , it shows
> the following error.

Thanks for sharing. Do you have a question?


> Traceback (most recent call last):
[...]
> File "/home/tester/routersploit/routersploit/interpreter.py", line 39, in setup
> readline.read_history_file(self.history_file)
> IOError: [Errno 13] Permission denied

Have you read the error message? It seems pretty obvious to me: you 
don't have permission to read the history file. That's not a Python 
problem, it's a permissions problem:

- check that you're reading the right file;
- check that you're in the right directory;
- check that you're running the code as the right user;
- check that permissions on the file are right.

Do you know how to do these things?



-- 
Steve

From min786a at googlemail.com  Sat Jul  2 06:46:07 2016
From: min786a at googlemail.com (Minhaj Ahmed)
Date: Sat, 2 Jul 2016 11:46:07 +0100
Subject: [Tutor] dont understand part of a code
Message-ID: <CANeHpPKZ-d2HukHO-pCi-XQS7jyaMsSQAp7GpQE-z5WMpnVctw@mail.gmail.com>

Hi, below is code for a hangman game which I copied from a book I am
studying,Python programming for the absolute beginners by Michael Dawson. I
have underlined the part of code I do not understand and why it is there.

import random

HANGMAN = (
    """
    ------|
    |
    |
    |
    |
    -----
    """,
    """

     ------|
    |      0
    |
    |
    |
    -----
    """,
    """
     ------|
    |      0
    |     -+-
    |
    |
    -----
    """,
    """
    ------|
    |     0
    |    -+-
    |
    |
    -----
    """,
    """
    ------|
    |     0
    |   /-+-
    |
    |
    -----
    """,
    """
    ------|
    |     0
    |   /-+-\
    |
    |
    -----
    """,
    """
    ------|
    |     0
    |   /-+-\
    |     |
    |
    -----
    """,
    """
    ------|
    |     0
    |   /-+-\
    |     |
    |    |
    -----
    """,
    """
    ------|
    |     0
    |   /-+-\
    |     |
    |    |
    -----
    """,
    """
    ------|
    |     0
    |   /-+-\
    |     |
    |    | |
    -----
    """)

MAX_WRONG = len(HANGMAN )-1
WORDS = ("PYTHON","RUBY","VISUAL BASIC","PHP","JAVA","UNIX","LINUX","PERL")
word = random.choice(WORDS)
so_far = "-" * len(word)
wrong = 0
used = []
print("Welcome to hangman.Good luck!")

while wrong < MAX_WRONG and so_far != word:
    print(HANGMAN[wrong])
    print("\nYou've used the following letterss:\n",used)
    print("\nSo far,the word is:\n", so_far)
    guess = input("\nEnter your guess: ")
    guess = guess.upper()

    while guess in used:
        print("You've already guessed the letter",guess)
        guess = input("Enter your guess: ")
        guess = guess.upper()

    used.append(guess)

    if guess in word:
        print("\nYes",guess,"is in the word!")

        new = ""
        for i in range(len(word)):
            if guess == word[i]:
                new += guess
          *  else:*
*                new += so_far[i]  # why is there a else code here?*
        so_far = new
    else:
        print("\nSorry",guess,"isnt in the word")
        wrong += 1
if wrong == MAX_WRONG:
    print(HANGMAN[wrog])
    print("\nYou have been hanged!!")
else:
    print("\nYou have guessed correct")

print("\nThe word was", word)

input("\nPress enter to exit")

From alan.gauld at yahoo.co.uk  Sat Jul  2 08:28:31 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 2 Jul 2016 13:28:31 +0100
Subject: [Tutor] dont understand part of a code
In-Reply-To: <CANeHpPKZ-d2HukHO-pCi-XQS7jyaMsSQAp7GpQE-z5WMpnVctw@mail.gmail.com>
References: <CANeHpPKZ-d2HukHO-pCi-XQS7jyaMsSQAp7GpQE-z5WMpnVctw@mail.gmail.com>
Message-ID: <nl8c1e$fmi$1@ger.gmane.org>

On 02/07/16 11:46, Minhaj Ahmed via Tutor wrote:

> have underlined the part of code I do not understand and why it is there.

The mailing list is plain text so formatting like underline
doesn't show up. Fortunately you added a comment too...

> so_far = "-" * len(word)

so_far is whats printed as the result so far.

> used = []

used is the letters input so far

> while wrong < MAX_WRONG and so_far != word:
>     print(HANGMAN[wrong])
>     print("\nYou've used the following letterss:\n",used)
>     print("\nSo far,the word is:\n", so_far)
>     guess = input("\nEnter your guess: ")
>     guess = guess.upper()
> 
>     while guess in used:
>         print("You've already guessed the letter",guess)
...

>     if guess in word:
>         print("\nYes",guess,"is in the word!")
> 
>         new = ""
>         for i in range(len(word)):
>             if guess == word[i]:
>                 new += guess
>           *  else:*
> *                new += so_far[i]  # why is there a else code here?*

The else part is needed so that when the guess is noyt at the given
position the current value of so_far is put into new.

Lets assume the word is python
lets assume sop_far contains

____o_

And you guess y

On the first letter new should equal _

So because y is not the first letter the if clause is false
so the else is selected and new[0] becomes so_far[0], ie '_'
new = '_'

Now on the next index i = 1
guess == word[1] is true
so the if part executes setting new[1] to guess (ie to 'y')
new now equals '_y'

Now on the next index i = 2
guess == word[2] is false so the el;se gets selected
setting new[2] to so_far[2] = '_'
new now equals '_y_'

and so on.

new[i] either acquires the value of guess or so_far[i]
(remember that guess may appear more than once...)

>         so_far = new

Finally so_far is replaced with the final value of new.

There are arguably easier ways of doing this using lists
of characters rather than strings but this 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 robertvstepp at gmail.com  Sun Jul  3 01:07:40 2016
From: robertvstepp at gmail.com (boB Stepp)
Date: Sun, 3 Jul 2016 00:07:40 -0500
Subject: [Tutor] OT: Recommendations for a Linux distribution to
 dual-boot with Win7-64 bit
In-Reply-To: <20160630041249.GK27919@ando.pearwood.info>
References: <CANDiX9+74i2_SzMuW4yqU1-DRnC7AY=CcHRkcE6QgHVAiu_nBQ@mail.gmail.com>
 <D29CAC21-30F2-4A47-8D0C-725ACFD19B38@graniteweb.com>
 <CANDiX9++cFA0Ui-LJESRORnU+PafPdeVLCm52ufYLTD1UVtNWQ@mail.gmail.com>
 <1A2C40AD-4A44-4B85-8C10-5EA271DA1D5D@graniteweb.com>
 <CANDiX9+u87oHB4UN2YJGM4Le3nxKLLiLGNBDO8WBywUViLEHOg@mail.gmail.com>
 <CANDiX9Jy6-ee_YFfaH-Tar+T4d+GmtcFD6rqPt0nZ0=sT_8bGw@mail.gmail.com>
 <40898999-E4E4-49F1-8CCC-4D1466A34D35@graniteweb.com>
 <CANDiX9L0=F91DT_6ED6qB9pF-ruM+BLzR11CkO3gYEwKTjDWJw@mail.gmail.com>
 <nl1nvd$8o0$1@ger.gmane.org>
 <CANDiX9KYeBwRjKLpyEza9uJGPQauN-r37xvznnxspQzt9wT4nQ@mail.gmail.com>
 <20160630041249.GK27919@ando.pearwood.info>
Message-ID: <57789D9C.4010706@gmail.com>

This is an update and a test to see if I have figured out Thunderbird's 
settings so that everything comes over as plain text instead of 
something else.  If there are any issues let me know.

Friday the Mint crew announced that they were releasing their new 
version of Mint, version 18, Sarah, so I went _bleeding edge_ and tried 
to install it.  Things did not go well in the sense that I was not able 
to make a dual-boot installation where Windows 7 was on its existing 
hard drive and Mint 18 on its own.  As far as I can tell I did 
everything correctly, but upon rebooting there was no option to go to 
Mint; instead, the boot went directly to Windows 7.  After many hours of 
effort, searching, etc. (It was after 6 AM local time when I gave up.) I 
decided to simply unplug the Windows 7 hard drive and plug my new hard 
drive in its place.  I successfully installed Mint 18 and it booted up 
fine with one quirk.  My understanding is that I would be prompted to 
remove my installation USB drive prior to it rebooting, but it didn't 
and this seemed to cause issues.  On my repeat installation effort I 
removed the USB drive myself when it appeared that the system had just 
shut down.  Things have gone well since.

I guess I will save the dual-boot effort for some other day.

Now I am updating things, playing with Firefox and Thunderbird, etc.  On 
the latter I was surprised that Thunderbird did not support conversation 
views out of the box.  I am currently testing an extension, "Thunderbird 
Conversations", which is a bit different in what I was expecting 
(Compared to Gmail.), but I suppose I will get used to it.

We will see how the Linux experiment will work!  My plan is to work my 
way through the book, "How Linux Works", by Brian Ward.  So that will 
probably distract me from Python studies for a while.

Again, thanks for all of the help you've collectively given!

boB

From info at riesrommens.nl  Sun Jul  3 15:32:35 2016
From: info at riesrommens.nl (Ries Rommens)
Date: Sun, 3 Jul 2016 21:32:35 +0200
Subject: [Tutor] OT: Recommendations for a Linux distribution to
 dual-boot with Win7-64 bit
In-Reply-To: <57789D9C.4010706@gmail.com>
References: <CANDiX9+74i2_SzMuW4yqU1-DRnC7AY=CcHRkcE6QgHVAiu_nBQ@mail.gmail.com>
 <D29CAC21-30F2-4A47-8D0C-725ACFD19B38@graniteweb.com>
 <CANDiX9++cFA0Ui-LJESRORnU+PafPdeVLCm52ufYLTD1UVtNWQ@mail.gmail.com>
 <1A2C40AD-4A44-4B85-8C10-5EA271DA1D5D@graniteweb.com>
 <CANDiX9+u87oHB4UN2YJGM4Le3nxKLLiLGNBDO8WBywUViLEHOg@mail.gmail.com>
 <CANDiX9Jy6-ee_YFfaH-Tar+T4d+GmtcFD6rqPt0nZ0=sT_8bGw@mail.gmail.com>
 <40898999-E4E4-49F1-8CCC-4D1466A34D35@graniteweb.com>
 <CANDiX9L0=F91DT_6ED6qB9pF-ruM+BLzR11CkO3gYEwKTjDWJw@mail.gmail.com>
 <nl1nvd$8o0$1@ger.gmane.org>
 <CANDiX9KYeBwRjKLpyEza9uJGPQauN-r37xvznnxspQzt9wT4nQ@mail.gmail.com>
 <20160630041249.GK27919@ando.pearwood.info> <57789D9C.4010706@gmail.com>
Message-ID: <7ff0b317-a41c-dd92-2632-35d683be39f7@riesrommens.nl>

Hello boB,

> On the latter I was surprised that Thunderbird did not support 
> conversation views out of the box.
After opening Thunderbird you will see a listing of your emails.
Clicking on the header of the very first column of the listing will give 
you the conversation mode.
(Second column header is a star, third one the attachments. Be aware 
that you can alter the columns shown, so things may be different in your 
case).

Kind regards,

Ries

<https://www.riesrommens.nl>
Op 03-07-16 om 07:07 schreef boB Stepp:
> This is an update and a test to see if I have figured out 
> Thunderbird's settings so that everything comes over as plain text 
> instead of something else.  If there are any issues let me know.
>
> Friday the Mint crew announced that they were releasing their new 
> version of Mint, version 18, Sarah, so I went _bleeding edge_ and 
> tried to install it.  Things did not go well in the sense that I was 
> not able to make a dual-boot installation where Windows 7 was on its 
> existing hard drive and Mint 18 on its own.  As far as I can tell I 
> did everything correctly, but upon rebooting there was no option to go 
> to Mint; instead, the boot went directly to Windows 7.  After many 
> hours of effort, searching, etc. (It was after 6 AM local time when I 
> gave up.) I decided to simply unplug the Windows 7 hard drive and plug 
> my new hard drive in its place. I successfully installed Mint 18 and 
> it booted up fine with one quirk.  My understanding is that I would be 
> prompted to remove my installation USB drive prior to it rebooting, 
> but it didn't and this seemed to cause issues.  On my repeat 
> installation effort I removed the USB drive myself when it appeared 
> that the system had just shut down.  Things have gone well since.
>
> I guess I will save the dual-boot effort for some other day.
>
> Now I am updating things, playing with Firefox and Thunderbird, etc.  
> On the latter I was surprised that Thunderbird did not support 
> conversation views out of the box.  I am currently testing an 
> extension, "Thunderbird Conversations", which is a bit different in 
> what I was expecting (Compared to Gmail.), but I suppose I will get 
> used to it.
>
> We will see how the Linux experiment will work!  My plan is to work my 
> way through the book, "How Linux Works", by Brian Ward. So that will 
> probably distract me from Python studies for a while.
>
> Again, thanks for all of the help you've collectively given!
>
> boB
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor


From robertvstepp at gmail.com  Sun Jul  3 18:29:27 2016
From: robertvstepp at gmail.com (boB Stepp)
Date: Sun, 3 Jul 2016 17:29:27 -0500
Subject: [Tutor] OT: Recommendations for a Linux distribution to
 dual-boot with Win7-64 bit
In-Reply-To: <7ff0b317-a41c-dd92-2632-35d683be39f7@riesrommens.nl>
References: <CANDiX9+74i2_SzMuW4yqU1-DRnC7AY=CcHRkcE6QgHVAiu_nBQ@mail.gmail.com>
 <D29CAC21-30F2-4A47-8D0C-725ACFD19B38@graniteweb.com>
 <CANDiX9++cFA0Ui-LJESRORnU+PafPdeVLCm52ufYLTD1UVtNWQ@mail.gmail.com>
 <1A2C40AD-4A44-4B85-8C10-5EA271DA1D5D@graniteweb.com>
 <CANDiX9+u87oHB4UN2YJGM4Le3nxKLLiLGNBDO8WBywUViLEHOg@mail.gmail.com>
 <CANDiX9Jy6-ee_YFfaH-Tar+T4d+GmtcFD6rqPt0nZ0=sT_8bGw@mail.gmail.com>
 <40898999-E4E4-49F1-8CCC-4D1466A34D35@graniteweb.com>
 <CANDiX9L0=F91DT_6ED6qB9pF-ruM+BLzR11CkO3gYEwKTjDWJw@mail.gmail.com>
 <nl1nvd$8o0$1@ger.gmane.org>
 <CANDiX9KYeBwRjKLpyEza9uJGPQauN-r37xvznnxspQzt9wT4nQ@mail.gmail.com>
 <20160630041249.GK27919@ando.pearwood.info> <57789D9C.4010706@gmail.com>
 <7ff0b317-a41c-dd92-2632-35d683be39f7@riesrommens.nl>
Message-ID: <577991C7.8050907@gmail.com>

On 07/03/2016 02:32 PM, Ries Rommens wrote:
> Hello boB,
>
>> On the latter I was surprised that Thunderbird did not support
>> conversation views out of the box.
> After opening Thunderbird you will see a listing of your emails.
> Clicking on the header of the very first column of the listing will give
> you the conversation mode.
> (Second column header is a star, third one the attachments. Be aware
> that you can alter the columns shown, so things may be different in your
> case).

I had found this -- threaded view -- but it lists the entire thread as a 
collection of separate emails.  What I consider _conversation view_ is 
all of the thread's emails presented in a single window once any of the 
emails is opened.

Alas, I cannot recommend the Thunderbird Conversations extension at this 
time as the way it presents the conversation view is difficult to 
distinguish text, at least in how it interacts with my current Mint 
theme.  So I have actually gone back to what you suggest!

Thanks!
boB

From colbychristensen at hotmail.com  Mon Jul  4 16:38:01 2016
From: colbychristensen at hotmail.com (Colby Christensen)
Date: Mon, 4 Jul 2016 16:38:01 -0400
Subject: [Tutor] iterators
Message-ID: <COL129-W77980FED3F2CF536405A8FD0380@phx.gbl>

I'm sure this is something simple but I'm missing it. 
When I check the statement with two values, the if statement works. However, for the statement with one value I get an error.
keycode = event.GetKeyCode()
if keycode in (13, 370):
    self.enter()
elif keycode in (43, 388):
    self.add()
elif keycode in (45, 390):
    self.sub()
elif keycode in (42, 387):
    self.mult()
elif keycode in (47, 392):
    self.div()
elif keycode in (27):
    self.clear_all()
elif keycode in (67, 99):
    self.display.SetValue('')
else:
    event.Skip()This is the error message.
Traceback (most recent call last):
? File "/home/colby/Calculator/Calculator_betaV3.py", line 110, in OnKeyPress
??? elif keycode in (27):
TypeError: argument of type 'int' is not iterable

I then tried using

elif keycode == 27:

but this statement didn't work. 

I'm pretty sure it's something simple that I've overlooked due to my inexperience.

Thanks in advance.
 		 	   		  

From alan.gauld at yahoo.co.uk  Mon Jul  4 17:36:42 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 4 Jul 2016 22:36:42 +0100
Subject: [Tutor] iterators
In-Reply-To: <COL129-W77980FED3F2CF536405A8FD0380@phx.gbl>
References: <COL129-W77980FED3F2CF536405A8FD0380@phx.gbl>
Message-ID: <nlekt9$gao$1@ger.gmane.org>

On 04/07/16 21:38, Colby Christensen wrote:

>   File "/home/colby/Calculator/Calculator_betaV3.py", line 110, in OnKeyPress
>     elif keycode in (27):
> TypeError: argument of type 'int' is not iterable

The problem is that 'in' needs a collection to test. (27) is not a
single element tuple but just an integer with parens around it. To make
it a tuple you need to add a comma:

elif keycode in (27,):

That should do what you want.

Whether it's what you really need is another story. I didn't read the
rest of the code!

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 robertvstepp at gmail.com  Mon Jul  4 17:57:25 2016
From: robertvstepp at gmail.com (boB Stepp)
Date: Mon, 4 Jul 2016 16:57:25 -0500
Subject: [Tutor] iterators
In-Reply-To: <COL129-W77980FED3F2CF536405A8FD0380@phx.gbl>
References: <COL129-W77980FED3F2CF536405A8FD0380@phx.gbl>
Message-ID: <577ADBC5.4010604@gmail.com>

On 07/04/2016 03:38 PM, Colby Christensen wrote:
> I'm sure this is something simple but I'm missing it.
> When I check the statement with two values, the if statement works. However, for the statement with one value I get an error.
> keycode = event.GetKeyCode()
> if keycode in (13, 370):
>      self.enter()
> elif keycode in (43, 388):
>      self.add()
> elif keycode in (45, 390):
>      self.sub()
> elif keycode in (42, 387):
>      self.mult()
> elif keycode in (47, 392):
>      self.div()
> elif keycode in (27):
>      self.clear_all()
> elif keycode in (67, 99):
>      self.display.SetValue('')
> else:
>      event.Skip()This is the error message.
> Traceback (most recent call last):
>    File "/home/colby/Calculator/Calculator_betaV3.py", line 110, in OnKeyPress
>      elif keycode in (27):
> TypeError: argument of type 'int' is not iterable

I believe that for (27) to be a tuple, you must insert a comma:  (27,).

boB

From ahall at autodist.com  Mon Jul  4 17:44:29 2016
From: ahall at autodist.com (Alex Hall)
Date: Mon, 4 Jul 2016 17:44:29 -0400
Subject: [Tutor] iterators
In-Reply-To: <COL129-W77980FED3F2CF536405A8FD0380@phx.gbl>
References: <COL129-W77980FED3F2CF536405A8FD0380@phx.gbl>
Message-ID: <03AFB68C-9B69-4417-BB3C-534570F4B547@autodist.com>

I believe the problem is what the error says: you're passing an int. When you give it two values, you're giving it a tuple, like (1, 2). That's a list type object in Python, and the 'in' keyword has to operate on lists. Therefore, it works.

When you give it one value, though, you're giving it an integer, which isn't a list type. The 'in' keyword can't do anything with integers, so it errors out. A check for equality seems the best approach here, but, in theory, I suppose you could do

If a in [27]

To get it to work.
> On Jul 4, 2016, at 16:38, Colby Christensen <colbychristensen at hotmail.com> wrote:
> 
> I'm sure this is something simple but I'm missing it. 
> When I check the statement with two values, the if statement works. However, for the statement with one value I get an error.
> keycode = event.GetKeyCode()
> if keycode in (13, 370):
>    self.enter()
> elif keycode in (43, 388):
>    self.add()
> elif keycode in (45, 390):
>    self.sub()
> elif keycode in (42, 387):
>    self.mult()
> elif keycode in (47, 392):
>    self.div()
> elif keycode in (27):
>    self.clear_all()
> elif keycode in (67, 99):
>    self.display.SetValue('')
> else:
>    event.Skip()This is the error message.
> Traceback (most recent call last):
>   File "/home/colby/Calculator/Calculator_betaV3.py", line 110, in OnKeyPress
>     elif keycode in (27):
> TypeError: argument of type 'int' is not iterable
> 
> I then tried using
> 
> elif keycode == 27:
> 
> but this statement didn't work. 
> 
> I'm pretty sure it's something simple that I've overlooked due to my inexperience.
> 
> Thanks in advance.
> 		 	   		  
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor


From alan.gauld at yahoo.co.uk  Mon Jul  4 19:47:27 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 5 Jul 2016 00:47:27 +0100
Subject: [Tutor] iterators
In-Reply-To: <COL129-W77980FED3F2CF536405A8FD0380@phx.gbl>
References: <COL129-W77980FED3F2CF536405A8FD0380@phx.gbl>
Message-ID: <nlesie$nao$1@ger.gmane.org>

On 04/07/16 21:38, Colby Christensen wrote:

> elif keycode in (47, 392):
>     self.div()
> elif keycode in (27):
>     self.clear_all()

I meant to say...

> I then tried using
> 
> elif keycode == 27:
> 
> but this statement didn't work. 

I'm not sure why that didn't work.
What exactly happened? Did you get a different error message?
If so what?


-- 
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 Jul  4 17:56:42 2016
From: dyoo at hashcollision.org (Danny Yoo)
Date: Mon, 4 Jul 2016 14:56:42 -0700
Subject: [Tutor] iterators
In-Reply-To: <COL129-W77980FED3F2CF536405A8FD0380@phx.gbl>
References: <COL129-W77980FED3F2CF536405A8FD0380@phx.gbl>
Message-ID: <CAGZAPF5Eb7xZ0vBbULwHiEXJr0Tant6z0ZtgbUsZGJyPTNZUcA@mail.gmail.com>

On Mon, Jul 4, 2016 at 1:38 PM, Colby Christensen
<colbychristensen at hotmail.com> wrote:
> I'm sure this is something simple but I'm missing it.
> When I check the statement with two values, the if statement works. However, for the statement with one value I get an error.
> keycode = event.GetKeyCode()
> if keycode in (13, 370):
>     self.enter()
> elif keycode in (43, 388):
>     self.add()
> elif keycode in (45, 390):
>     self.sub()
> elif keycode in (42, 387):
>     self.mult()
> elif keycode in (47, 392):
>     self.div()
> elif keycode in (27):
>     self.clear_all()
> elif keycode in (67, 99):
>     self.display.SetValue('')
> else:
>     event.Skip()


As Alan mentions, you've hit an "edge case" in Python's grammar.
Specifically, the grammar for defining tuples has a somewhat strange
edge case with regards to the 1-tuple.

    https://wiki.python.org/moin/TupleSyntax

where we need to add a trailing comma, even though it looks funky.


Why do we need it?  The reason that this edge case exists is to
disambiguate the 1-tuple from a different part of Python's grammar
involving parenthesized expressions.  Parentheses are used to enforce
a particular grouping of operations.

As an example, the math expression,

    y * (x + z)

uses parentheses to group the "x + z" part.  If we didn't use parens
there, it's harder to express the idea of adding 'x' and 'z' together
before multiplying by 'y', because multiplication "binds" more
strongly than addition, according to the grammatical rules.


So the extra trailing comma in a 1-tuple parenthesized expression is
just there to make it different looking, to disambiguate it from the
use of parentheses for expression grouping.

From steve at pearwood.info  Mon Jul  4 20:42:06 2016
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 5 Jul 2016 10:42:06 +1000
Subject: [Tutor] iterators
In-Reply-To: <nlesie$nao$1@ger.gmane.org>
References: <COL129-W77980FED3F2CF536405A8FD0380@phx.gbl>
 <nlesie$nao$1@ger.gmane.org>
Message-ID: <20160705004205.GQ27919@ando.pearwood.info>

On Tue, Jul 05, 2016 at 12:47:27AM +0100, Alan Gauld via Tutor wrote:

> > I then tried using
> > 
> > elif keycode == 27:
> > 
> > but this statement didn't work. 
> 
> I'm not sure why that didn't work.
> What exactly happened? Did you get a different error message?
> If so what?

I expect that the keycode is always a tuple, usually with two items but 
sometimes with one. So keycode == 27 compares the tuple (27,) with the 
int 27 and finds them to be different.


-- 
Steve

From eryksun at gmail.com  Mon Jul  4 21:12:42 2016
From: eryksun at gmail.com (eryk sun)
Date: Tue, 5 Jul 2016 01:12:42 +0000
Subject: [Tutor] iterators
In-Reply-To: <CAGZAPF5Eb7xZ0vBbULwHiEXJr0Tant6z0ZtgbUsZGJyPTNZUcA@mail.gmail.com>
References: <COL129-W77980FED3F2CF536405A8FD0380@phx.gbl>
 <CAGZAPF5Eb7xZ0vBbULwHiEXJr0Tant6z0ZtgbUsZGJyPTNZUcA@mail.gmail.com>
Message-ID: <CACL+1asQxD+Tjsop-wh9g-W69-pEFW+9XFfbta7SsmZ+DuN+QA@mail.gmail.com>

On Mon, Jul 4, 2016 at 9:56 PM, Danny Yoo <dyoo at hashcollision.org> wrote:
> So the extra trailing comma in a 1-tuple parenthesized expression is
> just there to make it different looking, to disambiguate it from the
> use of parentheses for expression grouping.

The comma is the distinguishing element of non-empty tuple literals.
It's always required in order to create a non-empty tuple, with or
without brackets. For example:

    >>> 27,
    (27,)

The parentheses are optional for a non-empty tuple, but they're often
required because a comma has low precedence. For example, with the
expression `x in y, z`, Python first evaluates `x in y`. If the goal
is to check whether x is in the the tuple `y, z`, then it has to be
written `x in (y, z)`.

From alan.gauld at yahoo.co.uk  Tue Jul  5 04:01:14 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 5 Jul 2016 09:01:14 +0100
Subject: [Tutor] iterators
In-Reply-To: <20160705004205.GQ27919@ando.pearwood.info>
References: <COL129-W77980FED3F2CF536405A8FD0380@phx.gbl>
 <nlesie$nao$1@ger.gmane.org> <20160705004205.GQ27919@ando.pearwood.info>
Message-ID: <nlfpg9$c6p$1@ger.gmane.org>

On 05/07/16 01:42, Steven D'Aprano wrote:
> On Tue, Jul 05, 2016 at 12:47:27AM +0100, Alan Gauld via Tutor wrote:
> 
>>> I then tried using
>>>
>>> elif keycode == 27:
>>>
>>> but this statement didn't work. 
>>
>> I'm not sure why that didn't work.
>> What exactly happened? Did you get a different error message?
>> If so what?
> 
> I expect that the keycode is always a tuple, usually with two items but 
> sometimes with one. So keycode == 27 compares the tuple (27,) with the 
> int 27 and finds them to be different.

but then the 'in' tests would fail.

>>> (27,) in (27,36)
False

the fact that the 'in' tests work suggests that keycode
is an int. But in that case the == test should work...

Although I just realized that the OP didn't actually say
the 'in' tests worked, just that they pass the compiler...

-- 
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 usstexas39 at outlook.com  Mon Jul  4 23:36:47 2016
From: usstexas39 at outlook.com (Frank Lawrence)
Date: Tue, 5 Jul 2016 03:36:47 +0000
Subject: [Tutor] Problem with code
Message-ID: <BLUPR18MB00031137B84715C7D77BBECCD8390@BLUPR18MB0003.namprd18.prod.outlook.com>

Hello, I have a code here that I?m having a problem with. It?s supposed to be a pizza ordering simulator, as you can tell by the title, but I keep trying to add music to it and whenever I try to play the music with the program running, it always freezes up and crashes. Can someone help me with this? It?s really been bugging me. Thanks!



Sent from Mail<https://go.microsoft.com/fwlink/?LinkId=550986> for Windows 10


From alan.gauld at yahoo.co.uk  Tue Jul  5 04:17:53 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 5 Jul 2016 09:17:53 +0100
Subject: [Tutor] Problem with code
In-Reply-To: <BLUPR18MB00031137B84715C7D77BBECCD8390@BLUPR18MB0003.namprd18.prod.outlook.com>
References: <BLUPR18MB00031137B84715C7D77BBECCD8390@BLUPR18MB0003.namprd18.prod.outlook.com>
Message-ID: <nlfqfg$qsc$1@ger.gmane.org>

On 05/07/16 04:36, Frank Lawrence wrote:
> Hello, I have a code here that I?m having a problem with. 

Unfortunately we can't see it.

Now, I could see it among a bunch of HTML when I checked it in the
moderator queue, so I'm guessing you sent it as some kind of
attachment and the server has stripped it off.

Please resend the code pasted into the body of the email.

> I keep trying to add music to it and whenever I try to play 
> the music with the program running, it always freezes up
> and crashes.

I don't know about the crash, but the freezing may be
because it needs to run in a separate thread. Anything
that takes a long time to process in a GUI should be
done in a background thread. (I don't know if you are
familiar with threads yet, but they are a kind of
lightweight background subprocess that allows your
program to do two things at once.)

But without seeing the code that is just a guess!

-- 
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 ahall at autodist.com  Tue Jul  5 09:22:52 2016
From: ahall at autodist.com (Alex Hall)
Date: Tue, 5 Jul 2016 09:22:52 -0400
Subject: [Tutor] Writing decorators?
Message-ID: <CA+Q8_Jes1FV=1rHOZLSODAkRCtiUBOAnp5ygUQsXWi-F-co7RQ@mail.gmail.com>

Hi list,
I've read three or four articles on creating decorators. I don't know why,
but the use of decorators makes sense, yet the creation of them isn't
clicking. I get the idea, but when it comes to precisely how to write
one--what goes where and gets returned/called when--it's just not making
complete sense.

To simplify things, what might be an example of a decorator that, say,
prints "decorated" before whatever string the decorated function prints?
That is:

@prependDecorated()
def printSomething(str):
    print str

printSomething("Hello world.")
#result should be:
decoratedHello world.

My attempt would be:

def prependDecorated(f):
  def prepend():
    return "decorated"+f()
  #something should go at this level too?

As I said, I've already read several sources on this. Are there any that
people find especially clear and helpful? Thanks for any links and/or
explanations.

-- 
Alex Hall
Automatic Distributors, IT department
ahall at autodist.com

From alan.gauld at yahoo.co.uk  Tue Jul  5 10:40:30 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 5 Jul 2016 15:40:30 +0100
Subject: [Tutor] Writing decorators?
In-Reply-To: <CA+Q8_Jes1FV=1rHOZLSODAkRCtiUBOAnp5ygUQsXWi-F-co7RQ@mail.gmail.com>
References: <CA+Q8_Jes1FV=1rHOZLSODAkRCtiUBOAnp5ygUQsXWi-F-co7RQ@mail.gmail.com>
Message-ID: <nlggst$7eh$1@ger.gmane.org>

On 05/07/16 14:22, Alex Hall wrote:

> To simplify things, what might be an example of a decorator that, say,
> prints "decorated" before whatever string the decorated function prints?

> My attempt would be:
> 
> def prependDecorated(f):
>   def prepend():
>     return "decorated"+f()
>   #something should go at this level too?

Recall that a decorator is:

a function
that takes a function as its argument
and returns a function

Your code fails on the third item.

Lets take a trivial example first, a decorator that
does nothing. Define a function that takes a function
and returns the same function untouched:

>>> def donothing(f): return f

Now apply it to a square() function:

>>> @donothing
def square(x): return x*x

>>> square
<function square at 0x7f3633fcb0d0>
>>> square(4)
16

We could do the same without the @ shorthand by using

square2 = donothing(square)

But the @ syntax makes it more readable.

Now lets look at your task
We need a function that takes a function and
returns a function that prepends a string:

def prepend(f):
    def add_string(*args, **kwargs):  # in case f takes arguments
        return "decorated "+ str(f(*args,**kwargs))
    return add_string

Now we can apply that to a function

@prepend
def cube(n): return n*n*n

cube(3)

I'm biased because I was the tech editor but the book
Professional Python has a nice chapter on decorators.

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  Tue Jul  5 11:26:34 2016
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 6 Jul 2016 01:26:34 +1000
Subject: [Tutor] Writing decorators?
In-Reply-To: <CA+Q8_Jes1FV=1rHOZLSODAkRCtiUBOAnp5ygUQsXWi-F-co7RQ@mail.gmail.com>
References: <CA+Q8_Jes1FV=1rHOZLSODAkRCtiUBOAnp5ygUQsXWi-F-co7RQ@mail.gmail.com>
Message-ID: <20160705152633.GR27919@ando.pearwood.info>

On Tue, Jul 05, 2016 at 09:22:52AM -0400, Alex Hall wrote:
> Hi list,
> I've read three or four articles on creating decorators. I don't know why,
> but the use of decorators makes sense, yet the creation of them isn't
> clicking. I get the idea, but when it comes to precisely how to write
> one--what goes where and gets returned/called when--it's just not making
> complete sense.

*Technically* a decorator can return anything at all, but the most 
common use for them is to return a function. In this case, the decorator 
is a function that:

(1) Takes as input a single function;
(2) Processes or wraps that function in some way; and
(3) Returns the original function, or the wrapped function, as output.

Back before Python had the "@decorator" syntax, we used to use 
decorators like this:

def func(arg):
    ...

func = decorator(func)


which has the disadvantage that we have to write the function name three 
times, and that the call to the decorator is kinda lost there at the end 
instead of near the function declaration, but it does have one 
advantage: it makes it clear that "func" gets set to whatever 
decorator() returns.

Which may be None if you're not careful.


> To simplify things, what might be an example of a decorator that, say,
> prints "decorated" before whatever string the decorated function prints?


import functools

def prependDecorated(function):
    """Wrap function so that it prints "decorated" before running."""
    # Here we define a new function that prints "decorated",
    # then calls the original function.
    #
    # We use functools.wraps as a bit of magic to make sure our new
    # function looks like the original (same name, docstring, etc).
    #
    @functools.wraps(function)
    def inner(*args, **kwargs):
        print("Decorated!")
        return function(*args, **kwargs)
    #
    # Now that we have our new "inner" function that calls the old
    # one, we have to return that inner function.
    return inner


@prependDecorated  # NO PARENTHESES!!!
def lunch():
    print("What's for lunch?")
    print("How about some wonderful SPAM!!!")




That's what the great bulk of decorators look like:

(1) declare a function that takes one function as argument;

(2) define an inner function (usually called "inner");

(3) it will often take arbitrary *args, **kwargs parameters, since you 
don't normally know what arguments the WRAPPED (decorated) function will 
take;

(3) use functools.wraps to disguise the inner function as the original 
function (this is important so that it keeps the docstring, the name, 
any other attached attributes etc. that the original had);

(4) inside the "inner" function, do your pre-processing, then call the 
original function, do any post-processing, and then return the result;

(5) finally return the "inner" function.


Here's a decorator that makes sure the decorated function returns a 
string:

def stringify(func):
    @functools.wraps(func)
    def inner(*args, **kwargs):
        result = func(*args, **kwargs)
        return "stringified result: " + str(result)
    return inner


@stringify
def add(a, b):
    """Return the stringified result of adding a and b."""
    return a+b


Here's a decorator that makes sure the first argument is greater than 
zero:

def verify_arg0(func):
    @functools.wraps(func)
    def inner(x, *args, **kwargs):
        if x <= 0:
            raise ValueError('x must be greater than zero')
        return func(x, *args, **kwargs)
    return inner

Here's a neat trick: here's a decorator that doesn't actually modify the 
function, but registers its name somewhere!


THE_REGISTER = []

def register(func):
    THE_REGISTER.append(func.__name__)
    return func

@register
def plus(a, b): return a + b

@register
def minus(a, b): return a - b



> That is:
> 
> @prependDecorated()
> def printSomething(str):
>     print str
> 
> printSomething("Hello world.")
> #result should be:
> decoratedHello world.


This one is trickier than you think, because it requires knowledge of 
what the original function will do. It *requires* that the original 
function MUST call print at least once, otherwise you'll have started to 
print something, but not completed the line. That may mess up your 
python prompt (in the interactive interpreter) or any other output you 
print. But here we go:


def prepend_actual_print(func):
    @functools.wraps(func)
    def inner(*args, **kwargs):
        ## print("decorated", end='')  # Python 3 syntax
        sys.stdout.write("decorated")  # Python 2
        return func(*args, **kwargs)
    return inner


Hope this helps!


-- 
Steve

From alan.gauld at yahoo.co.uk  Tue Jul  5 13:26:00 2016
From: alan.gauld at yahoo.co.uk (Alan G)
Date: Tue, 05 Jul 2016 18:26:00 +0100
Subject: [Tutor] Writing decorators?
Message-ID: <go048l6wjgnai5r2ruecyieq.1467739560709@email.android.com>

   Sorry for top posting, but yes excepting you don't need the parens after
   log in the @log line.

   Sent from my Fonepad

   Alex Hall <ahall at autodist.com> wrote:

   Okay, I think I follow. So a decorator to log that a function ran might
   be:

   import utils

   @log()
   def run():
   ** #do things

   #utils.py

   logger = #set up logging

   def log(f):
   ** def logThatFRan(*args, **kwargs):
   ****** [1]logger.info("running %s" %(f.__name__)
   ****** return f(*args, **kwargs)
   ** return logThatFRan

   That will log that F ran, then run f with any arguments. I know I'd have
   to decorate the inner function with functools.wraps for __name__ to work
   correctly, but that's the general idea, right?
   On Tue, Jul 5, 2016 at 10:40 AM, Alan Gauld via Tutor
   <[2]tutor at python.org> wrote:

     On 05/07/16 14:22, Alex Hall wrote:

     > To simplify things, what might be an example of a decorator that, say,
     > prints "decorated" before whatever string the decorated function
     prints?

     > My attempt would be:
     >
     > def prependDecorated(f):
     >** **def prepend():
     >** ** **return "decorated"+f()
     >** **#something should go at this level too?

     Recall that a decorator is:

     a function
     that takes a function as its argument
     and returns a function

     Your code fails on the third item.

     Lets take a trivial example first, a decorator that
     does nothing. Define a function that takes a function
     and returns the same function untouched:

     >>> def donothing(f): return f

     Now apply it to a square() function:

     >>> @donothing
     def square(x): return x*x

     >>> square
     <function square at 0x7f3633fcb0d0>
     >>> square(4)
     16

     We could do the same without the @ shorthand by using

     square2 = donothing(square)

     But the @ syntax makes it more readable.

     Now lets look at your task
     We need a function that takes a function and
     returns a function that prepends a string:

     def prepend(f):
     ** ** def add_string(*args, **kwargs):** # in case f takes arguments
     ** ** ** ** return "decorated "+ str(f(*args,**kwargs))
     ** ** return add_string

     Now we can apply that to a function

     @prepend
     def cube(n): return n*n*n

     cube(3)

     I'm biased because I was the tech editor but the book
     Professional Python has a nice chapter on decorators.

     HTH

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

     _______________________________________________
     Tutor maillist** -** [6]Tutor at python.org
     To unsubscribe or change subscription options:
     [7]https://mail.python.org/mailman/listinfo/tutor

   --
   Alex Hall
   Automatic Distributors, IT department
   [8]ahall at autodist.com

References

   Visible links
   1. http://logger.info/
   2. mailto:tutor at python.org
   3. http://www.alan-g.me.uk/
   4. http://www.amazon.com/author/alan_gauld
   5. http://www.flickr.com/photos/alangauldphotos
   6. mailto:Tutor at python.org
   7. https://mail.python.org/mailman/listinfo/tutor
   8. mailto:ahall at autodist.com

From ahall at autodist.com  Tue Jul  5 13:31:04 2016
From: ahall at autodist.com (Alex Hall)
Date: Tue, 5 Jul 2016 13:31:04 -0400
Subject: [Tutor] Writing decorators?
In-Reply-To: <go048l6wjgnai5r2ruecyieq.1467739560709@email.android.com>
References: <go048l6wjgnai5r2ruecyieq.1467739560709@email.android.com>
Message-ID: <CA+Q8_JfGLQNiOsMgdztsFHPpRVEJBmRPBi7hv=umLQdC7Dc8DA@mail.gmail.com>

On Tue, Jul 5, 2016 at 1:26 PM, Alan G <alan.gauld at yahoo.co.uk> wrote:

> Sorry for top posting, but yes excepting you don't need the parens after
> log in the @log line.
>

For decorators, do you never include parentheses except for passing
arguments? It seems a bit odd to drop them if they'd be empty, given that
anywhere else doing so would return the function object rather than call
it. Yet, if arguments are passed, you include them like you would anywhere
else. Or am I misunderstanding it?

>
> Sent from my Fonepad
>
> Alex Hall <ahall at autodist.com> wrote:
>
> Okay, I think I follow. So a decorator to log that a function ran might be:
>
> import utils
>
> @log()
> def run():
>   #do things
>
> #utils.py
>
> logger = #set up logging
>
> def log(f):
>   def logThatFRan(*args, **kwargs):
>     logger.info("running %s" %(f.__name__)
>     return f(*args, **kwargs)
>   return logThatFRan
>
> That will log that F ran, then run f with any arguments. I know I'd have
> to decorate the inner function with functools.wraps for __name__ to work
> correctly, but that's the general idea, right?
>
>
> On Tue, Jul 5, 2016 at 10:40 AM, Alan Gauld via Tutor <tutor at python.org>
> wrote:
>
>> On 05/07/16 14:22, Alex Hall wrote:
>>
>> > To simplify things, what might be an example of a decorator that, say,
>> > prints "decorated" before whatever string the decorated function prints?
>>
>> > My attempt would be:
>> >
>> > def prependDecorated(f):
>> >   def prepend():
>> >     return "decorated"+f()
>> >   #something should go at this level too?
>>
>> Recall that a decorator is:
>>
>> a function
>>
>> that takes a function as its argument
>> and returns a function
>>
>> Your code fails on the third item.
>>
>> Lets take a trivial example first, a decorator that
>> does nothing. Define a function that takes a function
>> and returns the same function untouched:
>>
>> >>> def donothing(f): return f
>>
>> Now apply it to a square() function:
>>
>> >>> @donothing
>> def square(x): return x*x
>>
>> >>> square
>> <function square at 0x7f3633fcb0d0>
>> >>> square(4)
>> 16
>>
>> We could do the same without the @ shorthand by using
>>
>> square2 = donothing(square)
>>
>> But the @ syntax makes it more readable.
>>
>> Now lets look at your task
>> We need a function that takes a function and
>> returns a function that prepends a string:
>>
>> def prepend(f):
>>     def add_string(*args, **kwargs):  # in case f takes arguments
>>         return "decorated "+ str(f(*args,**kwargs))
>>     return add_string
>>
>> Now we can apply that to a function
>>
>> @prepend
>> def cube(n): return n*n*n
>>
>> cube(3)
>>
>> I'm biased because I was the tech editor but the book
>> Professional Python has a nice chapter on decorators.
>>
>> 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
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>
>
>
> --
> Alex Hall
> Automatic Distributors, IT department
> ahall at autodist.com
>



-- 
Alex Hall
Automatic Distributors, IT department
ahall at autodist.com

From ahall at autodist.com  Tue Jul  5 15:05:45 2016
From: ahall at autodist.com (Alex Hall)
Date: Tue, 5 Jul 2016 15:05:45 -0400
Subject: [Tutor] isinstance versus 'is'?
Message-ID: <CA+Q8_JfMtXc3T6b4gRm3MQBd+rUbfEPn00ZSam6FAiNHS0pMgQ@mail.gmail.com>

Hi all,
Thanks for all the help regarding decorators. It makes more sense now.

I was double checking that I remembered the isinstance order of arguments
correctly by using the command line interpreter, and found something very
odd.

>>> a = 5
>>> isinstance(a, int)
True
>>> a is int
False

What happened there? Don't these do the same thing? I thought I could use
them interchangeably?

-- 
Alex Hall
Automatic Distributors, IT department
ahall at autodist.com

From michael.selik at gmail.com  Tue Jul  5 17:36:24 2016
From: michael.selik at gmail.com (Michael Selik)
Date: Tue, 05 Jul 2016 21:36:24 +0000
Subject: [Tutor] dont understand part of a code
In-Reply-To: <nl8c1e$fmi$1@ger.gmane.org>
References: <CANeHpPKZ-d2HukHO-pCi-XQS7jyaMsSQAp7GpQE-z5WMpnVctw@mail.gmail.com>
 <nl8c1e$fmi$1@ger.gmane.org>
Message-ID: <CAGgTfkNaKbkF30QqbqC3sPUQqRSBuk6WZWUrN-+2wiAbR9UzXg@mail.gmail.com>

On Sat, Jul 2, 2016 at 8:29 AM Alan Gauld via Tutor <tutor at python.org>
wrote:

> There are arguably easier ways of doing this
>

I think you'll find that for-loops are preferable to while-loops. Here's an
alternative implementation.

https://gist.github.com/selik/d8e0a7622ceff0fe8984a7d19d44bfca

    import random
    import string

    drawings = (
        r"""
        ------|
        |
        |
        |
        |
        --
        """,
        r"""
        ------|
        |     0
        |
        |
        |
        --
        """,
        r"""
        ------|
        |     0
        |    -+-
        |
        |
        --
        """,
        r"""
        ------|
        |     0
        |   /-+-
        |
        |
        --
        """,
        r"""
        ------|
        |     0
        |   /-+-\
        |
        |
        --
        """,
        r"""
        ------|
        |     0
        |   /-+-\
        |     |
        |
        --
        """,
        r"""
        ------|
        |     0
        |   /-+-\
        |     |
        |    |
        --
        """,
        r"""
        ------|
        |     0
        |   /-+-\
        |     |
        |    | |
        --
        """
    )

    print('Welcome to Hangman.')
    print('Good luck!')

    words = 'python ruby php java unix linux perl'.split()
    target = list(random.choice(words))
    known = ['_'] * len(target)
    used = []

    for drawing in drawings:
        print('-'.join(c if c not in used else ' ' for c in
string.ascii_lowercase))
        print(drawing, '\n\t', ' '.join(known))
        guess = input('\nEnter your guess: ').lower()

        while guess in used:
            print("You've already guessed that letter")
            guess = input('Please enter a new guess: ').lower()

        used.append(guess)
        if guess in target:
            print('Yes, {!r} is in the word!'.format(guess))
            for i, letter in enumerate(target):
                if guess == letter:
                    known[i] = letter
        else:
            print('Sorry, {!r} is not in the word.'.format(guess))

        if known == target:
            print('\nYou guessed the word correctly!')
            break
    else:
        print('\nYou have been hanged!')

    print('The word was {!r}'.format(''.join(target)))

From joel.goldstick at gmail.com  Tue Jul  5 18:49:38 2016
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Tue, 5 Jul 2016 18:49:38 -0400
Subject: [Tutor] isinstance versus 'is'?
In-Reply-To: <CA+Q8_JfMtXc3T6b4gRm3MQBd+rUbfEPn00ZSam6FAiNHS0pMgQ@mail.gmail.com>
References: <CA+Q8_JfMtXc3T6b4gRm3MQBd+rUbfEPn00ZSam6FAiNHS0pMgQ@mail.gmail.com>
Message-ID: <CAPM-O+yDmge6aW18i4spbJyXph65Lwz4=OMQMzjuN0RT11bRWg@mail.gmail.com>

On Tue, Jul 5, 2016 at 3:05 PM, Alex Hall <ahall at autodist.com> wrote:
> Hi all,
> Thanks for all the help regarding decorators. It makes more sense now.
>
> I was double checking that I remembered the isinstance order of arguments
> correctly by using the command line interpreter, and found something very
> odd.
>
>>>> a = 5
>>>> isinstance(a, int)
> True
>>>> a is int
> False
>
> What happened there? Don't these do the same thing? I thought I could use
> them interchangeably?
>
> --
> Alex Hall
> Automatic Distributors, IT department
> ahall at autodist.com
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

is denotes identity.  5 is not the type int.  It is an int, but it is
not the same -- if it was 5('16') would be 16.

-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays

From alan.gauld at yahoo.co.uk  Tue Jul  5 19:06:49 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 6 Jul 2016 00:06:49 +0100
Subject: [Tutor] Writing decorators?
In-Reply-To: <CA+Q8_JfGLQNiOsMgdztsFHPpRVEJBmRPBi7hv=umLQdC7Dc8DA@mail.gmail.com>
References: <go048l6wjgnai5r2ruecyieq.1467739560709@email.android.com>
 <CA+Q8_JfGLQNiOsMgdztsFHPpRVEJBmRPBi7hv=umLQdC7Dc8DA@mail.gmail.com>
Message-ID: <nlhei8$iao$1@ger.gmane.org>

On 05/07/16 18:31, Alex Hall wrote:

> For decorators, do you never include parentheses except for passing
> arguments? It seems a bit odd to drop them if they'd be empty, given that
> anywhere else doing so would return the function object rather than call
> it. 

Remember what the @ sign is doing.

@decorator
def func():...

is effectively suyntactic sugar for

func = decorator(func)

If you write @decorator()

That translates to

@decorator()(func)

which is not at all the same thing.

Of course you could get into brain melting mode and
write a meta-decorator that returns a decorator!

>>> def meta():
	def decorator(f):
	    def logit(*args,**kwargs):
		    print("called function with ", args, kwargs)
		    return f(*args,**kwargs)
	    return logit
	return decorator

>>> @meta()    #with parens and potentially args
def square(x): return x*x

>>> square(3)
called function with  (3,) {}
9
>>>

yikes! It all starts to get too complicated for my tiny
brain at this point and I usually find another more
explicit way to do what I need...


-- 
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 yahoo.co.uk  Tue Jul  5 19:22:48 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 6 Jul 2016 00:22:48 +0100
Subject: [Tutor] isinstance versus 'is'?
In-Reply-To: <CA+Q8_JfMtXc3T6b4gRm3MQBd+rUbfEPn00ZSam6FAiNHS0pMgQ@mail.gmail.com>
References: <CA+Q8_JfMtXc3T6b4gRm3MQBd+rUbfEPn00ZSam6FAiNHS0pMgQ@mail.gmail.com>
Message-ID: <nlhfg7$1ae$1@ger.gmane.org>

On 05/07/16 20:05, Alex Hall wrote:

> I was double checking that I remembered the isinstance order of arguments
> correctly by using the command line interpreter, and found something very
> odd.
> 
>>>> a = 5
>>>> isinstance(a, int)
> True
>>>> a is int
> False
> 
> What happened there? Don't these do the same thing? 

Evidently not!
Think about it. isinstance() is asking if a is an
instance of int. int is a type. 5 is an instance of
that type but it's not the type itself.

a is int

is asking if a and int are the same things
(are they actually the same object).
Clearly 5 is not the type int. We can check
this in the interpreter:

>>> isinstance(5,int)
True
>>> int
<type 'int'>
>>> 5
5

What you may be getting confused with is:

>>> type(5) is int
True
>>>

But even then this is not identical to isinstance,
because the latter checks for subclass relationships
too:

>>> class C: pass
...
>>> class D(C): pass
...
>>> c = C()
>>> d = D()
>>> isinstance(c, C)
True
>>> isinstance(c, D)
False
>>> isinstance(d, C)
True
>>> isinstance(d, D)
True
>>> type(c) is C
True
>>> type(d) is type(C)
False

And to further complicate matters the above works
differently in v2 from v3(above)

The bottom line is that isinstance() is usually
the best choice.


-- 
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 yahoo.co.uk  Tue Jul  5 19:24:36 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 6 Jul 2016 00:24:36 +0100
Subject: [Tutor] Writing decorators?
In-Reply-To: <nlhei8$iao$1@ger.gmane.org>
References: <go048l6wjgnai5r2ruecyieq.1467739560709@email.android.com>
 <CA+Q8_JfGLQNiOsMgdztsFHPpRVEJBmRPBi7hv=umLQdC7Dc8DA@mail.gmail.com>
 <nlhei8$iao$1@ger.gmane.org>
Message-ID: <nlhfji$1ae$2@ger.gmane.org>

On 06/07/16 00:06, Alan Gauld via Tutor wrote:

> func = decorator(func)
> 
> If you write @decorator()
> 
> That translates to
> 
> @decorator()(func)

Ooops, I meant to say

func = decorator()(func)

Sorry.
-- 
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  Tue Jul  5 19:28:04 2016
From: dyoo at hashcollision.org (Danny Yoo)
Date: Tue, 5 Jul 2016 16:28:04 -0700
Subject: [Tutor] isinstance versus 'is'?
In-Reply-To: <CA+Q8_JfMtXc3T6b4gRm3MQBd+rUbfEPn00ZSam6FAiNHS0pMgQ@mail.gmail.com>
References: <CA+Q8_JfMtXc3T6b4gRm3MQBd+rUbfEPn00ZSam6FAiNHS0pMgQ@mail.gmail.com>
Message-ID: <CAGZAPF5H1xh7u9TV1Dy+RADoVQt0dsAeBd3BL2QpwA4WDhGSMw@mail.gmail.com>

On Tue, Jul 5, 2016 at 12:05 PM, Alex Hall <ahall at autodist.com> wrote:

>>>> a = 5
>>>> isinstance(a, int)
> True
>>>> a is int
> False
>
> What happened there? Don't these do the same thing? I thought I could use
> them interchangeably?


'isinstance' is something else from 'is'.

isinstance will tell us if something is considered to be an "instance"
of something: it knows how to categorize.

This might be important if, when we're running our program, we have
some data and want to do some case analysis based on what
classification that data falls into.

For example, True and False can be identified as instances of the booleans.

###################################
>>> isinstance(True, bool)
True
>>> isinstance(False, bool)
True
###################################

If we're object oriented programming based on different classes of
data, then 'isinstance' can be used to distinguish things based on
their class.  For example:

#############################
class C1(object): pass
class C2(object): pass

barry = C1()
white = C2()

print(isinstance(barry, C1))
print(isinstance(barry, C2))
##############################

if we have two classes, we can create instances of them, and use
'isinstance' to find out if they match a particular class-ification.

I rarely use this operator in practice because usually, *how* a value
operates and behaves is much more important than *what* strata that
value belongs to.

I suppose that's an ideal of meritocracy.  :)



In contrast, 'is' is a more low-level notion having to do with
*equality*, not classification.  These are both operations that
compare two things, but their conceptual types are not the same:

  * 'isinstance' deals with a thing and a category.

  * 'is' works on two things that, presumably, might be the same type
of thing.  (Why?  Because if we knew in advance that the the two
things were of different types, then we already know that 'is' will
return False, so we know our answer in advance.)

From lohecn at tuta.io  Tue Jul  5 19:56:19 2016
From: lohecn at tuta.io (lohecn at tuta.io)
Date: Wed, 6 Jul 2016 00:56:19 +0100 (BST)
Subject: [Tutor] help with exercise 15 of zed shaw's LPTHW
Message-ID: <KLxUPLY--3-0@tuta.io>

hey everyone. this is my first time trying this -- actually, I've been 
studying python only for some days now, and I'm afraid my questions are going 
to be reeeeally simple, but I can't seem to understand this piece of code and 
thus can't move on.

you probably know the book, so you know that zed always makes us write code 
so that then we can understand how it works, and it's great, but in this 
exercise there are just too many new functions and without explanation they 
are a bit hard to understand... so I'm having trouble with most of the lines 
here.

it's not that I want the full explanation to that code, but since I'm 
unfamiliar with some of its concepts, I'm just going to tell you all the 
things that I don't understand (sorry for it being a lot):
1. the need to put script into an estipulation for argv (line 3)
2. the what is txt and why it has to be used there (line 4)
3. txt.read() -- which are all new functions(? I dont even know what they 
are)? (line 7)
4. file_again (line 10)
5. txt_again (line 12)
and line 14.

as you can see, it's pretty much everything. sorry about that.
I'd really appreciate any help at all!
thanks a lot,

heloisa

From alan.gauld at yahoo.co.uk  Tue Jul  5 20:28:32 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 6 Jul 2016 01:28:32 +0100
Subject: [Tutor] isinstance versus 'is'?
In-Reply-To: <nlhfg7$1ae$1@ger.gmane.org>
References: <CA+Q8_JfMtXc3T6b4gRm3MQBd+rUbfEPn00ZSam6FAiNHS0pMgQ@mail.gmail.com>
 <nlhfg7$1ae$1@ger.gmane.org>
Message-ID: <nlhjbf$op3$1@ger.gmane.org>

On 06/07/16 00:22, Alan Gauld via Tutor wrote:

>>>> type(c) is C
> True
>>>> type(d) is type(C)
> False

The last one should of course be

>>> type(d) is C
False

Apologies.

-- 
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  Tue Jul  5 20:32:28 2016
From: robertvstepp at gmail.com (boB Stepp)
Date: Tue, 5 Jul 2016 19:32:28 -0500
Subject: [Tutor] help with exercise 15 of zed shaw's LPTHW
In-Reply-To: <KLxUPLY--3-0@tuta.io>
References: <KLxUPLY--3-0@tuta.io>
Message-ID: <577C519C.5010206@gmail.com>

Welcome!

On 07/05/2016 06:56 PM, lohecn at tuta.io wrote:
> hey everyone. this is my first time trying this -- actually, I've been
> studying python only for some days now, and I'm afraid my questions are going
> to be reeeeally simple, but I can't seem to understand this piece of code and
> thus can't move on.
>
> you probably know the book, so you know that zed always makes us write code
> so that then we can understand how it works, and it's great, but in this
> exercise there are just too many new functions and without explanation they
> are a bit hard to understand... so I'm having trouble with most of the lines
> here.

While this book is fairly well known, not everyone has a copy at hand. 
I would suggest that you resend your email with the full exercise typed 
into its body (This list does not accept attachments BTW.), and then 
pose your questions.  This way you provide the necessary context *in* 
your email body, so that everyone can follow along.

Cheers!
boB

From steve at pearwood.info  Tue Jul  5 20:54:42 2016
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 6 Jul 2016 10:54:42 +1000
Subject: [Tutor] isinstance versus 'is'?
In-Reply-To: <CA+Q8_JfMtXc3T6b4gRm3MQBd+rUbfEPn00ZSam6FAiNHS0pMgQ@mail.gmail.com>
References: <CA+Q8_JfMtXc3T6b4gRm3MQBd+rUbfEPn00ZSam6FAiNHS0pMgQ@mail.gmail.com>
Message-ID: <20160706005441.GT27919@ando.pearwood.info>

On Tue, Jul 05, 2016 at 03:05:45PM -0400, Alex Hall wrote:

> >>> a = 5
> >>> isinstance(a, int)
> True
> >>> a is int
> False
> 
> What happened there? Don't these do the same thing? I thought I could use
> them interchangeably?

You're probably thinking of "is a", as in, "5 is an int", "'Hello 
World' is a str", "[1, 2, 3] is a list", etc.

Python doesn't have an operator for testing "is a" relationships, it 
uses isinstance(obj, type). There's also issubclass(), for testing 
whether one class is a subclass of another.

"x is y" checks whether the two operands x and y are the same object. 
That's *not* the same as checking whether they are equal. You should 
hardly ever use "is" in Python, with the exception of testing for None: 
"if obj is None: ..." sort of thing.


-- 
Steve

From steve at pearwood.info  Tue Jul  5 21:04:36 2016
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 6 Jul 2016 11:04:36 +1000
Subject: [Tutor] help with exercise 15 of zed shaw's LPTHW
In-Reply-To: <KLxUPLY--3-0@tuta.io>
References: <KLxUPLY--3-0@tuta.io>
Message-ID: <20160706010435.GU27919@ando.pearwood.info>

Hi Heloisa, and welcome.

Do you have a link to the code? Or better still, if it is short (say 
under fifty lines) can you copy it into an email and send it?

On Wed, Jul 06, 2016 at 12:56:19AM +0100, lohecn at tuta.io wrote:

[...]
> 1. the need to put script into an estipulation for argv (line 3)

I'm sorry, I don't know what that word "estipulation" means. Do you mean 
"stipulation", as in:

    That which is stipulated, or agreed upon; that which is
    definitely arranged or contracted; an agreement


> 2. the what is txt and why it has to be used there (line 4)
> 3. txt.read() -- which are all new functions(? I dont even know what they 
> are)? (line 7)
> 4. file_again (line 10)
> 5. txt_again (line 12)
> and line 14.

The only thing I can guess without seeing the code is that MAYBE txt is 
an open file, and txt.read() reads the content of the file.



-- 
Steve

From ahall at autodist.com  Tue Jul  5 21:37:26 2016
From: ahall at autodist.com (Alex Hall)
Date: Tue, 5 Jul 2016 21:37:26 -0400
Subject: [Tutor] isinstance versus 'is'?
In-Reply-To: <20160706005441.GT27919@ando.pearwood.info>
References: <CA+Q8_JfMtXc3T6b4gRm3MQBd+rUbfEPn00ZSam6FAiNHS0pMgQ@mail.gmail.com>
 <20160706005441.GT27919@ando.pearwood.info>
Message-ID: <CC7D6A43-F40C-40E1-A6DD-995DC8AA24BC@autodist.com>

Thanks everyone, that all makes more sense. I think I was indeed thinking of "is None", which is essentially the same as "== None" (I know there's a subtile difference, but they do the same thing). Of course, "is None" fits with this usage, as you're asking if the value is the literal None object. It seems it's the way None is handled, not an exception in the way 'is' works. Anyway, thanks for the explanations.
> On Jul 5, 2016, at 20:54, Steven D'Aprano <steve at pearwood.info> wrote:
> 
> On Tue, Jul 05, 2016 at 03:05:45PM -0400, Alex Hall wrote:
> 
>>>>> a = 5
>>>>> isinstance(a, int)
>> True
>>>>> a is int
>> False
>> 
>> What happened there? Don't these do the same thing? I thought I could use
>> them interchangeably?
> 
> You're probably thinking of "is a", as in, "5 is an int", "'Hello 
> World' is a str", "[1, 2, 3] is a list", etc.
> 
> Python doesn't have an operator for testing "is a" relationships, it 
> uses isinstance(obj, type). There's also issubclass(), for testing 
> whether one class is a subclass of another.
> 
> "x is y" checks whether the two operands x and y are the same object. 
> That's *not* the same as checking whether they are equal. You should 
> hardly ever use "is" in Python, with the exception of testing for None: 
> "if obj is None: ..." sort of thing.
> 
> 
> -- 
> Steve
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor


From michael.selik at gmail.com  Tue Jul  5 20:34:28 2016
From: michael.selik at gmail.com (Michael Selik)
Date: Wed, 06 Jul 2016 00:34:28 +0000
Subject: [Tutor] help with exercise 15 of zed shaw's LPTHW
In-Reply-To: <KLxUPLY--3-0@tuta.io>
References: <KLxUPLY--3-0@tuta.io>
Message-ID: <CAGgTfkM_diAScK=Q2DPL7LABMkXnzTtPSKWmcr4gUgqkB9Fj+g@mail.gmail.com>

On Tue, Jul 5, 2016 at 8:24 PM <lohecn at tuta.io> wrote:

> I'm having trouble with most of the lines here.
>

It looks like you tried to attach a file. This mailing list does not allow
attachments. Instead, could you paste the code into your email?


> things that I don't understand:
> 1. the need to put script into an estipulation for argv (line 3)
> 2. the what is txt and why it has to be used there (line 4)
> 3. txt.read() -- which are all new functions(? I dont even know what they
> are)  (line 7)
>

I'm guessing txt is a file object or a file-like object that supports the
.read method to read the entire contents of the file into a single string
object.


> 4. file_again (line 10)
> 5. txt_again (line 12)
> and line 14.
>

From michael.selik at gmail.com  Tue Jul  5 21:44:56 2016
From: michael.selik at gmail.com (Michael Selik)
Date: Wed, 06 Jul 2016 01:44:56 +0000
Subject: [Tutor] dont understand part of a code
In-Reply-To: <CAGgTfkNaKbkF30QqbqC3sPUQqRSBuk6WZWUrN-+2wiAbR9UzXg@mail.gmail.com>
References: <CANeHpPKZ-d2HukHO-pCi-XQS7jyaMsSQAp7GpQE-z5WMpnVctw@mail.gmail.com>
 <nl8c1e$fmi$1@ger.gmane.org>
 <CAGgTfkNaKbkF30QqbqC3sPUQqRSBuk6WZWUrN-+2wiAbR9UzXg@mail.gmail.com>
Message-ID: <CAGgTfkP=xYMduYVpc_b04-z27RT97x_aD++ogyfUPn3hp2_b=Q@mail.gmail.com>

On Tue, Jul 5, 2016 at 5:36 PM Michael Selik <michael.selik at gmail.com>
wrote:

> On Sat, Jul 2, 2016 at 8:29 AM Alan Gauld via Tutor <tutor at python.org>
> wrote:
>
>> There are arguably easier ways of doing this
>>
>
> I think you'll find that for-loops are preferable to while-loops. Here's
> an alternative implementation.
>
> https://gist.github.com/selik/d8e0a7622ceff0fe8984a7d19d44bfca
>

On further reflection, unfortunately a for-loop doesn't seem best for this
particular problem. I updated the gist, linked above. I wish the author had
chosen a better problem to emphasize Pythonic iteration.

From alan.gauld at yahoo.co.uk  Wed Jul  6 04:10:02 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 6 Jul 2016 09:10:02 +0100
Subject: [Tutor] help with exercise 15 of zed shaw's LPTHW
In-Reply-To: <KLxUPLY--3-0@tuta.io>
References: <KLxUPLY--3-0@tuta.io>
Message-ID: <577CBCDA.1010508@yahoo.co.uk>

On 06/07/16 00:56, lohecn at tuta.io wrote:
> hey everyone. this is my first time trying this 

Welcome, but...

> you probably know the book,

Sorry, I don't and I suspect I'm not alone.
It's probably a fine book, but we don't all know it.

>  so you know that zed always makes us write code 
> so that then we can understand how it works, 

Good man Zed :-)

> exercise there are just too many new functions and without explanation they 
> are a bit hard to understand... so I'm having trouble with most of the lines 
> here.

And here's the next problem.
This is a text based mailing list. As such the server often strips out
attachments as potential security risks. So we can't see the code (I'm
assuming you attached it?)

> 1. the need to put script into an estipulation for argv (line 3)
> 2. the what is txt and why it has to be used there (line 4)
> 3. txt.read() -- which are all new functions(? I dont even know what they 
> are)  (line 7)
> 4. file_again (line 10)
> 5. txt_again (line 12)
> and line 14.

Without sight of the code its hard to know what's going on.
But I suspect some of these "functions" are actually variables
(or objects) and hopefully zed has already discussed those?

Can you repost but include your code inside the mail message.
Also try to post in plain text since HTML tends to get garbled
in transit.

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 __peter__ at web.de  Wed Jul  6 04:22:06 2016
From: __peter__ at web.de (Peter Otten)
Date: Wed, 06 Jul 2016 10:22:06 +0200
Subject: [Tutor] help with exercise 15 of zed shaw's LPTHW
References: <KLxUPLY--3-0@tuta.io>
Message-ID: <nlif3g$ffs$1@ger.gmane.org>

lohecn at tuta.io wrote:

> hey everyone. this is my first time trying this -- actually, I've been
> studying python only for some days now, and I'm afraid my questions are
> going to be reeeeally simple, but I can't seem to understand this piece of
> code and thus can't move on.

You seem to be talking about

http://learnpythonthehardway.org/book/ex15.html

"""
from sys import argv

script, filename = argv

txt = open(filename)

print "Here's your file %r:" % filename
print txt.read()

print "Type the filename again:"
file_again = raw_input("> ")

txt_again = open(file_again)

print txt_again.read()
"""

As others said, always provide the code you are asking about, or if that is 
not possible at least provide a link.
 
> you probably know the book, so you know that zed always makes us write
> code so that then we can understand how it works, and it's great, but in
> this exercise there are just too many new functions and without
> explanation they are a bit hard to understand... so I'm having trouble
> with most of the lines here.
> 
> it's not that I want the full explanation to that code, but since I'm
> unfamiliar with some of its concepts, I'm just going to tell you all the
> things that I don't understand (sorry for it being a lot):
> 1. the need to put script into an estipulation for argv (line 3)

Write a script tmp.py containing

from sys import argv
print argv

then call it with with one parameter, e. g.

$ python tmp.py somefile.txt
['tmp.py', 'somefile.txt']

As you can see argv is a list with two items, the first being "tmp.py", the 
name of the script you are invoking. You are only interested in the second 
one, the filename. The easy way to get that is

filename = argv[1]

the hard way is to use "unpacking"

script, filename = argv

where python will assign one item from the list on the right to every name 
on the left:

>>> items = ["foo", "bar"]
>>> one, two = items
>>> one
'foo'
>>> two
'bar'

What happens if the number of names on the left doesn't match the number of 
items in the list?

>>> one, two, three = items
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack

You get an exception. That is why you have to provide the name "script" in 
Zed's example even though you are not actually interested in the script 
name.

> 2. the what is txt and why it has to be used there (line 4)

txt is a file object and

> 3. txt.read() -- which are all new functions(? I dont even know what they
> are)  (line 7)

read() is a method that here reads the whole file into a string. You use the 
open() function to open a file and usually assign the file object that is 
returned by open to a name. You can freely choose that name. The structure 
is the same for every object, be it a number:

x = 42  # assign a number to x
y = x + x  # do some arithmetic with x and assign the result to y
print y  # print the result

a list:

mynumbers = list()  # create a list
mynumbers.append(42)  # append a number to the list
print mynumbers  # print the list

or a file:

myfile = open("example.txt")  # open the file example.txt in the current
                              # working directory. If the file doesn't exist
                              # you get an error

print "first line:", myfile.readline()  # read the first line and print it
print "rest of the file:"
print myfile.read()  # read the rest of the file and print it

myfile.close()  # close the file

> 4. file_again (line 10)
> 5. txt_again (line 12)
> and line 14.

4. and 5. are just a repetition of the first part, with the variation that 
the filename, assigned to file_again is read interactively with raw_input() 
instead of passing it as a commandline argument to the script.

The names used can be freely chosen by the programmer, a script

from sys import argv

red_apple, my_hat = argv

blue_suede_shoes = open(my_hat)
print blue_suede_shoes.read()
blue_suede_shoes.close()

would work exactly like the first part of the hard-way example. However, 
picking descriptive names and using them consistently makes it much easier 
for a human reader to understand what's going on.


From ahall at autodist.com  Wed Jul  6 08:32:35 2016
From: ahall at autodist.com (Alex Hall)
Date: Wed, 6 Jul 2016 08:32:35 -0400
Subject: [Tutor] Subclassing logging.Handler?
Message-ID: <CA+Q8_JcT=0aBH3nGFCzQZv2E38msJPJrrOofu8VzcjV6HN1Xag@mail.gmail.com>

Hey list,
Another day, another Python experiment. I'm wondering what methods I'd have
to implement in a custom subclass of logger.Handler.

Currently, the recurring jobs I have written log their events to a file
each time they run. That's fine, but it doesn't let me keep
easily-sorted/searched records. Even if I use a size-based log file
handler, it'll get hard to search. I'm pondering logging to a database as
well, so that the files will always have the most recent few runs, but the
database will have everything. That means subclassing logger.Handler.

I found the docs for this, but is emit() the only function I need to
implement? There are things about i/o locks, formatting, and so on as well.
How much do I need to do, and how much can I leave up to the super class?
I'll have to call
super(MyLogHandler, self).__init__()
I know, but what else do I have to worry about? To be clear, I'm not asking
about logging to a database, only what to do to make a Handler subclass
capable of logging through whatever mechanisms I want. Thanks.

-- 
Alex Hall
Automatic Distributors, IT department
ahall at autodist.com

From lohecn at tuta.io  Wed Jul  6 10:04:27 2016
From: lohecn at tuta.io (lohecn at tuta.io)
Date: Wed, 6 Jul 2016 15:04:27 +0100 (BST)
Subject: [Tutor] help with exercise 15 of zed shaw's LPTHW
In-Reply-To: <nlif3g$ffs$1@ger.gmane.org>
References: <KLxUPLY--3-0@tuta.io> <nlif3g$ffs$1@ger.gmane.org>
Message-ID: <KM-WXgn----0@tuta.io>

first, sorry everyone for having attached the file instead of just typing it 
here.
second, thanks a lot for the replies; even though I gave you no code it was 
quite helpful!
the code was this:

from sys import argv

script, filename = argv
txt = open (filename)

print "Here's your file %r: " % filename
print txt.read()

print "Type the filename again: "
file_again = raw_input("> ")

txt_again = open(file_again)

print txt_again.read()

Peter Otten explained it to me line by line [thanks so much :)] however, I do 
have one more question:
why do I have to create a variable txt_again to assign it to the open 
function and them print the file?
why is it that I can't only write something like open(file_again).read()?


6. Jul 2016 05:22 by __peter__ at web.de:


> lohecn at tuta.io>  wrote:
>
>> hey everyone. this is my first time trying this -- actually, I've been
>> studying python only for some days now, and I'm afraid my questions are
>> going to be reeeeally simple, but I can't seem to understand this piece of
>> code and thus can't move on.
>
> You seem to be talking about
>
> http://learnpythonthehardway.org/book/ex15.html
>
> """
> from sys import argv
>
> script, filename = argv
>
> txt = open(filename)
>
> print "Here's your file %r:" % filename
> print txt.read()
>
> print "Type the filename again:"
> file_again = raw_input("> ")
>
> txt_again = open(file_again)
>
> print txt_again.read()
> """
>
> As others said, always provide the code you are asking about, or if that is
> not possible at least provide a link.
>
>> you probably know the book, so you know that zed always makes us write
>> code so that then we can understand how it works, and it's great, but in
>> this exercise there are just too many new functions and without
>> explanation they are a bit hard to understand... so I'm having trouble
>> with most of the lines here.
>>
>> it's not that I want the full explanation to that code, but since I'm
>> unfamiliar with some of its concepts, I'm just going to tell you all the
>> things that I don't understand (sorry for it being a lot):
>> 1. the need to put script into an estipulation for argv (line 3)
>
> Write a script tmp.py containing
>
> from sys import argv
> print argv
>
> then call it with with one parameter, e. g.
>
> $ python tmp.py somefile.txt
> ['tmp.py', 'somefile.txt']
>
> As you can see argv is a list with two items, the first being "tmp.py", the
> name of the script you are invoking. You are only interested in the second
> one, the filename. The easy way to get that is
>
> filename = argv[1]
>
> the hard way is to use "unpacking"
>
> script, filename = argv
>
> where python will assign one item from the list on the right to every name
> on the left:
>
>>>> items = ["foo", "bar"]
>>>> one, two = items
>>>> one
> 'foo'
>>>> two
> 'bar'
>
> What happens if the number of names on the left doesn't match the number of
> items in the list?
>
>>>> one, two, three = items
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> ValueError: need more than 2 values to unpack
>
> You get an exception. That is why you have to provide the name "script" in
> Zed's example even though you are not actually interested in the script
> name.
>
>> 2. the what is txt and why it has to be used there (line 4)
>
> txt is a file object and
>
>> 3. txt.read() -- which are all new functions(? I dont even know what they
>> are)  (line 7)
>
> read() is a method that here reads the whole file into a string. You use 
> the
> open() function to open a file and usually assign the file object that is
> returned by open to a name. You can freely choose that name. The structure
> is the same for every object, be it a number:
>
> x = 42  # assign a number to x
> y = x + x  # do some arithmetic with x and assign the result to y
> print y  # print the result
>
> a list:
>
> mynumbers = list()  # create a list
> mynumbers.append(42)  # append a number to the list
> print mynumbers  # print the list
>
> or a file:
>
> myfile = open("example.txt")  # open the file example.txt in the current
>                               # working directory. If the file doesn't 
> exist
>                               # you get an error
>
> print "first line:", myfile.readline()  # read the first line and print it
> print "rest of the file:"
> print myfile.read()  # read the rest of the file and print it
>
> myfile.close()  # close the file
>
>> 4. file_again (line 10)
>> 5. txt_again (line 12)
>> and line 14.
>
> 4. and 5. are just a repetition of the first part, with the variation that
> the filename, assigned to file_again is read interactively with raw_input()
> instead of passing it as a commandline argument to the script.
>
> The names used can be freely chosen by the programmer, a script
>
> from sys import argv
>
> red_apple, my_hat = argv
>
> blue_suede_shoes = open(my_hat)
> print blue_suede_shoes.read()
> blue_suede_shoes.close()
>
> would work exactly like the first part of the hard-way example. However,
> picking descriptive names and using them consistently makes it much easier
> for a human reader to understand what's going on.
>
> _______________________________________________
> Tutor maillist  -  > Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

From ahall at autodist.com  Wed Jul  6 13:01:07 2016
From: ahall at autodist.com (Alex Hall)
Date: Wed, 6 Jul 2016 13:01:07 -0400
Subject: [Tutor] Subclassing logging.Handler?
In-Reply-To: <CA+Q8_JcT=0aBH3nGFCzQZv2E38msJPJrrOofu8VzcjV6HN1Xag@mail.gmail.com>
References: <CA+Q8_JcT=0aBH3nGFCzQZv2E38msJPJrrOofu8VzcjV6HN1Xag@mail.gmail.com>
Message-ID: <CA+Q8_Jf-_kRH4j2vYWfNqxYFZ4rrgHME4Z2-jSGuLNTiGAy4KA@mail.gmail.com>

Regarding this project: I've gone ahead and tried a variant of it. I wanted
to log to an HTML file, since those are much easier to look at with a
screen reader and so I could get used to the concepts involved. Here's what
I've come up with so far. I'll ask the question, then paste the code. I'm
getting an error on the self.stream.write line in _open that
"'ADTimedRotatingLogFileHandler' has no attribute stream". If I'm
subclassing TimedRotatingFileHandler, how can it not have stream?

import logging
import logging.handlers as logHandlers
class ADTimedRotatingLogFileHandler(logHandlers.TimedRotatingFileHandler):

    def __init__(self, filename, when, interval, backupCount, title):
        """Most parameters are for the superclass, but 'title' is the title
you want your HTML file to have."""
        super(ADTimedRotatingLogFileHandler, self).__init__(filename, when,
interval, backupCount)
        self._title = title

    def _open(self):
        super(ADTimedRotatingLogFileHandler, self)._open()
        self.stream.write("""<html>
<head>
<title>%s</title>
</head>
<body>
""" %(self._title))

    def close(self):
        self.stream.write("""
</body>
</html>""")
        super(ADTimedRotatingLogFileHandler, self).close()


On Wed, Jul 6, 2016 at 8:32 AM, Alex Hall <ahall at autodist.com> wrote:

> Hey list,
> Another day, another Python experiment. I'm wondering what methods I'd
> have to implement in a custom subclass of logger.Handler.
>
> Currently, the recurring jobs I have written log their events to a file
> each time they run. That's fine, but it doesn't let me keep
> easily-sorted/searched records. Even if I use a size-based log file
> handler, it'll get hard to search. I'm pondering logging to a database as
> well, so that the files will always have the most recent few runs, but the
> database will have everything. That means subclassing logger.Handler.
>
> I found the docs for this, but is emit() the only function I need to
> implement? There are things about i/o locks, formatting, and so on as well.
> How much do I need to do, and how much can I leave up to the super class?
> I'll have to call
> super(MyLogHandler, self).__init__()
> I know, but what else do I have to worry about? To be clear, I'm not
> asking about logging to a database, only what to do to make a Handler
> subclass capable of logging through whatever mechanisms I want. Thanks.
>
> --
> Alex Hall
> Automatic Distributors, IT department
> ahall at autodist.com
>



-- 
Alex Hall
Automatic Distributors, IT department
ahall at autodist.com

From ahall at autodist.com  Wed Jul  6 13:42:57 2016
From: ahall at autodist.com (Alex Hall)
Date: Wed, 6 Jul 2016 13:42:57 -0400
Subject: [Tutor] Subclassing logging.Handler?
In-Reply-To: <CA+Q8_Jf-_kRH4j2vYWfNqxYFZ4rrgHME4Z2-jSGuLNTiGAy4KA@mail.gmail.com>
References: <CA+Q8_JcT=0aBH3nGFCzQZv2E38msJPJrrOofu8VzcjV6HN1Xag@mail.gmail.com>
 <CA+Q8_Jf-_kRH4j2vYWfNqxYFZ4rrgHME4Z2-jSGuLNTiGAy4KA@mail.gmail.com>
Message-ID: <CA+Q8_JcbMN6bLM8ROmXfYqiv0=bfHQxm=7xikZTajAth0O6L3w@mail.gmail.com>

On Wed, Jul 6, 2016 at 1:01 PM, Alex Hall <ahall at autodist.com> wrote:

> Regarding this project: I've gone ahead and tried a variant of it. I
> wanted to log to an HTML file, since those are much easier to look at with
> a screen reader and so I could get used to the concepts involved. Here's
> what I've come up with so far. I'll ask the question, then paste the code.
> I'm getting an error on the self.stream.write line in _open that
> "'ADTimedRotatingLogFileHandler' has no attribute stream". If I'm
> subclassing TimedRotatingFileHandler, how can it not have stream?
>

Again, in case someone is searching for an answer later and finds this
thread: you must assign it.

def _open(self):
    self.stream = super(ADTimedRotatingLogFileHandler, self)._open()

I'm now getting a different error, in close():
TypeError: must be type, not None

I'm not sure what that's about, but at least I now know why I wasn't
getting a stream.

>
> import logging
> import logging.handlers as logHandlers
> class ADTimedRotatingLogFileHandler(logHandlers.TimedRotatingFileHandler):
>
>     def __init__(self, filename, when, interval, backupCount, title):
>         """Most parameters are for the superclass, but 'title' is the
> title you want your HTML file to have."""
>         super(ADTimedRotatingLogFileHandler, self).__init__(filename,
> when, interval, backupCount)
>         self._title = title
>
>     def _open(self):
>         super(ADTimedRotatingLogFileHandler, self)._open()
>         self.stream.write("""<html>
> <head>
> <title>%s</title>
> </head>
> <body>
> """ %(self._title))
>
>     def close(self):
>         self.stream.write("""
> </body>
> </html>""")
>         super(ADTimedRotatingLogFileHandler, self).close()
>
>
> On Wed, Jul 6, 2016 at 8:32 AM, Alex Hall <ahall at autodist.com> wrote:
>
>> Hey list,
>> Another day, another Python experiment. I'm wondering what methods I'd
>> have to implement in a custom subclass of logger.Handler.
>>
>> Currently, the recurring jobs I have written log their events to a file
>> each time they run. That's fine, but it doesn't let me keep
>> easily-sorted/searched records. Even if I use a size-based log file
>> handler, it'll get hard to search. I'm pondering logging to a database as
>> well, so that the files will always have the most recent few runs, but the
>> database will have everything. That means subclassing logger.Handler.
>>
>> I found the docs for this, but is emit() the only function I need to
>> implement? There are things about i/o locks, formatting, and so on as well.
>> How much do I need to do, and how much can I leave up to the super class?
>> I'll have to call
>> super(MyLogHandler, self).__init__()
>> I know, but what else do I have to worry about? To be clear, I'm not
>> asking about logging to a database, only what to do to make a Handler
>> subclass capable of logging through whatever mechanisms I want. Thanks.
>>
>> --
>> Alex Hall
>> Automatic Distributors, IT department
>> ahall at autodist.com
>>
>
>
>
> --
> Alex Hall
> Automatic Distributors, IT department
> ahall at autodist.com
>



-- 
Alex Hall
Automatic Distributors, IT department
ahall at autodist.com

From michael.selik at gmail.com  Wed Jul  6 11:23:04 2016
From: michael.selik at gmail.com (Michael Selik)
Date: Wed, 06 Jul 2016 15:23:04 +0000
Subject: [Tutor] help with exercise 15 of zed shaw's LPTHW
In-Reply-To: <KM-WXgn----0@tuta.io>
References: <KLxUPLY--3-0@tuta.io> <nlif3g$ffs$1@ger.gmane.org>
 <KM-WXgn----0@tuta.io>
Message-ID: <CAGgTfkNaRg6ctL_vTUkuWAH+-tsnEK+833m9XbcQHh_xteiWZg@mail.gmail.com>

On Wed, Jul 6, 2016 at 10:59 AM <lohecn at tuta.io> wrote:

> why do I have to create a variable txt_again to assign it to the open
> function and them print the file?
> why is it that I can't only write something like open(file_again).read()?
>

Good insight. In fact you don't need to create the variable. The code ``data
= open('filename').read()`` will open the file named "filename" in the
current working directory, read it, and assign the data to a variable.

However, many programmers use variables not because they must, but because
good variable names can make code easier to read. Also, doing less stuff on
a line of code can make that code easier to read.

From samuel.moses at mymail.champlain.edu  Wed Jul  6 13:27:32 2016
From: samuel.moses at mymail.champlain.edu (Moses, Samuel)
Date: Wed, 6 Jul 2016 10:27:32 -0700
Subject: [Tutor] error
Message-ID: <CAAv-vb1OPSePsyPbyHRTB=kes94p_TVb=PQ4pzrA0Pu=QDQYLQ@mail.gmail.com>

I am getting an error.  I tired to run the script in wing IDE.

I am getting this error,

"Traceback (most recent call last):
  File "C:\Program Files (x86)\Wing IDE 5.1\bin\wingdb.py", line 822, in
main
    args['firststop'], err, netserver, pwfile_path)
  File "C:\Program Files (x86)\Wing IDE 5.1\bin\wingdb.py", line 649, in
CreateServer
    pwfile_path, internal_modules=tuple(internal_modules))
  File "C:\src\ide\bin\3.2\src/debug/tserver\netserver.pyc", line 922, in
__init__
  File "C:\src\ide\bin\3.2\src/debug/tserver\netserver.pyc", line 2234, in
__PrepareConnectListener
  File "C:\Python32\lib\socket.py", line 94, in __init__
    _socket.socket.__init__(self, family, type, proto, fileno)
socket.error: [Errno 10107] A system call has failed"

I tried printing "Christmas"
It said there was no TCP/IP connection.

Any suggestion would help

Thank you

Samuel Moses

From alan.gauld at yahoo.co.uk  Wed Jul  6 14:33:08 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 6 Jul 2016 19:33:08 +0100
Subject: [Tutor] help with exercise 15 of zed shaw's LPTHW
In-Reply-To: <KM-WXgn----0@tuta.io>
References: <KLxUPLY--3-0@tuta.io> <nlif3g$ffs$1@ger.gmane.org>
 <KM-WXgn----0@tuta.io>
Message-ID: <nljit3$mip$1@ger.gmane.org>

On 06/07/16 15:04, lohecn at tuta.io wrote:

> script, filename = argv
> txt = open (filename)
> 
> print "Here's your file %r: " % filename
> print txt.read()
> 
> print "Type the filename again: "
> file_again = raw_input("> ")
> 
> txt_again = open(file_again)
> print txt_again.read()


> why do I have to create a variable txt_again to assign it to the open 
> function and them print the file?

You don't, and could get away with a single
variable - filename. Like this:

filename = argv[1]
print "Here's your file %r: " % filename
print open(filename).read()

filename = raw_input("Type the filename again: >")
print open(filename).read()

But your book is (I assume) trying to teach you
good practice.

While you could have just printed the result of read directly,
its better not to over complicate code by doing too much in one
line (for a start, its harder to debug) the same variable.
Variables are cheap to create and if given useful names
tell us a lot about the purpose of the code.

In this case it's all a bit trivial, just printing the file
content, but if you were doing more complex processing
storing the file (and data) in variables would be the
best choice.

-- 
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 yahoo.co.uk  Wed Jul  6 14:39:31 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 6 Jul 2016 19:39:31 +0100
Subject: [Tutor] error
In-Reply-To: <CAAv-vb1OPSePsyPbyHRTB=kes94p_TVb=PQ4pzrA0Pu=QDQYLQ@mail.gmail.com>
References: <CAAv-vb1OPSePsyPbyHRTB=kes94p_TVb=PQ4pzrA0Pu=QDQYLQ@mail.gmail.com>
Message-ID: <nljj92$s41$1@ger.gmane.org>

On 06/07/16 18:27, Moses, Samuel wrote:
> I am getting an error.  I tired to run the script in wing IDE.
> 

Without the accompanying code we can only guess.

> I am getting this error,
> 
> "Traceback (most recent call last):
>   File "C:\Program Files (x86)\Wing IDE 5.1\bin\wingdb.py", line 822, in
> main
>     args['firststop'], err, netserver, pwfile_path)
>   File "C:\Program Files (x86)\Wing IDE 5.1\bin\wingdb.py", line 649, in
> CreateServer
>     pwfile_path, internal_modules=tuple(internal_modules))
>   File "C:\src\ide\bin\3.2\src/debug/tserver\netserver.pyc", line 922, in
> __init__
>   File "C:\src\ide\bin\3.2\src/debug/tserver\netserver.pyc", line 2234, in
> __PrepareConnectListener
>   File "C:\Python32\lib\socket.py", line 94, in __init__
>     _socket.socket.__init__(self, family, type, proto, fileno)
> socket.error: [Errno 10107] A system call has failed"

Have you checked that you have the requisite permissions? That the
socket you are connecting to exists? If its a system call error the
problem is most likely in your environment rather than your code.

But check the values you pass into socket. Print them out
to check they are what you (and Python) expect...

> I tried printing "Christmas"

I have no idea what that means. Literally putting

print "Christmas"

in your code probably wouldn't help so I assume you
did something else?

> It said there was no TCP/IP connection.

What said? Was it another error trace? Or something 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 badouglas at gmail.com  Wed Jul  6 15:35:16 2016
From: badouglas at gmail.com (bruce)
Date: Wed, 6 Jul 2016 15:35:16 -0400
Subject: [Tutor] decorators -- treat me like i'm 6.. what are they.. why are
 they?
Message-ID: <CAP16ngoczcMTxGF4JUUU7oXZ=wx8SLPRG1Yz=Q2FGUn+jQGvkQ@mail.gmail.com>

Hi.

Saw the decorator thread earlier.. didn't want to pollute it. I know, I
could google!

But, what are decorators, why are decorators? who decided you needed them!

Thanks!

From ahall at autodist.com  Wed Jul  6 16:56:47 2016
From: ahall at autodist.com (Alex Hall)
Date: Wed, 6 Jul 2016 16:56:47 -0400
Subject: [Tutor] decorators -- treat me like i'm 6.. what are they.. why
 are they?
In-Reply-To: <CAP16ngoczcMTxGF4JUUU7oXZ=wx8SLPRG1Yz=Q2FGUn+jQGvkQ@mail.gmail.com>
References: <CAP16ngoczcMTxGF4JUUU7oXZ=wx8SLPRG1Yz=Q2FGUn+jQGvkQ@mail.gmail.com>
Message-ID: <CA+Q8_JcKrqwmcphhAZfOdgL325nRQMmnBEC0i2_1Ejz0=k72Yw@mail.gmail.com>

On Wed, Jul 6, 2016 at 3:35 PM, bruce <badouglas at gmail.com> wrote:

> Hi.
>
> Saw the decorator thread earlier.. didn't want to pollute it. I know, I
> could google!
>
> But, what are decorators, why are decorators? who decided you needed them!
>

They're functions that modify the decorated function. If I make a function
that performs a task, I might decorate with a logging function:

@logThis
def doSomething():
  #do stuff

The logThis decorator could log the run, or modify the doSomething output,
or do any number of tasks. To get that extra functionality, I need only
decorate my own function. I see these a lot in Flask, a web framework,
where they are used to define what parts of your website are handled by
what functions, for instance. Basically, they let you extend what your
functions do without needing to subclass anything.

>
> Thanks!
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Alex Hall
Automatic Distributors, IT department
ahall at autodist.com

From ahall at autodist.com  Wed Jul  6 17:25:58 2016
From: ahall at autodist.com (Alex Hall)
Date: Wed, 6 Jul 2016 17:25:58 -0400
Subject: [Tutor] decorators -- treat me like i'm 6.. what are they.. why
 are they?
In-Reply-To: <CA+Q8_JcKrqwmcphhAZfOdgL325nRQMmnBEC0i2_1Ejz0=k72Yw@mail.gmail.com>
References: <CAP16ngoczcMTxGF4JUUU7oXZ=wx8SLPRG1Yz=Q2FGUn+jQGvkQ@mail.gmail.com>
 <CA+Q8_JcKrqwmcphhAZfOdgL325nRQMmnBEC0i2_1Ejz0=k72Yw@mail.gmail.com>
Message-ID: <CA+Q8_JcO24Ypwdcvcv1TD+-i_FRHPy1O+Addxv5drnP2cPuJjg@mail.gmail.com>

On Wed, Jul 6, 2016 at 4:56 PM, Alex Hall <ahall at autodist.com> wrote:

>
>
> On Wed, Jul 6, 2016 at 3:35 PM, bruce <badouglas at gmail.com> wrote:
>
>> Hi.
>>
>> Saw the decorator thread earlier.. didn't want to pollute it. I know, I
>> could google!
>>
>> But, what are decorators, why are decorators? who decided you needed them!
>>
>
> I thought of an example that may help. It's not a great example, but here
goes.

Say you own a bakery, and you employ Joe and me. You task me with taking
cookies from the kitchen and putting them in the display case in the
service area, which I do well. The problem is that I don't know what looks
appealing and what doesn't, so I keep putting cookies out that don't look
great. You can't teach something like that, it's just something you know.

Since you can't modify me to do my task in the way you want, you grab Joe
and have him help me. Instead of putting all the cookies out, I now have
Joe checking me before I place each one. Joe knows appealing, so is good at
this, but he's also usually busy up front so can't carry the cookies out
from the kitchen like I can.

Joe is the decorator, and I'm the function being decorated. Since I do my
task well, but lack a component you want, and since that component would be
hard to program, you find an existing version of the component (Joe) and
tell us to work together. Joe can modify my output before I return it,
letting him filter the appealing cookies out while I do the work of
carrying them up and setting out the ones Joe doesn't tell me to reject.
Hopefully this makes some sense.

> They're functions that modify the decorated function. If I make a function
> that performs a task, I might decorate with a logging function:
>
> @logThis
> def doSomething():
>   #do stuff
>
> The logThis decorator could log the run, or modify the doSomething output,
> or do any number of tasks. To get that extra functionality, I need only
> decorate my own function. I see these a lot in Flask, a web framework,
> where they are used to define what parts of your website are handled by
> what functions, for instance. Basically, they let you extend what your
> functions do without needing to subclass anything.
>
>>
>> Thanks!
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>
>
>
> --
> Alex Hall
> Automatic Distributors, IT department
> ahall at autodist.com
>



-- 
Alex Hall
Automatic Distributors, IT department
ahall at autodist.com

From samuel.moses at mymail.champlain.edu  Wed Jul  6 14:34:36 2016
From: samuel.moses at mymail.champlain.edu (Moses, Samuel)
Date: Wed, 6 Jul 2016 11:34:36 -0700
Subject: [Tutor] OS and Windows version
Message-ID: <CAAv-vb1dcphs_jFktXeUQzQ8bBrPothNxyPsy9hjQrmOFAntrg@mail.gmail.com>

Mine

OS: Windows

Windows version: 8.1

Python 3.2

Wing IDE: 15.1

Sam

From alan.gauld at yahoo.co.uk  Wed Jul  6 17:34:47 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 6 Jul 2016 22:34:47 +0100
Subject: [Tutor] decorators -- treat me like i'm 6.. what are they.. why
 are they?
In-Reply-To: <CAP16ngoczcMTxGF4JUUU7oXZ=wx8SLPRG1Yz=Q2FGUn+jQGvkQ@mail.gmail.com>
References: <CAP16ngoczcMTxGF4JUUU7oXZ=wx8SLPRG1Yz=Q2FGUn+jQGvkQ@mail.gmail.com>
Message-ID: <nljthm$vde$1@ger.gmane.org>

On 06/07/16 20:35, bruce wrote:

> Saw the decorator thread earlier.. didn't want to pollute it. I know, I
> could google!
> 
> But, what are decorators, why are decorators? who decided you needed them!

decorators are things that modify functions in standard ways.
Specifically they are functions that act on functions.
Mostly people think of them as being the thing that comes after an @
sign, but in fact they are just functions but with a bit of syntactic
sugar to make them more readable.

You don't really *need* them as a feature, but if you have
the ability to treat functions as values they are a useful
technique.

Most Python programmers don't implement decorators they just
use the standard ones. But as the thread showed implementing
them is not too difficult once you get happy with the idea
of passing functions around as arguments to other functions.

As to who suggested them you'd need to go back through the
PEPs to see who first suggested it, and then maybe more to see
who's idea finally got accepted. I think it was in Python 2.5.

-- 
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 yahoo.co.uk  Wed Jul  6 17:39:50 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 6 Jul 2016 22:39:50 +0100
Subject: [Tutor] OS and Windows version
In-Reply-To: <CAAv-vb1dcphs_jFktXeUQzQ8bBrPothNxyPsy9hjQrmOFAntrg@mail.gmail.com>
References: <CAAv-vb1dcphs_jFktXeUQzQ8bBrPothNxyPsy9hjQrmOFAntrg@mail.gmail.com>
Message-ID: <nljtr5$479$1@ger.gmane.org>

On 06/07/16 19:34, Moses, Samuel wrote:
> Mine
> 
> OS: Windows
> Windows version: 8.1
> 
> Python 3.2
> Wing IDE: 15.1

Thanks for the extra info but it doesn't help much with
your problem since we still don't know what your code
does nor how your environment is set up.

BTW Can you connect to your target socket using telnet? (Use
a CMD console)If you get an error message there you probably
can't connect from Python either.

Finally you could try running the script outside Wing. IDEs can
do all sorts of weird stuff to programs. Its always worth a try
running it using the vanilla Python interpreter.

-- 
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  Wed Jul  6 20:33:23 2016
From: dyoo at hashcollision.org (Danny Yoo)
Date: Wed, 6 Jul 2016 17:33:23 -0700
Subject: [Tutor] decorators -- treat me like i'm 6.. what are they.. why
 are they?
In-Reply-To: <nljthm$vde$1@ger.gmane.org>
References: <CAP16ngoczcMTxGF4JUUU7oXZ=wx8SLPRG1Yz=Q2FGUn+jQGvkQ@mail.gmail.com>
 <nljthm$vde$1@ger.gmane.org>
Message-ID: <CAGZAPF7C8cs+6ZN08mBQLuXmW=RqOxKubXgSwiiN2NoU7wNRwA@mail.gmail.com>

> As to who suggested them you'd need to go back through the
> PEPs to see who first suggested it, and then maybe more to see
> who's idea finally got accepted. I think it was in Python 2.5.


Hi Bruce,


Yes, it happened back around 2003:

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

Decorators are "syntactic sugar" in the sense that they can be
rewritten in terms of more primitive parts of the language (function
calls).  If you already know about functions that work on functions,
then you know what decorators are.

However, if you haven't seen the concept of functions that take
functions as input, and you want to talk about that, feel free to ask
questions!  It would likely be a "fun" discussion to have.

From dyoo at hashcollision.org  Wed Jul  6 20:37:55 2016
From: dyoo at hashcollision.org (Danny Yoo)
Date: Wed, 6 Jul 2016 17:37:55 -0700
Subject: [Tutor] error
In-Reply-To: <nljj92$s41$1@ger.gmane.org>
References: <CAAv-vb1OPSePsyPbyHRTB=kes94p_TVb=PQ4pzrA0Pu=QDQYLQ@mail.gmail.com>
 <nljj92$s41$1@ger.gmane.org>
Message-ID: <CAGZAPF4eEU97_39vK72eUzBzYq=ZtQssGVwpEt_qPpKWGXLdrA@mail.gmail.com>

>
> Have you checked that you have the requisite permissions? That the
> socket you are connecting to exists? If its a system call error the
> problem is most likely in your environment rather than your code.
>


That particular error is from Windows.  One common cause for it is a
network firewall, which normally is great because at least it's
working as a first line of defense.  If that's the case, you probably
want to tell your firewall to make an exception for your program.

From steve at pearwood.info  Wed Jul  6 22:18:43 2016
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 7 Jul 2016 12:18:43 +1000
Subject: [Tutor] decorators -- treat me like i'm 6.. what are they.. why
 are they?
In-Reply-To: <CAP16ngoczcMTxGF4JUUU7oXZ=wx8SLPRG1Yz=Q2FGUn+jQGvkQ@mail.gmail.com>
References: <CAP16ngoczcMTxGF4JUUU7oXZ=wx8SLPRG1Yz=Q2FGUn+jQGvkQ@mail.gmail.com>
Message-ID: <20160707021843.GW27919@ando.pearwood.info>

On Wed, Jul 06, 2016 at 03:35:16PM -0400, bruce wrote:
> Hi.
> 
> Saw the decorator thread earlier.. didn't want to pollute it. I know, 
> I could google!
> 
> But, what are decorators, why are decorators? who decided you needed 
> them!

Sometimes you find yourself writing many functions (or methods) that 
have bits in common.

For example, you might have a bunch of mathematical functions that all 
start off with the same boring code "check that the argument x is a 
number, raise an exception if it isn't". Sure, it's only two or three 
lines, but if you've got twenty functions to write, you have to write 
those same lines twenty times. And then if you decide to change the 
error message, or change the way you check something is a number, you 
have to do that in twenty places.

A decorator let's you factor out that common code into a single place, 
so you only need to make changes to *one* place instead of twenty 
separate functions. You still have to apply the decorator to each of the 
functions, but that's only once line. Besides, a decorator is not really 
about cutting back the number of lines of code (although it is nice when 
that happens) as it is about moving common code to one place.

def verify_numeric_argument(func):
    """Decorator that checks the argument to a function is a number."""
    @functools.wraps(func)
    def inner(x):
        if isinstance(x, numbers.Number):
            return func(x)
        else:
            kind = type(x).__name__
            raise TypeError("expected a number, but got %s" % kind)
    return inner


@verify_numeric_argument
def sinc(x):
    if x == 0:
        return 1.0
    else:
        return math.sin(x)/x



Obviously you wouldn't bother if you're only going to do it *once*. 
There's a bunch of overhead involved in writing a decorator, usually 
about five or six lines of code per decorator. The rule of thumb I use 
is that if I have one or two functions with the same, common, chunk of 
code, I probably wouldn't bother; if I have three functions, I might, 
and if I have four or more, then I probably will.

But as I said, it's not really about saving lines of code. It's about 
keeping code that belongs together in one place, and about recognising 
when functions repeat the same structure. If you have a bunch of 
functions that look like this:

def function(arguments):
    boring boilerplate that is the same each time
    interesting bit that is different each time
    more boring boilingplate
    return result

then this is a great candidate for a decorator: move the boring 
boilerplate into the decorator, then turn the functions into this:

@apply_boilerplate
def function(arguments):
    interesting bit that is different each time
    return result


Doesn't that look better? That's the purpose of the decorator: move the 
boring bits, or sometimes the hard, complicated bits, away so you can 
focus on the interesting bits. Depending on just how boring that 
boilerplate is, I might even do it for ONE function, just to get it out 
of the way.


-- 
Steve

From alan.gauld at yahoo.co.uk  Thu Jul  7 04:36:56 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 7 Jul 2016 09:36:56 +0100
Subject: [Tutor] decorators -- treat me like i'm 6.. what are they.. why
 are they?
In-Reply-To: <CAP16ngoczcMTxGF4JUUU7oXZ=wx8SLPRG1Yz=Q2FGUn+jQGvkQ@mail.gmail.com>
References: <CAP16ngoczcMTxGF4JUUU7oXZ=wx8SLPRG1Yz=Q2FGUn+jQGvkQ@mail.gmail.com>
Message-ID: <nll4b7$5i1$1@ger.gmane.org>

On 06/07/16 20:35, bruce wrote:

> But, what are decorators, why are decorators? who decided you needed them!

Thinking about this a little wider than Python.

Decorators are a standard software design pattern and were
first(?) formally documented in the famous book known as the
"Gang of Four" (GoF) but actually called "Design Patterns"
published in 1995.

But the GoF decorator pattern is quite different in the way
it is implemented (using object inheritance) from Python's
functional decorators. But the intent is the same - to add
common functionality to another object.

I think that's probably the earliest use of "decorator" in a
computing context.

-- 
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 bkd69ster at gmail.com  Fri Jul  8 09:22:46 2016
From: bkd69ster at gmail.com (Bruce Dykes)
Date: Fri, 8 Jul 2016 09:22:46 -0400
Subject: [Tutor] Counting and grouping dictionary values in Python 2.7
Message-ID: <CAE3hSEq7rPAzxLweZBrRPe7bC4-jeABqiJUDB9zkxr70+1J-bA@mail.gmail.com>

I'm compiling application logs from a bunch of servers, reading the log
entries, parsing each log entry into a dictionary, and compiling all the
log entries into a single list of dictionaries. At present, all I'm doing
with it is writing the list of dictionaries to a .csv file, and to date,
we've been able to get by doing some basic analysis by simply using grep
and wc, but I need to do more with it now.

Here's what the data structures look like:

NY = ['BX01','BX02','BK01','MN01','SI01']
NJ = ['NW01','PT01','PT02']
CT = ['ST01','BP01','NH01']

sales = [
{'store':'store','date':'date','time':'time','state':'state',transid':'transid','product':'product','price':'price'},
{'store':'BX01','date':'8','time':'08:55','state':'NY',transid':'387','product':'soup','price':'2.59'},
{'store':'NW01','date':'8','time':'08:57','state':'NJ',transid':'24','product':'apples','price':'1.87'},
{'store':'BX01','date':'8','time':'08:56','state':'NY',transid':'387','product':'crackers','price':'3.44'}]

The first group of list with the state abbreviations is there to add the
state information to the compiled log, as it's not included in the
application log. The first dictionary in the list, with the duplicated key
names in the value field is there to provide a header line as the first
line in the compiled .csv file.

Now, what I need to do with this arbitrarily count and total the values in
the dictionaries, ie the total amount and number of items for transaction
id 387, or the total number of crackers sold in NJ stores. I think the
collections library has the functions I need, but I haven't been able to
grok the examples uses I've seen online. Likewise, I know I could build a
lot of what I need using regex and lists, etc, but if Python 2.7 already
has the blocks there to be used, well let's use the blocks then.

Also, is there any particular advantage to pickling the list and having two
files, one, the pickled file to be read as a data source, and the .csv file
for portability/readability, as opposed to just a single .csv file that
gets reparsed by the reporting script?

Thanks in advance
bkd

From SylviaDeAguiar at alphapoint.co.jp  Thu Jul  7 23:01:52 2016
From: SylviaDeAguiar at alphapoint.co.jp (Sylvia DeAguiar)
Date: Thu, 8 Jul 2016 03:01:52 +0000
Subject: [Tutor] (no subject)
Message-ID: <B070AACC-A518-40EE-B471-46E60D7B5AB5@alphapoint.co.jp>


http://point.gendelmangroup.com/Sylvia_DeAguiar


Sylvia Deaguiar
Sent from my iPhone

From alan.gauld at yahoo.co.uk  Fri Jul  8 13:33:24 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 8 Jul 2016 18:33:24 +0100
Subject: [Tutor] Counting and grouping dictionary values in Python 2.7
In-Reply-To: <CAE3hSEq7rPAzxLweZBrRPe7bC4-jeABqiJUDB9zkxr70+1J-bA@mail.gmail.com>
References: <CAE3hSEq7rPAzxLweZBrRPe7bC4-jeABqiJUDB9zkxr70+1J-bA@mail.gmail.com>
Message-ID: <nloo53$66n$1@ger.gmane.org>

On 08/07/16 14:22, Bruce Dykes wrote:

> with it is writing the list of dictionaries to a .csv file, and to date,
> we've been able to get by doing some basic analysis by simply using grep
> and wc, but I need to do more with it now.

I'm a big fan of using the right tool for the job.
If you got your data in CSV have you considered using a
spreadsheet to read the data and analyse it? They have lots
of formulae and stats functions built in and can do really
cool graphs etc and can read csv files natively.

Python might be a better tool if you want regular identical reports, say
on a daily basis, but for ad-hoc analysis, or at least till you know
exactly what you need, Excel or Calc are possibly better tools.

> Also, is there any particular advantage to pickling the list and having two
> files, one, the pickled file to be read as a data source, and the .csv file

Probably not, the cost of converting the strings in the csv to objects
is not that high unless you have huge volumes to manage(ie millions of
records).


-- 
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 beachkidken at gmail.com  Sat Jul  9 10:22:16 2016
From: beachkidken at gmail.com (Ken G.)
Date: Sat, 9 Jul 2016 10:22:16 -0400
Subject: [Tutor] Quote and double quotes opens up File Explorer in Windows 10
Message-ID: <57810898.5030400@gmail.com>

Hi: In gradually moving over my Python programs (2.7.6) to Windows 10 
and using Geany 1.27 to modify or write up a program there, it is noted 
that whenever I typed in a quote (') or double quote ("), Windows 10 
File Explorer opens up. I end up closing it by typing ALT-F4 to resume 
typing as before. Is there a way to prevent the File Explorer from 
opening up whenever I use a quote or double quote? Is there another 
key(s) that does weird thing in Windows 10? Thanks.

Ken


From eryksun at gmail.com  Sat Jul  9 13:02:12 2016
From: eryksun at gmail.com (eryk sun)
Date: Sat, 9 Jul 2016 17:02:12 +0000
Subject: [Tutor] Quote and double quotes opens up File Explorer in
 Windows 10
In-Reply-To: <57810898.5030400@gmail.com>
References: <57810898.5030400@gmail.com>
Message-ID: <CACL+1auFdE1t1wtBr_+S-0-C_N9ZmYF8sxxAHDoB6xCMT4OxGQ@mail.gmail.com>

On Sat, Jul 9, 2016 at 2:22 PM, Ken G. <beachkidken at gmail.com> wrote:
> Hi: In gradually moving over my Python programs (2.7.6) to Windows 10 and
> using Geany 1.27 to modify or write up a program there, it is noted that
> whenever I typed in a quote (') or double quote ("), Windows 10 File
> Explorer opens up. I end up closing it by typing ALT-F4 to resume typing as
> before. Is there a way to prevent the File Explorer from opening up whenever
> I use a quote or double quote? Is there another key(s) that does weird thing
> in Windows 10? Thanks.

The single/double quote key isn't a standard hotkey in any version of
Windows. That would be insane. If this is just happening in Geany,
check its keybindings preferences. Otherwise, check that you're using
the right keyboard layout and that you don't have any programs (or
malware) that's registering a global hotkey.

For example, here's a simple script that registers the single quote
(US keyboard layout) as a global hotkey to open the desktop in
Explorer:

    #! /usr/bin/python3
    import os
    import ctypes
    from ctypes import wintypes

    user32 = ctypes.WinDLL('user32')

    WM_HOTKEY = 0x0312
    MOD_NOREPEAT = 0x4000
    VK_OEM_7 = 0xDE # US layout, single/double quote

    hotkey_id = 1
    if user32.RegisterHotKey(None, hotkey_id, MOD_NOREPEAT, VK_OEM_7):
        print('Hotkey "\'" registered.')
        msg = wintypes.MSG()
        count = 0
        while (count < 3 and
               user32.GetMessageW(ctypes.byref(msg), None, 0, 0)):
            if msg.message == WM_HOTKEY and msg.wParam == hotkey_id:
                count += 1
                print('Hotkey received.')
                os.startfile('shell:Desktop')

From B150612244 at outlook.com  Sat Jul  9 22:23:23 2016
From: B150612244 at outlook.com (Chan Cheuk)
Date: Sun, 10 Jul 2016 02:23:23 +0000
Subject: [Tutor] Some Python difficulties ..
Message-ID: <SG2PR03MB1805C4EE7E569A487B5F7BC48D3E0@SG2PR03MB1805.apcprd03.prod.outlook.com>

Dear all,


I would like to know whether my designed Python program below for Linux route command could not run and show the output onto the textarea that I planned originally.


The source code is:


#!/usr/bin/python
# lb        => Label
# btn       => button
# tb        => textbox / entry
# txtarea   => multiline text
# cb        => Checkbox
# rb        => radiobutton
# e.g. lb_ipaddress, btn_start, tb_output

from Tkinter import *

root = Tk()
root.title("netcat(nc) GUI")

option_a = IntVar()
option_b = IntVar()
option_c = IntVar()
option_d = IntVar()

def startfping():
    print "Start nc button clicked!"
    fpingcommand = command_gen()
    print "\tnetcat command: " + nccommand
    commandresult = runcommand()
    print "\tCommand output: " + commandresult

def command_gen():
    print "Generate the netcat command details!"
    command = "netcat "

    print "option a: " + str(option_a.get())
    if option_a.get():
        command = command + "-a "

    print "option b: " + str(option_b.get())
    if option_b.get():
        command = command + "-c 1 "

    print "option c: " + str(option_c.get())
    if option_c.get():
        command = command + "-q "

    command = command + tb_ipaddress.get()

    print "option d: " + str(option_d.get())
    if option_d.get():
        command = "netcat -h"

    result = command
    return result

def runcommand():
    print "Run command and get return!"
    result = "Get it"
    return result

lb_ipaddress = Label(root, text="IP Address(s):", fg="orange", justify=LEFT)
lb_ipaddress.grid(row=0, column=0, padx=2, pady=5, sticky=W)

tb_ipaddress = Entry(root, width=40, bd=5)
tb_ipaddress.grid(row=0, column=1, columnspan=3, padx=5, pady=5)

cb_option_a = Checkbutton(root, text = "Telnet details",variable=option_a, justify=LEFT)
cb_option_a.grid(row=1, column=0, columnspan=2, padx=5, pady=5, sticky=W)
# option a => -a

cb_option_b = Checkbutton(root, text="Port scanning", variable=option_b, justify=LEFT)
cb_option_b.grid(row=1, column=2, columnspan=2, padx=5, pady=5, sticky=W)
# option b => -c 1

cb_option_c = Checkbutton(root, text="Remote Shell/Backdoor", variable=option_c, justify=LEFT)
cb_option_c.grid(row=2, column=0, columnspan=2, padx=5, pady=5, sticky=W)
# option c => -q

cb_option_d = Checkbutton(root, text="Reverse Shells", variable=option_d, justify=LEFT)
cb_option_d.grid(row=2, column=2, columnspan=2, padx=5 , pady=5, sticky=W)
# option d => -h (but exclude all other options and IP address)

btn_run = Button(root, width = 10, text="Run!",justify=RIGHT, command=startfping)
btn_run.grid(row=3, column=3, padx=5, pady=5, stick=E)

lb_commandoutput = Label(root, text="Command Output:", fg="red", justify=LEFT)
lb_commandoutput.grid(row=4, column=0, padx=2, pady=0)

txtarea_output = Text(root, height=10, width=60)
txtarea_output.grid(row=5, column=0, columnspan=4, padx=10, pady=10)

root.mainloop()


Thank you for your kindly attention if you tell me how to fix it :'(


From __peter__ at web.de  Sun Jul 10 05:00:40 2016
From: __peter__ at web.de (Peter Otten)
Date: Sun, 10 Jul 2016 11:00:40 +0200
Subject: [Tutor] Some Python difficulties ..
References: <SG2PR03MB1805C4EE7E569A487B5F7BC48D3E0@SG2PR03MB1805.apcprd03.prod.outlook.com>
Message-ID: <nlt2rr$h50$1@ger.gmane.org>

Chan Cheuk wrote:

> I would like to know whether my designed Python program below for Linux
> route command could not run and show the output onto the textarea that I
> planned originally.

When you run the script and click on the Run! button, what do you see?
Read the traceback carefully and come back for more hints if you cannot fix 
the problem yourself.

Look at the subprocess module 

https://docs.python.org/2.7/library/subprocess.html

for ways to run an external command and capture its output in a string 
variable.

Once the script works as desired except that it prints to the command line 
via print statements rather than into the Text widget search your tkinter 
documentation for a way to insert() text into the widget and replace the 
print statements with these method calls.

> The source code is:
> 
> 
> #!/usr/bin/python
> # lb        => Label
> # btn       => button
> # tb        => textbox / entry
> # txtarea   => multiline text
> # cb        => Checkbox
> # rb        => radiobutton
> # e.g. lb_ipaddress, btn_start, tb_output
> 
> from Tkinter import *
> 
> root = Tk()
> root.title("netcat(nc) GUI")
> 
> option_a = IntVar()
> option_b = IntVar()
> option_c = IntVar()
> option_d = IntVar()
> 
> def startfping():
>     print "Start nc button clicked!"
>     fpingcommand = command_gen()
>     print "\tnetcat command: " + nccommand
>     commandresult = runcommand()
>     print "\tCommand output: " + commandresult
> 
> def command_gen():
>     print "Generate the netcat command details!"
>     command = "netcat "
> 
>     print "option a: " + str(option_a.get())
>     if option_a.get():
>         command = command + "-a "
> 
>     print "option b: " + str(option_b.get())
>     if option_b.get():
>         command = command + "-c 1 "
> 
>     print "option c: " + str(option_c.get())
>     if option_c.get():
>         command = command + "-q "
> 
>     command = command + tb_ipaddress.get()
> 
>     print "option d: " + str(option_d.get())
>     if option_d.get():
>         command = "netcat -h"
> 
>     result = command
>     return result
> 
> def runcommand():
>     print "Run command and get return!"
>     result = "Get it"
>     return result
> 
> lb_ipaddress = Label(root, text="IP Address(s):", fg="orange",
> justify=LEFT) lb_ipaddress.grid(row=0, column=0, padx=2, pady=5, sticky=W)
> 
> tb_ipaddress = Entry(root, width=40, bd=5)
> tb_ipaddress.grid(row=0, column=1, columnspan=3, padx=5, pady=5)
> 
> cb_option_a = Checkbutton(root, text = "Telnet details",variable=option_a,
> justify=LEFT) cb_option_a.grid(row=1, column=0, columnspan=2, padx=5,
> pady=5, sticky=W)
> # option a => -a
> 
> cb_option_b = Checkbutton(root, text="Port scanning", variable=option_b,
> justify=LEFT) cb_option_b.grid(row=1, column=2, columnspan=2, padx=5,
> pady=5, sticky=W)
> # option b => -c 1
> 
> cb_option_c = Checkbutton(root, text="Remote Shell/Backdoor",
> variable=option_c, justify=LEFT) cb_option_c.grid(row=2, column=0,
> columnspan=2, padx=5, pady=5, sticky=W)
> # option c => -q
> 
> cb_option_d = Checkbutton(root, text="Reverse Shells", variable=option_d,
> justify=LEFT) cb_option_d.grid(row=2, column=2, columnspan=2, padx=5 ,
> pady=5, sticky=W)
> # option d => -h (but exclude all other options and IP address)
> 
> btn_run = Button(root, width = 10, text="Run!",justify=RIGHT,
> command=startfping) btn_run.grid(row=3, column=3, padx=5, pady=5, stick=E)
> 
> lb_commandoutput = Label(root, text="Command Output:", fg="red",
> justify=LEFT) lb_commandoutput.grid(row=4, column=0, padx=2, pady=0)
> 
> txtarea_output = Text(root, height=10, width=60)
> txtarea_output.grid(row=5, column=0, columnspan=4, padx=10, pady=10)
> 
> root.mainloop()
> 
> 
> Thank you for your kindly attention if you tell me how to fix it :'(
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor



From steve at pearwood.info  Sun Jul 10 05:16:03 2016
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 10 Jul 2016 19:16:03 +1000
Subject: [Tutor] Some Python difficulties ..
In-Reply-To: <SG2PR03MB1805C4EE7E569A487B5F7BC48D3E0@SG2PR03MB1805.apcprd03.prod.outlook.com>
References: <SG2PR03MB1805C4EE7E569A487B5F7BC48D3E0@SG2PR03MB1805.apcprd03.prod.outlook.com>
Message-ID: <20160710091556.GF27919@ando.pearwood.info>

On Sun, Jul 10, 2016 at 02:23:23AM +0000, Chan Cheuk wrote:
> Dear all,
> 
> 
> I would like to know whether my designed Python program below for 
> Linux route command could not run and show the output onto the 
> textarea that I planned originally.

Did you try running it? What happened?

If you run your code from a shell, so you can watch any error messages 
that are generated, you will see this error whenever you click the Run 
button:


Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/lib-tk/Tkinter.py", line 1410, in 
__call__
    return self.func(*args)
  File "netcat.py", line 14, in startfping
    print "\tnetcat command: " + nccommand
NameError: global name 'nccommand' is not defined


> def startfping():
>     print "Start nc button clicked!"
>     fpingcommand = command_gen()
>     print "\tnetcat command: " + nccommand

Where is nccommand defined?

>     commandresult = runcommand()

How does runcommand() know what command to run?



-- 
Steve

From nitinchandra1 at gmail.com  Mon Jul 11 05:18:40 2016
From: nitinchandra1 at gmail.com (nitin chandra)
Date: Mon, 11 Jul 2016 14:48:40 +0530
Subject: [Tutor] Python WATable & DB
Message-ID: <CAFSKaezi2SX8sooPtTy73RGmX333VpxmpVWSHKfdTp3BymrTTw@mail.gmail.com>

Hi All,

Any body got experience in WATable + passing data from DB to JS / json
... and if it is stretching it a bit .. has done it with python.

Also, how do I pass link of employee images/photos.

I just posted the part of  JS , which I believe is concerned with data
to be displayed in the table.

Really appreciate ... so close and .... still some way to go to insert DB.

Thanks

Nitin

==============================

<script type="text/javascript">
        $(document).ready( function() {
                var waTable = $('#example2').WATable({
                //data: generateSampleData(100), //Initiate with data
if you already have it
                debug:false,                //Prints some debug info to console
                dataBind: true,             //Auto-updates table when
changing data row values. See example below. (Note. You need a column
with the 'unique' property)
                pageSize: 20,                //Initial pagesize
                pageSizePadding: true,      //Pads with empty rows
when pagesize is not met
                transition: 'scroll',       //Type of transition when
paging (bounce, fade, flip, rotate, scroll, slide).Requires
https://github.com/daneden/animate.css.
                //transitionDuration: 0.2,    //Duration of transition
in seconds.
                filter: true,               //Show filter fields
                sorting: true,              //Enable sorting
                sortEmptyLast:true,         //Empty values will be shown last
                //columnPicker: true,         //Show the columnPicker button
                pageSizes: [1,5,10,20,200],  //Set custom pageSizes.
Leave empty array to hide button.
                hidePagerOnEmpty: true,     //Removes the pager if
data is empty.
                //checkboxes: true,           //Make rows checkable.
(Note. You need a column with the 'unique' property)
                checkAllToggle:true,        //Show the check-all toggle
                preFill: true,              //Initially fills the
table with empty rows (as many as the pagesize).
                //url: '/someWebservice'    //Url to a webservice if
not setting data manually as we do in this example
                //urlData: { report:1 }     //Any data you need to
pass to the webservice
                //urlPost: true             //Use POST httpmethod to
webservice. Default is GET.
                types: {                    //If you want, you can
supply some properties that will be applied for specific data types.
                    string: {
                        //filterTooltip: "Giggedi..."    //What to say
in tooltip when hoovering filter fields. Set false to remove.
                        //placeHolder: "Type here..."    //What to say
in placeholder filter fields. Set false for empty.
                    },
                    number: {
                        decimals: 1   //Sets decimal precision for float types
                    },
                    bool: {
                        //filterTooltip: false
                    },
                    date: {
                      utc:false,            //Show time as universal
time, ie without timezones.
                      format: 'dd/MM/yyyy',   //The format. See all
possible formats here http://arshaw.com/xdate/#Formatting.
                      datePicker: true      //Requires "Datepicker for
Bootstrap" plugin (http://www.eyecon.ro/bootstrap-datepicker).
                    }
                },

                tableCreated: function(data) {    //Fires when the
table is created / recreated. Use it if you want to manipulate the
table in any way.
                    console.log('table created'); //data.table holds
the html table element.
                    console.log(data);            //'this' keyword
also holds the html table element.
                },
                rowClicked: function(data) {      //Fires when a row
or anything within is clicked (Note. You need a column with the
'unique' property).
                    console.log('row clicked');   //data.event holds
the original jQuery event.
                                                  //data.row holds the
underlying row you supplied.
                                                  //data.index holds
the index of row in rows array (Useful when you want to remove the
row)
                                                  //data.column holds
the underlying column you supplied.
                                                  //data.checked is
true if row is checked. (Set to false/true to have it
unchecked/checked)
                                                  //'this' keyword
holds the clicked element.

                    //Removes the row if user clicked on the column
called 'remove'.
                    if (data.column.column == "remove") {
                        data.event.preventDefault();
                        //Remove fast with dataBind option
                        waTable.getData().rows.splice(data.index, 1);
                        Platform.performMicrotaskCheckpoint();

                        //This would have worked fine as well, but is slower
                        //var d = waTable.getData();
                        //d.rows.splice(data.index, 1);
                        //waTable.setData(d);
                    }
                    //We can look at classes on the clicked element as well
                    if (this.classList.contains('someClass')) {
                        //Do something...
                    }
                    //Example toggle checked state
                    if (data.column.column == "check") {
                        data.checked = !data.checked;
                    }
                    console.log(data);
                },
                columnClicked: function(data) {    //Fires when a
column is clicked
                  console.log('column clicked');  //data.event holds
the original jQuery event
                  console.log(data);              //data.column holds
the underlying column you supplied
                                                  //data.descending is
true when sorted descending (duh)
                },
                pageChanged: function(data) {      //Fires when
manually changing page
                  console.log('page changed');    //data.event holds
the original jQuery event
                  console.log(data);              //data.page holds
the new page index
                },
                pageSizeChanged: function(data) {  //Fires when
manually changing pagesize
                  console.log('pagesize changed');//data.event holds
teh original event
                  console.log(data);              //data.pageSize
holds the new pagesize
                }
            }).data('WATable');  //This step reaches into the html
data property to get the actual WATable object. Important if you want
a reference to it as we want here.

            //Generate some data
            var data = generateSampleData(500);
            waTable.setData(data);  //Sets the data.
            //waTable.setData(data, true); //Sets the data but
prevents any previously set columns from being overwritten
            //waTable.setData(data, false, false); //Sets the data and
prevents any previously checked rows from being reset

            //Get the data
            var allRows = waTable.getData(false); //Returns the data
you previously set.
            var checkedRows = waTable.getData(true); //Returns only
the checked rows.
            var filteredRows = waTable.getData(false, true); //Returns
only the filtered rows.
            var renderedRows = waTable.getData(false, false, true)
//Returns only the rendered rows.

            //Set options on the fly
            var pageSize = waTable.option("pageSize"); //Get option
            //waTable.option("pageSize", pageSize); //Set option

            //Databinding example
            var row = waTable.getRow(5).row; //Get row with unique value of 5.
            row.name = "Data-Binding Works"; //This would update the
table...but only in ultra modern browsers. (See here
http://caniuse.com/#search=observe)
            Platform.performMicrotaskCheckpoint(); //This make sure it
also works in browsers not yet compatible with Object.observe. This is
the polyfill that's used.(https://github.com/polymer/observe-js).

            //More databinding
            data.rows.shift(); //Removes the first row.
            var newRow = generateSampleData(1).rows[0];
            data.rows.push(newRow); //Add new row
            Platform.performMicrotaskCheckpoint();

            //Example event handler triggered by the custom refresh link above.
            $('#example2').on('click', '.refresh', function(e) {
                e.preventDefault();
                //Get and set some new data
                var data = generateSampleData(100);
                waTable.setData(data, true);
            });
            //Example event handler triggered by the custom export links above.
            $('#example2').on('click', '.export', function(e) {
                e.preventDefault();
                var elem = $(e.target);
                var data;
                if (elem.hasClass('all')) data = waTable.getData(false);
                else if (elem.hasClass('checked')) data = waTable.getData(true);
                else if (elem.hasClass('filtered')) data =
waTable.getData(false, true);
                else if (elem.hasClass('rendered')) data =
waTable.getData(false, false, true);
                console.log(data.rows.length + ' rows returned', data);
                alert(data.rows.length + ' rows returned.See data in console.');
            });

        });

        //Generates some data.
        function generateSampleData(limit, simpleMode) {

            //First define the columns
            var cols = {
                employeeId: {
                    index: 1, //The order this column should appear in the table
                    type: "number", //The type. Possible are string,
number, bool, date(in milliseconds).
                    friendly: "Employee<br>ID",  //Name that will be
used in header. Can also be any html as shown here.
                    format: "<a href='#' target='_blank'>{0}</a>",
//Used to format the data anything you want. Use {0} as placeholder
for the actual data.
                    unique: true,  //This is required if you want
checkable rows, databinding or to use the rowClicked callback. Be
certain the values are really unique or weird things will happen.
                    sortOrder: "asc", //Data will initially be sorted
by this column. Possible are "asc" or "desc"
                    tooltip: "This column is listing unique Employee
ID", //Show some additional info about column
                    filter: "1..400" //Set initial filter.
                },
                employeeName: {
                    index: 2, //The order this column should appear in the table
                    type: "string", //The type. Possible are string,
number, bool, date(in milliseconds).
                    friendly: "Employee Name",  //Name that will be
used in header. Can also be any html as shown here.
                    //format: "<a href='#' target='_blank'>{0}</a>",
//Used to format the data anything you want. Use {0} as placeholder
for the actual data.
                    //unique: true,  //This is required if you want
checkable rows, databinding or to use the rowClicked callback. Be
certain the values are really unique or weird things will happen.
                    //sortOrder: "asc", //Data will initially be
sorted by this column. Possible are "asc" or "desc"
                    tooltip: "This column is lists Employee Name of
Employee ID", //Show some additional info about column
                    filter: false //Set initial filter.
                },


            var rows = [];
            var i = 1;
            while(i <= limit)
            {
                var row = {};
                row.employeeId     =i;
                row.employeeName   =i;

            //Create the returning object. Besides cols and rows, you
can also pass any other object you would need later on.
            var data = {
                cols: cols,
                rows: rows,
                otherStuff: {
                    thatIMight: 1,
                    needLater: true
                }
            };
            return data;
        }

From alan.gauld at yahoo.co.uk  Mon Jul 11 10:32:43 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 11 Jul 2016 15:32:43 +0100
Subject: [Tutor] Python WATable & DB
In-Reply-To: <CAFSKaezi2SX8sooPtTy73RGmX333VpxmpVWSHKfdTp3BymrTTw@mail.gmail.com>
References: <CAFSKaezi2SX8sooPtTy73RGmX333VpxmpVWSHKfdTp3BymrTTw@mail.gmail.com>
Message-ID: <nm0ama$m80$1@ger.gmane.org>

On 11/07/16 10:18, nitin chandra wrote:

> Any body got experience in WATable + passing data from DB to JS / json
> ... and if it is stretching it a bit .. has done it with python.

Given that WATable is a (very impressive) JQuery table it's really
pretty far off topic for this group(core Python language and library).
You are far more likely to get responses on a JS/JQuery forum.

I notice the WATable web site has a comment board, they can
probably advise on the best sites to ask stuff.

As for using one from Python, that's going to be in the web server
domain and the json module in the standard library should be
helpful, so if you have specific questions about json then feel
free to ask more here.

> Also, how do I pass link of employee images/photos.

Assuming you have a json data structure containing employee
data I'd expect there to be a link to an image file in there. Then when
you want to display that it's just a matter of creating an <img...> tag
somewhere on your page/table.


-- 
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 pranavj021 at gmail.com  Mon Jul 11 12:43:04 2016
From: pranavj021 at gmail.com (Pranav Jain)
Date: Mon, 11 Jul 2016 22:13:04 +0530
Subject: [Tutor] (no subject)
Message-ID: <CAPN6evcqv-j9TeUUucScbmGzQqTT72WThkBu_u9Zf8ysQAZQ6A@mail.gmail.com>

Pls unsubscribe me

-- 
Best Regards

Pranav Jain

0-9868204263
pranavj021 at gmail.com

From srini.seri at outlook.com  Mon Jul 11 23:56:28 2016
From: srini.seri at outlook.com (srini s)
Date: Tue, 12 Jul 2016 03:56:28 +0000
Subject: [Tutor] cx_Oracle Installation on windows
Message-ID: <PN1PR01MB0413125D7CAA5F40CFF0310C90300@PN1PR01MB0413.INDPRD01.PROD.OUTLOOK.COM>

Hi,

While installation process, getting the below issue. Please suggest me.

Sent from Mail<https://go.microsoft.com/fwlink/?LinkId=550986> for Windows 10C:\Python34\Scripts>pip install cx_Oracle
Collecting cx_Oracle
  Using cached cx_Oracle-5.2.1.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\WINDOWS\TEMP\pip-build-tuf94dnb\cx-Oracle\setup.py", line 170, in <module>
        raise DistutilsSetupError("cannot locate an Oracle software " \
    distutils.errors.DistutilsSetupError: cannot locate an Oracle software installation

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\WINDOWS\TEMP\pip-build-tuf94dnb\cx-Oracle\


From ammar_online at hotmail.com  Tue Jul 12 10:32:38 2016
From: ammar_online at hotmail.com (ammar jallawi)
Date: Tue, 12 Jul 2016 14:32:38 +0000
Subject: [Tutor] AF_BLUETOOTH  with windows?
Message-ID: <BY2PR1201MB0949CA0FC9E7F30E57B22BE7ED300@BY2PR1201MB0949.namprd12.prod.outlook.com>

Hi


I am running this code on windows:


# Simple TCP client and server that send and receive 16 octets
import socket, sys
s = socket.socket(socket.AF_BLUETOOTH, socket.SO_REUSEADDR, socket.BTPROTO_RFCOMM)
#HOST = sys.argv.pop() if len(sys.argv) == 3 else '127.0.0.1'
HOST = 'DC:FE:07:4D:BF:2F'
#HOST = '4C:EB:42:F1:F3:D7'
PORT = 1060
def recv_all(sock, length):
    data = ''
    while len(data) < length:
        more = sock.recv(length - len(data))
        if not more:
            raise EOFError('socket closed %d bytes into a %d-byte message'
            % (len(data), length))
        data += more
    return data
if sys.argv[1:] == ['server']:
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((HOST, PORT))
    s.listen(1)
    while True:
        print 'Listening at', s.getsockname()
        sc, sockname = s.accept()
        print 'We have accepted a connection from', sockname
        print 'Socket connects', sc.getsockname(), 'and', sc.getpeername()
        message = recv_all(sc, 16)
        print 'The incoming sixteen-octet message says', repr(message)
        sc.sendall('Farewell, client')
        sc.close()
        print 'Reply sent, socket closed'
elif sys.argv[1:] == ['client']:
    s.connect((HOST, PORT))
    print 'Client has been assigned socket name', s.getsockname()
    s.sendall('Hi there, server')
    reply = recv_all(s, 16)
    print 'The server said', repr(reply)
    s.close()
else:
    print >>sys.stderr, 'usage: tcp_local.py server|client [host]'


and getting this error:

AttributeError: 'module' object has no attribute 'AF_BLUETOOTH'


Is the AF_BLUETOOTH supported in windows? if not what I need to do? thanks


regards,


Ammar

From alan.gauld at yahoo.co.uk  Tue Jul 12 15:57:27 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 12 Jul 2016 20:57:27 +0100
Subject: [Tutor] cx_Oracle Installation on windows
In-Reply-To: <PN1PR01MB0413125D7CAA5F40CFF0310C90300@PN1PR01MB0413.INDPRD01.PROD.OUTLOOK.COM>
References: <PN1PR01MB0413125D7CAA5F40CFF0310C90300@PN1PR01MB0413.INDPRD01.PROD.OUTLOOK.COM>
Message-ID: <nm3i35$pop$1@ger.gmane.org>

On 12/07/16 04:56, srini s wrote:
> Hi,
> 
> While installation process, getting the below issue. Please suggest me.
> 
> Sent from Mail<https://go.microsoft.com/fwlink/?LinkId=550986> for Windows 10C:\Python34\Scripts>pip install cx_Oracle
> Collecting cx_Oracle
>   Using cached cx_Oracle-5.2.1.tar.gz
>     Complete output from command python setup.py egg_info:
>     Traceback (most recent call last):
>       File "<string>", line 1, in <module>
>       File "C:\WINDOWS\TEMP\pip-build-tuf94dnb\cx-Oracle\setup.py", line 170, in <module>
>         raise DistutilsSetupError("cannot locate an Oracle software " \
>     distutils.errors.DistutilsSetupError: cannot locate an Oracle software installation

The obvious question is do you have an Oracle database installed?
Can you, for example, run SQLplus from the command 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 yahoo.co.uk  Tue Jul 12 16:45:26 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 12 Jul 2016 21:45:26 +0100
Subject: [Tutor] AF_BLUETOOTH with windows?
In-Reply-To: <BY2PR1201MB0949CA0FC9E7F30E57B22BE7ED300@BY2PR1201MB0949.namprd12.prod.outlook.com>
References: <BY2PR1201MB0949CA0FC9E7F30E57B22BE7ED300@BY2PR1201MB0949.namprd12.prod.outlook.com>
Message-ID: <nm3kt5$964$1@ger.gmane.org>

On 12/07/16 15:32, ammar jallawi wrote:

> # Simple TCP client and server that send and receive 16 octets
> import socket, sys
> s = socket.socket(socket.AF_BLUETOOTH, socket.SO_REUSEADDR, socket.BTPROTO_RFCOMM)
> 


> and getting this error:
> 
> AttributeError: 'module' object has no attribute 'AF_BLUETOOTH'
> 
> 
> Is the AF_BLUETOOTH supported in windows? if not what I need to do? thanks

Please always include the full error text not just the last line summary.

In this case it was fairly easy to find the error source but if it had
been further down or had multiple references it would have been harder.

As to the error what makes you think AF_BLUETOOTH is a valid protocol?
There is no mention of it in the module documentation for Python v2.7
(which is what you appear to be targeting).

It does appear from v3.3 so you need to target that version
(or later) of 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 crusier at gmail.com  Wed Jul 13 08:03:41 2016
From: crusier at gmail.com (Crusier)
Date: Wed, 13 Jul 2016 05:03:41 -0700
Subject: [Tutor] Fwd: 10+ Different Python Script?
In-Reply-To: <CAC7HCj_RKUg1QXUY8eikCkkn+qSJzFMe22-4_F-JVysoDwCyVg@mail.gmail.com>
References: <CAC7HCj_RKUg1QXUY8eikCkkn+qSJzFMe22-4_F-JVysoDwCyVg@mail.gmail.com>
Message-ID: <CAC7HCj-AX+mVaRyo6T-jXQRfSX-13KKn=G2jRPoM_2hvj7iFzw@mail.gmail.com>

Dear All,

I am currently using:
Python 3.5
Window 7


I have a python script which is used for downloading Real Time Stocks.
Currently, there is over a 1000 stocks in the Portfolio.

If I download the market info during market hours, it would take over
40 minutes to finish downloading all the market info. Since I am
trading stock real time, I am thinking of breaking it down into 100
stocks per group, so I could make the download time shorter. For the
market info, I will put into database and for data analysis.

My Question is as follows:

Please advise if I should put the portfolio and split it into 10
different scripts, so each scripts consists a list of 100+ number of
stocks. Or is there any Pythonic way to approach this problem??

I am currently using Multi Thread but there is an Operational Error....


I am having a hard time to approach OOP. I just can't grasp the
understanding of it as it seems so abstract. Please advise.

Thank you

Regards,
Hank

From steve at pearwood.info  Wed Jul 13 09:08:06 2016
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 13 Jul 2016 23:08:06 +1000
Subject: [Tutor] Fwd: 10+ Different Python Script?
In-Reply-To: <CAC7HCj-AX+mVaRyo6T-jXQRfSX-13KKn=G2jRPoM_2hvj7iFzw@mail.gmail.com>
References: <CAC7HCj_RKUg1QXUY8eikCkkn+qSJzFMe22-4_F-JVysoDwCyVg@mail.gmail.com>
 <CAC7HCj-AX+mVaRyo6T-jXQRfSX-13KKn=G2jRPoM_2hvj7iFzw@mail.gmail.com>
Message-ID: <20160713130805.GO27919@ando.pearwood.info>

On Wed, Jul 13, 2016 at 05:03:41AM -0700, Crusier wrote:


> I have a python script which is used for downloading Real Time Stocks.
> Currently, there is over a 1000 stocks in the Portfolio.
>
> If I download the market info during market hours, it would take over
> 40 minutes to finish downloading all the market info.

That's only 2.4 seconds per stock. Depending on how much data each stock 
provides, that doesn't sound like much time to me.

(1) How much data is downloaded? Perhaps you are downloading as fast 
as your internet conection will allow.

(2) How long does it take to download outside of market hours? Perhaps 
the supplier throttles the speed that you can download during market 
hours, or perhaps they're just overloaded with requests and can't supply 
information any faster.


> Since I am
> trading stock real time, I am thinking of breaking it down into 100
> stocks per group, so I could make the download time shorter.

Why do you think that downloading 10*100 stocks will take less time 
than downloading 1000 stocks? Either way, you still have to download the 
same amount of information.


> For the
> market info, I will put into database and for data analysis.
> 
> My Question is as follows:
> 
> Please advise if I should put the portfolio and split it into 10
> different scripts, so each scripts consists a list of 100+ number of
> stocks. Or is there any Pythonic way to approach this problem??

Absolutely not. You shouldn't have the portfolio inside the script. You 
should have one script, and ten portfolios. Then you give the name of 
the portfolio as an argument to the script:

myscript.py portfolio1
myscript.py portfolio2
myscript.py portfolio3
...
myscript.py portfolio10

or possibly:

myscript.py portfolio1 portfolio2 portfolio3 ... portfolio10

> I am currently using Multi Thread but there is an Operational Error....

What sort of error?


> I am having a hard time to approach OOP. I just can't grasp the
> understanding of it as it seems so abstract. Please advise.

One related question per email please. It makes it easier to follow the 
conversations if you put unrelated questions in different emails.



-- 
Steve

From wrw at mac.com  Wed Jul 13 09:02:58 2016
From: wrw at mac.com (William Ray Wing)
Date: Wed, 13 Jul 2016 09:02:58 -0400
Subject: [Tutor] 10+ Different Python Script?
In-Reply-To: <CAC7HCj-AX+mVaRyo6T-jXQRfSX-13KKn=G2jRPoM_2hvj7iFzw@mail.gmail.com>
References: <CAC7HCj_RKUg1QXUY8eikCkkn+qSJzFMe22-4_F-JVysoDwCyVg@mail.gmail.com>
 <CAC7HCj-AX+mVaRyo6T-jXQRfSX-13KKn=G2jRPoM_2hvj7iFzw@mail.gmail.com>
Message-ID: <E4B7228E-0363-47CB-94CF-2A6FBC586487@mac.com>


> On Jul 13, 2016, at 8:03 AM, Crusier <crusier at gmail.com> wrote:
> 
> Dear All,
> 
> I am currently using:
> Python 3.5
> Window 7
> 
> 
> I have a python script which is used for downloading Real Time Stocks.
> Currently, there is over a 1000 stocks in the Portfolio.
> 
> If I download the market info during market hours, it would take over
> 40 minutes to finish downloading all the market info. Since I am

Do you know where this (seeming) throughput limitation is _actually_ occurring?
I don?t know what format you are getting the data in, but if each stock is represented by it?s 1-4 character symbol, followed by a current quote (perhaps both bid and asked), then this adds up to around a dozen characters.  Lets be generous and say 20 bytes.  Twenty bytes times 1000 stocks is 20 kB.  Even a ?slow? connection these days should give you a 2 Mbs throughput or 200 kBs (including overhead), so your 20 kB of data should download in roughly one tenth of a second. 


> trading stock real time, I am thinking of breaking it down into 100
> stocks per group, so I could make the download time shorter. For the
> market info, I will put into database and for data analysis.
> 

In other words, don?t waste time solving the wrong problem.

> My Question is as follows:
> 
> Please advise if I should put the portfolio and split it into 10
> different scripts, so each scripts consists a list of 100+ number of
> stocks. Or is there any Pythonic way to approach this problem??
> 
> I am currently using Multi Thread but there is an Operational Error....
> 
> 
> I am having a hard time to approach OOP. I just can't grasp the
> understanding of it as it seems so abstract. Please advise.
> 
> Thank you
> 
> Regards,
> Hank
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor


From bkd69ster at gmail.com  Wed Jul 13 08:20:46 2016
From: bkd69ster at gmail.com (Bruce Dykes)
Date: Wed, 13 Jul 2016 08:20:46 -0400
Subject: [Tutor] Counting and grouping dictionary values in Python 2.7
In-Reply-To: <nloo53$66n$1@ger.gmane.org>
References: <CAE3hSEq7rPAzxLweZBrRPe7bC4-jeABqiJUDB9zkxr70+1J-bA@mail.gmail.com>
 <nloo53$66n$1@ger.gmane.org>
Message-ID: <CAE3hSErt3jBiFRR5zvex-54KzfB=WFiUfCCkK+_nS8o-Ug6=oQ@mail.gmail.com>

On Fri, Jul 8, 2016 at 1:33 PM, Alan Gauld via Tutor <tutor at python.org>
wrote:

> On 08/07/16 14:22, Bruce Dykes wrote:
>
> > with it is writing the list of dictionaries to a .csv file, and to date,
> > we've been able to get by doing some basic analysis by simply using grep
> > and wc, but I need to do more with it now.
>
> I'm a big fan of using the right tool for the job.
> If you got your data in CSV have you considered using a
> spreadsheet to read the data and analyse it? They have lots
> of formulae and stats functions built in and can do really
> cool graphs etc and can read csv files natively.
>
> Python might be a better tool if you want regular identical reports, say
> on a daily basis, but for ad-hoc analysis, or at least till you know
> exactly what you need, Excel or Calc are possibly better tools.
>
>
>
We can and have used spreadsheets for small ad-hoc things, but no, we need
two things, first, as noted, a daily report with various basic analyses,
mainly totals, and percentages, and second, possibly, some near-current
alarm checks, depending. That's less important, actually, but it might be a
nice convenience. In the first instance, we want the reports to be accessed
and displayed as web pages. Now, likewise, I'm sure there's a CMS that
might make semi-quick work of this as well, but really, all I need to do is
to display some web pages and run some cgi scripts.

bkd

From beachkidken at gmail.com  Wed Jul 13 14:29:48 2016
From: beachkidken at gmail.com (Ken G.)
Date: Wed, 13 Jul 2016 14:29:48 -0400
Subject: [Tutor] Quote and double quotes opens up File Explorer in
 Windows 10 (RESOLVED)
In-Reply-To: <CACL+1auFdE1t1wtBr_+S-0-C_N9ZmYF8sxxAHDoB6xCMT4OxGQ@mail.gmail.com>
References: <57810898.5030400@gmail.com>
 <CACL+1auFdE1t1wtBr_+S-0-C_N9ZmYF8sxxAHDoB6xCMT4OxGQ@mail.gmail.com>
Message-ID: <5786889C.4060601@gmail.com>


On 07/09/2016 01:02 PM, eryk sun wrote:
> On Sat, Jul 9, 2016 at 2:22 PM, Ken G. <beachkidken at gmail.com> wrote:
>> Hi: In gradually moving over my Python programs (2.7.6) to Windows 10 and
>> using Geany 1.27 to modify or write up a program there, it is noted that
>> whenever I typed in a quote (') or double quote ("), Windows 10 File
>> Explorer opens up. I end up closing it by typing ALT-F4 to resume typing as
>> before. Is there a way to prevent the File Explorer from opening up whenever
>> I use a quote or double quote? Is there another key(s) that does weird thing
>> in Windows 10? Thanks.
> The single/double quote key isn't a standard hotkey in any version of
> Windows. That would be insane. If this is just happening in Geany,
> check its keybindings preferences. Otherwise, check that you're using
> the right keyboard layout and that you don't have any programs (or
> malware) that's registering a global hotkey.
>
> For example, here's a simple script that registers the single quote
> (US keyboard layout) as a global hotkey to open the desktop in
> Explorer:
>
>      #! /usr/bin/python3
>      import os
>      import ctypes
>      from ctypes import wintypes
>
>      user32 = ctypes.WinDLL('user32')
>
>      WM_HOTKEY = 0x0312
>      MOD_NOREPEAT = 0x4000
>      VK_OEM_7 = 0xDE # US layout, single/double quote
>
>      hotkey_id = 1
>      if user32.RegisterHotKey(None, hotkey_id, MOD_NOREPEAT, VK_OEM_7):
>          print('Hotkey "\'" registered.')
>          msg = wintypes.MSG()
>          count = 0
>          while (count < 3 and
>                 user32.GetMessageW(ctypes.byref(msg), None, 0, 0)):
>              if msg.message == WM_HOTKEY and msg.wParam == hotkey_id:
>                  count += 1
>                  print('Hotkey received.')
>                  os.startfile('shell:Desktop')
>
Thank you for the responses. As it just turned out, it was the keyboard 
sending out a faulty signal for the quote and double quote to the 
computer. I switched keyboard and there was no opening of the File 
Explorer when sending quote and double quote using Geany. Again, thanks.

Ken

From michael.selik at gmail.com  Wed Jul 13 23:36:21 2016
From: michael.selik at gmail.com (Michael Selik)
Date: Thu, 14 Jul 2016 03:36:21 +0000
Subject: [Tutor] Counting and grouping dictionary values in Python 2.7
In-Reply-To: <CAE3hSEq7rPAzxLweZBrRPe7bC4-jeABqiJUDB9zkxr70+1J-bA@mail.gmail.com>
References: <CAE3hSEq7rPAzxLweZBrRPe7bC4-jeABqiJUDB9zkxr70+1J-bA@mail.gmail.com>
Message-ID: <CAGgTfkMFi7D06F+53d90mjhE=8hj9bEBOAetWi0d99ZKAiOVQQ@mail.gmail.com>

On Fri, Jul 8, 2016 at 10:15 AM Bruce Dykes <bkd69ster at gmail.com> wrote:

> I'm compiling application logs from a bunch of servers, reading the log
> entries, parsing each log entry into a dictionary, and compiling all the
> log entries into a single list of dictionaries.
>

Seems reasonable. Perhaps instead of having each log entry as a dictionary,
you might prefer to create a namedtuple.


> Now, what I need to do with this arbitrarily count and total the values in
> the dictionaries, ie the total amount and number of items for transaction
> id 387, or the total number of crackers sold in NJ stores.


Use the Counter class from the collections module. Loop over your records,
write an if-statement to determine which records are interesting, then
increment the count for the appropriate key.

If you're having trouble, share your code and the error message.

Also, is there any particular advantage to pickling the list and having two
> files, one, the pickled file to be read as a data source, and the .csv file
> for portability/readability, as opposed to just a single .csv file that
> gets reparsed by the reporting script?
>

Probably simpler to keep just a CSV.

From noahstickel33 at gmail.com  Thu Jul 14 00:06:28 2016
From: noahstickel33 at gmail.com (Noah Stickel)
Date: Wed, 13 Jul 2016 23:06:28 -0500
Subject: [Tutor] wiped file
Message-ID: <CAJv1DrO4HTAGJSsWuco+BPRX1Q67zgYBkK0nYX=+ZfDd4wNdhQ@mail.gmail.com>

i open a python file in IDLE (python 3.5.1) and then my computer froze
after displaying an error 40 message (i have a DELL PC) and when i
restarted it i discovered that the file had been completely wiped clean. So
i still have the file but there is nothing in it. is there anyway i can
restore the contents of this python file?

From alan.gauld at yahoo.co.uk  Thu Jul 14 11:13:59 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 14 Jul 2016 16:13:59 +0100
Subject: [Tutor] wiped file
In-Reply-To: <CAJv1DrO4HTAGJSsWuco+BPRX1Q67zgYBkK0nYX=+ZfDd4wNdhQ@mail.gmail.com>
References: <CAJv1DrO4HTAGJSsWuco+BPRX1Q67zgYBkK0nYX=+ZfDd4wNdhQ@mail.gmail.com>
Message-ID: <nm8a7m$10k$1@ger.gmane.org>

On 14/07/16 05:06, Noah Stickel wrote:
> i open a python file in IDLE (python 3.5.1) and then my computer froze
> after displaying an error 40 message (i have a DELL PC) and when i
> restarted it i discovered that the file had been completely wiped clean. So
> i still have the file but there is nothing in it. is there anyway i can
> restore the contents of this python file?

If you stored the file on the cloud (Dropbox, Google drive etc)
you may be able to recover old versions. If you run Linux you
may have a journalling file-system that can recover previous
versions.

Alternatively you may have committed the file to a version
control system? In that case simply check out the old version.

And of course if you regularly backup your disks then your
backup programme can probably retrieve the last saved version.

If none of the above applies then now you know why they should! :-(

-- 
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 gokoproject at gmail.com  Thu Jul 14 18:19:00 2016
From: gokoproject at gmail.com (John Wong)
Date: Thu, 14 Jul 2016 18:19:00 -0400
Subject: [Tutor] wiped file
In-Reply-To: <nm8a7m$10k$1@ger.gmane.org>
References: <CAJv1DrO4HTAGJSsWuco+BPRX1Q67zgYBkK0nYX=+ZfDd4wNdhQ@mail.gmail.com>
 <nm8a7m$10k$1@ger.gmane.org>
Message-ID: <CACCLA57cxtNot05T+Z9rHDUTbMDgEkaL0amYXPLtB--gEttabA@mail.gmail.com>

Alan made really good points, standard practice, however, on Linux and
MacOSX, usually if you use editors like VIM, a temporary file is always
created. For Windows, I am not sure 100%. Check your editor, your editor
may have saved a cache file but marked as hidden file. For example,
Notepad++ has this feature:
http://superuser.com/questions/281776/does-notepad-backup-pre-edited-files-anywhere
.

I made my point because version control system (VCS) is an on-demand
software. Unless you instruct VCS to keep "version controlling" your code,
it will only keep the last copy. Furthermore, you'd have to store the VCS
repository somewhere else. For example, if you are using Git, you may use
BitBucket, GitHub, Gitlab to store a remote copy.


On Thu, Jul 14, 2016 at 11:13 AM, Alan Gauld via Tutor <tutor at python.org>
wrote:

> On 14/07/16 05:06, Noah Stickel wrote:
> > i open a python file in IDLE (python 3.5.1) and then my computer froze
> > after displaying an error 40 message (i have a DELL PC) and when i
> > restarted it i discovered that the file had been completely wiped clean.
> So
> > i still have the file but there is nothing in it. is there anyway i can
> > restore the contents of this python file?
>
> If you stored the file on the cloud (Dropbox, Google drive etc)
> you may be able to recover old versions. If you run Linux you
> may have a journalling file-system that can recover previous
> versions.
>
> Alternatively you may have committed the file to a version
> control system? In that case simply check out the old version.
>
> And of course if you regularly backup your disks then your
> backup programme can probably retrieve the last saved version.
>
> If none of the above applies then now you know why they should! :-(
>
> --
> 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 yahoo.co.uk  Thu Jul 14 19:16:29 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 15 Jul 2016 00:16:29 +0100
Subject: [Tutor] wiped file
In-Reply-To: <CACCLA57cxtNot05T+Z9rHDUTbMDgEkaL0amYXPLtB--gEttabA@mail.gmail.com>
References: <CAJv1DrO4HTAGJSsWuco+BPRX1Q67zgYBkK0nYX=+ZfDd4wNdhQ@mail.gmail.com>
 <nm8a7m$10k$1@ger.gmane.org>
 <CACCLA57cxtNot05T+Z9rHDUTbMDgEkaL0amYXPLtB--gEttabA@mail.gmail.com>
Message-ID: <57881D4D.6090009@yahoo.co.uk>

On 14/07/16 23:19, John Wong wrote:
> ... if you use editors like VIM, a temporary file is always created.

But with vim once you close the file it deletes the temporary copy.
So unless you realize the problem before it gets deleted it won't help.
But since you are using IDLE I don;t think that's even an option.
So far as i know IDLE doesn't create a backup file.

> I made my point because version control system (VCS) is an
> on-demand software. Unless you instruct VCS to keep
> "version controlling" your code, it will only keep the last copy.

It will keep all the versions that you check in. so if you create an
editor macro (assuming you have an editor that does macros
 - IDLE doesn't...) that checks in the file each time you save it
then you can roll back to any intermediate save.

> Furthermore, you'd have to store the VCS repository somewhere
> else. For example, if you are using Git, you may use BitBucket,

That's not strictly true, it depends on the VCS (and even  server
based ones can be used locally if needed). I still use RCS for my
own projects and that's just a local file (or more usually a folder
called RCS...) CVS and SVN can both work with local files if you
want something beefier than RCS.

-- 
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  Thu Jul 14 20:08:52 2016
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 15 Jul 2016 10:08:52 +1000
Subject: [Tutor] wiped file
In-Reply-To: <CAJv1DrO4HTAGJSsWuco+BPRX1Q67zgYBkK0nYX=+ZfDd4wNdhQ@mail.gmail.com>
References: <CAJv1DrO4HTAGJSsWuco+BPRX1Q67zgYBkK0nYX=+ZfDd4wNdhQ@mail.gmail.com>
Message-ID: <20160715000851.GR27919@ando.pearwood.info>

On Wed, Jul 13, 2016 at 11:06:28PM -0500, Noah Stickel wrote:
> i open a python file in IDLE (python 3.5.1) and then my computer froze
> after displaying an error 40 message (i have a DELL PC) and when i
> restarted it i discovered that the file had been completely wiped clean. So
> i still have the file but there is nothing in it. is there anyway i can
> restore the contents of this python file?

Probably not. This is not a Python issue, but a problem with your 
operating system and hard drive's file system.

If your file is called (let's say) "myfile.py", you could look for a 
file called "myfile.py~" which may contain a backup, or possibly a 
previous version. But unlikely.

By the way, what's "error 40"? Is that a Windows thing?


-- 
Steve

From rahulsijwali at gmail.com  Sat Jul 16 07:31:16 2016
From: rahulsijwali at gmail.com (rahul sijwali)
Date: Sat, 16 Jul 2016 04:31:16 -0700
Subject: [Tutor] learning path for python
Message-ID: <CAF_5A9hE+7eO5HqfLCa3H97JSoXKeO9q+MGoms1mpSQ9PAgT+w@mail.gmail.com>

i started learning python previous week using "Automate the Boring
Stuff with Python" i am totally new to programming but had no problem
completing the first part now i am off second part which actually
involves "automating stuff"

now i saw it involves "web scrapping" i want to learn more of it and
also be able to develop physics based 2-d games and also stuff like
"face-recognition"

what i want is learning path in order like what to learn first and up
to what extent and if you could recommend good resources on it (mostly
texts)please do

also i am new to programming so keep that in mind while recommending
learning path

Thanks !

From alan.gauld at yahoo.co.uk  Sat Jul 16 10:34:32 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 16 Jul 2016 15:34:32 +0100
Subject: [Tutor] learning path for python
In-Reply-To: <CAF_5A9hE+7eO5HqfLCa3H97JSoXKeO9q+MGoms1mpSQ9PAgT+w@mail.gmail.com>
References: <CAF_5A9hE+7eO5HqfLCa3H97JSoXKeO9q+MGoms1mpSQ9PAgT+w@mail.gmail.com>
Message-ID: <nmdglm$dce$1@ger.gmane.org>

On 16/07/16 12:31, rahul sijwali wrote:
> i started learning python previous week using "Automate the Boring
> Stuff with Python" i am totally new to programming but had no problem
> completing the first part now i am off second part which actually
> involves "automating stuff"
> 
> now i saw it involves "web scrapping" i want to learn more of it and
> also be able to develop physics based 2-d games and also stuff like
> "face-recognition"
> 
> what i want is learning path in order like what to learn first and up
> to what extent and if you could recommend good resources on it (mostly
> texts)please do

A good foundation in general programming never goes amiss.
It sounds like you have found a resource that works for you
so stick with it. If you have specific questions or things
you want more detail about feel free to ask here.

As to 2D games you can try PyGame.

Things like face recognition are highly complex and specialised
techniques, but there are some libraries around that do the
hard stuff for you so provided you want to play with face
recognition rather than develop your own recognition algorithms
from scratch you should e fine. But these libraries will
assume you are already competent in general programming.

So in summary, continue with your book. Ask for extra
information here. Consider a general purpose tutorial
too (there are lots listed on the Python web sitre, including
mine(see below).

Then try pyGame - there are tutorials and a support forum.

Finally for the 2D/physics stuff there are other libraries
you can try like pymunk and cgkit. In fact there's a dedicated
page on the wiki:

http://wiki.python.org/moin/PythonGameLibraries


Enjoy,

-- 
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  Sun Jul 17 07:18:00 2016
From: marcus.luetolf at bluewin.ch (=?iso-8859-1?Q?marcus_l=FCtolf?=)
Date: Sun, 17 Jul 2016 13:18:00 +0200
Subject: [Tutor] installing openpyxl
Message-ID: <098a01d1e01c$e3bcc380$ab364a80$@bluewin.ch>

dear Experts,


could someone please tell me what exactly I have to type in my a) Python 35
? command line or 

b) desktopcomputer ( W10, 64bit)-command line in ordert to install openpyxl
which I downloaded in

C:\Users\marcus\Downloads on my computer. 
I have used all kinds of commands with ?pip install? at the end, all
unsuccessful.

 

Thanks for help.

Marcus.

 



---
Diese E-Mail wurde von Avast Antivirus-Software auf Viren gepr?ft.
https://www.avast.com/antivirus

From brozi at toya.net.pl  Sun Jul 17 08:41:33 2016
From: brozi at toya.net.pl (A.Brozi)
Date: Sun, 17 Jul 2016 14:41:33 +0200
Subject: [Tutor] strange behavior of matrix**matrix
Message-ID: <6ac21b06-4fb0-88d5-5cfb-166cf79f2642@toya.net.pl>

Hello

I'm puzzling over some strange behavior of raising a matrix to a matrix 
power:

If I create two matrices (containing integers):
a = np.array([2])
and
b = np.array([-1])
the operation a**b produces:
array([0], dtype=int32)

The result of division b/a is correct:
array([-0.5])

If any one of the matrices is float (i.e. created with the use of 
dtype=float) the result is correct, i.e. a**b produces:
array([ 0.5])

If a and b are single integer 32 numbers, e.g. obtained with:
a = np.int32(2)
and
b = np.int32(-1)
the same operation a**b produces:
0.5
as expected.

Perhaps it's somehow related to the 'old' integer division of Pythons 2.x.

I wonder if it's a bug or a feature.
And if it's a feature, then what is it useful for?

I'm on Python 3.5.1 64bit via Spyder 3.0.0dev, numpy 1.9.3, scipy 0.16.1 
(all installed from WinPython-64bit-3.5.1.3.exe), running on Windows 10.

Regards
Andrzej Brozi

From alan.gauld at yahoo.co.uk  Sun Jul 17 09:57:27 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 17 Jul 2016 14:57:27 +0100
Subject: [Tutor] installing openpyxl
In-Reply-To: <098a01d1e01c$e3bcc380$ab364a80$@bluewin.ch>
References: <098a01d1e01c$e3bcc380$ab364a80$@bluewin.ch>
Message-ID: <nmg2s5$21n$1@ger.gmane.org>

On 17/07/16 12:18, marcus l?tolf wrote:

> could someone please tell me what exactly I have to type

> I have used all kinds of commands with ?pip install? at the end, all
> unsuccessful.

At an OS command prompt type

C:\WINDOWS> pip install openpyxl

You will need write permission to the site packages folder

There is a very brief PyPI tutorial hee:

http://wiki.python.org/moin/CheeseShopTutorial


-- 
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 __peter__ at web.de  Sun Jul 17 11:17:16 2016
From: __peter__ at web.de (Peter Otten)
Date: Sun, 17 Jul 2016 17:17:16 +0200
Subject: [Tutor] strange behavior of matrix**matrix
References: <6ac21b06-4fb0-88d5-5cfb-166cf79f2642@toya.net.pl>
Message-ID: <nmg7hu$33g$1@ger.gmane.org>

A.Brozi wrote:

> Hello
> 
> I'm puzzling over some strange behavior of raising a matrix to a matrix
> power:
> 
> If I create two matrices (containing integers):
> a = np.array([2])
> and
> b = np.array([-1])
> the operation a**b produces:
> array([0], dtype=int32)
> 
> The result of division b/a is correct:
> array([-0.5])
> 
> If any one of the matrices is float (i.e. created with the use of
> dtype=float) the result is correct, i.e. a**b produces:
> array([ 0.5])
> 
> If a and b are single integer 32 numbers, e.g. obtained with:
> a = np.int32(2)
> and
> b = np.int32(-1)
> the same operation a**b produces:
> 0.5
> as expected.
> 
> Perhaps it's somehow related to the 'old' integer division of Pythons 2.x.
> 
> I wonder if it's a bug or a feature.

There are two division operators, / and //, so you can choose explicitly:

>>> numpy.array([4, 6]) / numpy.array([3, 2])
array([ 1.33333333,  3.        ])
>>> numpy.array([4, 6]) // numpy.array([3, 2])
array([1, 3])

There is only one ** operator, so numpy has to pick a default.

> And if it's a feature, then what is it useful for?

It's probably rarely used with negative exponents, but you don't want numpy 
to pick the result type by inspecting all entry values in the potentially 
large result array. For scalars the overhead is less relevant.

> I'm on Python 3.5.1 64bit via Spyder 3.0.0dev, numpy 1.9.3, scipy 0.16.1
> (all installed from WinPython-64bit-3.5.1.3.exe), running on Windows 10.



From steve at pearwood.info  Sun Jul 17 11:23:01 2016
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 18 Jul 2016 01:23:01 +1000
Subject: [Tutor] strange behavior of matrix**matrix
In-Reply-To: <6ac21b06-4fb0-88d5-5cfb-166cf79f2642@toya.net.pl>
References: <6ac21b06-4fb0-88d5-5cfb-166cf79f2642@toya.net.pl>
Message-ID: <20160717152300.GT27919@ando.pearwood.info>

On Sun, Jul 17, 2016 at 02:41:33PM +0200, A.Brozi wrote:
> Hello
> 
> I'm puzzling over some strange behavior of raising a matrix to a matrix 
> power:
> 
> If I create two matrices (containing integers):
> a = np.array([2])
> and
> b = np.array([-1])
> the operation a**b produces:
> array([0], dtype=int32)

What result did you expect? 2**-1 as an int32 cannot be 0.5, as that's a 
float.

I'm not really sure about the rules that numpy uses for coercing from 
one type to another, but I'm not surprised by this result. I don't know 
if it is documented anywhere, but it seems like the sort of thing numpy 
would do. Here's another similar example:

py> np.array([0])**-1
__main__:1: RuntimeWarning: divide by zero encountered in power
__main__:1: RuntimeWarning: invalid value encountered in power
array([-2147483648])



> The result of division b/a is correct:
> array([-0.5])

You only get that result in Python 3, or Python 2 with "from __future__ 
import division". Without it, / behaves the same as // (integer 
division), for example:

py> b//a
array([-1])
py> b/a
array([-1])

But once I run the future import, the behaviour changes:

py> from __future__ import division
py> b/a
array([-0.5])



> I wonder if it's a bug or a feature.
> And if it's a feature, then what is it useful for?

My guess is that the only reason for it is that it keeps the code 
simple, which allows numpy to be fast.

-- 
Steve

From steve at pearwood.info  Sun Jul 17 11:39:24 2016
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 18 Jul 2016 01:39:24 +1000
Subject: [Tutor] installing openpyxl
In-Reply-To: <nmg2s5$21n$1@ger.gmane.org>
References: <098a01d1e01c$e3bcc380$ab364a80$@bluewin.ch>
 <nmg2s5$21n$1@ger.gmane.org>
Message-ID: <20160717153924.GU27919@ando.pearwood.info>

On Sun, Jul 17, 2016 at 02:57:27PM +0100, Alan Gauld via Tutor wrote:
> On 17/07/16 12:18, marcus l?tolf wrote:
> 
> > could someone please tell me what exactly I have to type
> 
> > I have used all kinds of commands with ?pip install? at the end, all
> > unsuccessful.
> 
> At an OS command prompt type
> 
> C:\WINDOWS> pip install openpyxl

If that doesn't work, try this:

python35 -m pip install openpyxl


> You will need write permission to the site packages folder

That is certainly true.


-- 
Steve

From umed.saidov at gmail.com  Sun Jul 17 22:00:19 2016
From: umed.saidov at gmail.com (Umed Saidov)
Date: Sun, 17 Jul 2016 21:00:19 -0500
Subject: [Tutor] Python3: looping through web address
Message-ID: <578C3833.1040406@gmail.com>

Hello Tutor(s),

I want to create a loop that loops through a web address, changing only 
a part of that address with each loop. I can't seem to be able to get 
the code to do this. Below is the code with some explanation of what I 
am trying to do. The code seems to loop through the ticker symbol file 
ignoring the web address. Is there another way of doing the same thing?

import urllib.request, json
import csv
import pandas as pd
import itertools

ticker = []
ticker = pd.DataFrame(ticker)

#open a cvs file with 100+ stock tickers from S&P500. Save in a 
dataframe 'ticker'.
ticker =pd.read_csv('tickers.csv')

#Loop through ticker, changing the designated part of the web address. 
Download the data into 'response'

for t in ticker.itertuples():
     response += 
urllib.request.urlopen('https:websiteaddress/{ct}/financials'.format(ct=ticker))


From __peter__ at web.de  Mon Jul 18 05:11:47 2016
From: __peter__ at web.de (Peter Otten)
Date: Mon, 18 Jul 2016 11:11:47 +0200
Subject: [Tutor] Python3: looping through web address
References: <578C3833.1040406@gmail.com>
Message-ID: <nmi6gl$e8j$1@ger.gmane.org>

Umed Saidov wrote:

> Hello Tutor(s),
> 
> I want to create a loop that loops through a web address, changing only
> a part of that address with each loop. I can't seem to be able to get
> the code to do this. Below is the code with some explanation of what I
> am trying to do. The code seems to loop through the ticker symbol file
> ignoring the web address. Is there another way of doing the same thing?
> 
> import urllib.request, json
> import csv
> import pandas as pd
> import itertools
> 
> ticker = []
> ticker = pd.DataFrame(ticker)
> 
> #open a cvs file with 100+ stock tickers from S&P500. Save in a
> dataframe 'ticker'.
> ticker =pd.read_csv('tickers.csv')
> 
> #Loop through ticker, changing the designated part of the web address.
> Download the data into 'response'
> 
> for t in ticker.itertuples():
>      response +=
> 
urllib.request.urlopen('https:websiteaddress/{ct}/financials'.format(ct=ticker))


ticker is the complete DataFrame and t corresponds to one row in the csv. 
Assuming the column in the csv you are interested in is called "foo" you can 
get it with

columnname = "foo" # replace with your own name
for ct in ticker[columnname]:
    url = 'https:websiteaddress/{ct}/financials'.format(ct=ticker)
    print(url)

Once this prints the correct urls you can write a little function

def process_page(url):
    request = urllib.request.urlopen(url)
    ... # do what you want with the request

invoke it with one url and refine it until the function does what you want. 
Then combine it with the loop

columnname = "foo" # replace with your own name
for ct in ticker[columnname]:
    url = 'https:websiteaddress/{ct}/financials'.format(ct=ticker)
    process_page(url)

In short: take small controlled steps to get to the desired result instead 
of writing a complete script that may or may not work.


From alan.gauld at yahoo.co.uk  Mon Jul 18 07:35:03 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 18 Jul 2016 12:35:03 +0100
Subject: [Tutor] Python3: looping through web address
In-Reply-To: <578C3833.1040406@gmail.com>
References: <578C3833.1040406@gmail.com>
Message-ID: <nmiet6$hjp$1@ger.gmane.org>

On 18/07/16 03:00, Umed Saidov wrote:

> import urllib.request, json
> import csv
> import pandas as pd
> import itertools
> 
> ticker = []
> ticker = pd.DataFrame(ticker)

Caveat: I'm not a Pandas expert but...
This looks odd. You first assign an empty list to ticker and pass that
into pandas.DataFrame then assign the result back to ticker. Is that
what you intended? Why not just

ticker = pd.DataFrame([])

Or is there something clever going on?

> #open a cvs file with 100+ stock tickers from S&P500. Save in a 
> dataframe 'ticker'.

> ticker =pd.read_csv('tickers.csv')

And now you overwrite the dataframe with the content of a csv file?
I'm not sure what read_csv returns but it seems to me you are
creating and throwing away a lot of stuff here?

> for t in ticker.itertuples():
>      response += 
> urllib.request.urlopen('https:websiteaddress/{ct}/financials'.format(ct=ticker))

ticker is the iterable, it does not change during the loop.
Yet in the url it is ticker you assign to the ct marker.
Don't you want 't'? That's the thing that changes.

It might help to create and print the address before calling urlopen:

for t in ticker.itertuples():
    address = 'https:websiteaddress/{ct}/financials'.format(ct=ticker)
    print address   # remove when done
    response += urllib.request.urlopen(address)



-- 
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 umed.saidov at gmail.com  Mon Jul 18 10:10:40 2016
From: umed.saidov at gmail.com (Umed Saidov)
Date: Mon, 18 Jul 2016 09:10:40 -0500
Subject: [Tutor] Python3: looping through web address
In-Reply-To: <nmiet6$hjp$1@ger.gmane.org>
References: <578C3833.1040406@gmail.com> <nmiet6$hjp$1@ger.gmane.org>
Message-ID: <578CE360.2030700@gmail.com>



On 07/18/2016 06:35 AM, Alan Gauld via Tutor wrote:
> Caveat: I'm not a Pandas expert but... This looks odd. You first 
> assign an empty list to ticker and pass that into pandas.DataFrame 
> then assign the result back to ticker. Is that what you intended? Why 
> not just ticker = pd.DataFrame([]) Or is there something clever going on? 
No. nothing clever I am afraid. I wanted to create a variable to store 
data in pandas format. This seemed like a good way of doing it... but 
perhaps not.
>> #open a cvs file with 100+ stock tickers from S&P500. Save in a
>> dataframe 'ticker'.
>> ticker =pd.read_csv('tickers.csv')
> And now you overwrite the dataframe with the content of a csv file?
> I'm not sure what read_csv returns but it seems to me you are
> creating and throwing away a lot of stuff here?
>
the csv is just a column of tickers. I wanted to store them in pandas 
format. this returns a pandas dataframe with contents of the csv file 
stored in two columns (index and ticker values)
>> for t in ticker.itertuples():
>>       response +=
>> urllib.request.urlopen('https:websiteaddress/{ct}/financials'.format(ct=ticker))
> ticker is the iterable, it does not change during the loop.
> Yet in the url it is ticker you assign to the ct marker.
> Don't you want 't'? That's the thing that changes.
     I want the content of the column one in ticker. With each iteration 
of t, which I thought was just a simple numeric progression representing 
a row number, I wanted to get the content of the column one.
> It might help to create and print the address before calling urlopen:
>
> for t in ticker.itertuples():
>      address = 'https:websiteaddress/{ct}/financials'.format(ct=ticker)
>      print address   # remove when done
>      response += urllib.request.urlopen(address)
>
>
>
Thanks for the suggestion. I tried this and received the badstatusline 
error message:

Traceback (most recent call last):
   File "something.py", line 23, in <module>
     response += urllib.request.urlopen(address)
   File "...request.py", line 162, in urlopen
     return opener.open(url, data, timeout)
   File "..request.py", line 465, in open
     response = self._open(req, data)
   File "..request.py", line 483, in _open
     '_open', req)
   File "python3.5/urllib/request.py", line 443, in _call_chain
     result = func(*args)
   File "python3.5/urllib/request.py", line 1283, in https_open
     context=self._context, check_hostname=self._check_hostname)
   File "/python3.5/urllib/request.py", line 1243, in do_open
     r = h.getresponse()
   File "python3.5/http/client.py", line 1174, in getresponse
     response.begin()
   File "python3.5/http/client.py", line 282, in begin
     version, status, reason = self._read_status()
   File "python3.5/http/client.py", line 264, in _read_status
     raise BadStatusLine(line)
http.client.BadStatusLine: <html>


From alan.gauld at yahoo.co.uk  Mon Jul 18 13:48:11 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 18 Jul 2016 18:48:11 +0100
Subject: [Tutor] Python3: looping through web address
In-Reply-To: <578CE360.2030700@gmail.com>
References: <578C3833.1040406@gmail.com> <nmiet6$hjp$1@ger.gmane.org>
 <578CE360.2030700@gmail.com>
Message-ID: <nmj4op$osh$1@ger.gmane.org>

On 18/07/16 15:10, Umed Saidov wrote:

> No. nothing clever I am afraid. I wanted to create a variable to store 
> data in pandas format. This seemed like a good way of doing it... but 
> perhaps not.
>>> #open a cvs file with 100+ stock tickers from S&P500. Save in a
>>> dataframe 'ticker'.
>>> ticker =pd.read_csv('tickers.csv')
>>
> the csv is just a column of tickers. I wanted to store them in pandas 
> format. this returns a pandas dataframe with contents of the csv file 
> stored in two columns (index and ticker values)

In that case you should be able to miss out the two lines above and just use

ticker = pd.read_csv('tickers.csv')

>      I want the content of the column one in ticker. With each iteration 
> of t, which I thought was just a simple numeric progression representing 
> a row number, I wanted to get the content of the column one.

In Python a for loop returns the actual data items not
an index. So I would expect the value of t to be one of
whatever ticker.itertuples() returns - presumably a tuple.
And if you want the first(only?) element then you need to use


t[0] to get it.

>> It might help to create and print the address before calling urlopen:
>>
>> for t in ticker.itertuples():
>>      address = 'https:websiteaddress/{ct}/financials'.format(ct=ticker)
>>      print address   # remove when done
>>      response += urllib.request.urlopen(address)
>>
> Thanks for the suggestion. I tried this and received the badstatusline 
> error message:

OK, In that case comment out the openurl() line and just look at what
values the address has (or even just t itself initially). Simplify as
much as possible. Once you know you are getting the right value then you
can create the right address, then you can try to open it.

Take it one step at a time.
-- 
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 skapeven at gmail.com  Mon Jul 18 17:32:40 2016
From: skapeven at gmail.com (Skapeven Punkboard)
Date: Mon, 18 Jul 2016 18:32:40 -0300
Subject: [Tutor] The Way
In-Reply-To: <CADbqSPQMvmmR6mv7yO1oF=77JumQwjvqzAzXxheGdtiOtYsUZw@mail.gmail.com>
References: <CADbqSPTpJQrnpZLMViOxAU6A3m5UBQG6mc+4sxGKQ9=yianNvA@mail.gmail.com>
 <CADbqSPSkipFws_QQcE7osOwrGaCfw4cNCNVTF3Li8kOjoYBABQ@mail.gmail.com>
 <CADbqSPQCwjxSjX03gikLTbAgwgSQCSCJE=TnWrFKO+1qiP45mg@mail.gmail.com>
 <CADbqSPQMvmmR6mv7yO1oF=77JumQwjvqzAzXxheGdtiOtYsUZw@mail.gmail.com>
Message-ID: <CADbqSPRCf7HZWMDA0bGbKen8mz_YR_yrtPd0BJGWJ1d+vZzjNw@mail.gmail.com>

Hello I have programmed a lot but only basic stuff, I never got further
from a point in which I had to start looking for information in forums.
Since the tutorials wherent enogh.  I would like to learn more by trying to
solve usefull stuff with or for others.  How could I do this and
participate in the comunity?

From alan.gauld at yahoo.co.uk  Mon Jul 18 19:55:07 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 19 Jul 2016 00:55:07 +0100
Subject: [Tutor] The Way
In-Reply-To: <CADbqSPRCf7HZWMDA0bGbKen8mz_YR_yrtPd0BJGWJ1d+vZzjNw@mail.gmail.com>
References: <CADbqSPTpJQrnpZLMViOxAU6A3m5UBQG6mc+4sxGKQ9=yianNvA@mail.gmail.com>
 <CADbqSPSkipFws_QQcE7osOwrGaCfw4cNCNVTF3Li8kOjoYBABQ@mail.gmail.com>
 <CADbqSPQCwjxSjX03gikLTbAgwgSQCSCJE=TnWrFKO+1qiP45mg@mail.gmail.com>
 <CADbqSPQMvmmR6mv7yO1oF=77JumQwjvqzAzXxheGdtiOtYsUZw@mail.gmail.com>
 <CADbqSPRCf7HZWMDA0bGbKen8mz_YR_yrtPd0BJGWJ1d+vZzjNw@mail.gmail.com>
Message-ID: <nmjq8p$vsc$1@ger.gmane.org>

On 18/07/16 22:32, Skapeven Punkboard wrote:
> Hello I have programmed a lot but only basic stuff, I never got further
> from a point in which I had to start looking for information in forums.
> Since the tutorials wherent enogh.  I would like to learn more by trying to
> solve usefull stuff with or for others.  How could I do this and
> participate in the comunity?

You could try an open source project. Get involved with that,
start by fixing bugs or testing or writing documentation.

Or even hang out here and answer some questions. They come at all levels
and as you gain experience you can answer more advanced
topics.

Or do both... :-)

-- 
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 monikajg at netzero.net  Tue Jul 19 01:36:02 2016
From: monikajg at netzero.net (monikajg at netzero.net)
Date: Tue, 19 Jul 2016 05:36:02 GMT
Subject: [Tutor] The Way
Message-ID: <20160718.223602.16331.0@webmail03.dca.untd.com>

How do you get involved in open source project?
Thank you
Monika

---------- Original Message ----------
From: Alan Gauld via Tutor <tutor at python.org>
To: tutor at python.org
Subject: Re: [Tutor] The Way
Date: Tue, 19 Jul 2016 00:55:07 +0100

On 18/07/16 22:32, Skapeven Punkboard wrote:
> Hello I have programmed a lot but only basic stuff, I never got further
> from a point in which I had to start looking for information in forums.
> Since the tutorials wherent enogh.  I would like to learn more by trying to
> solve usefull stuff with or for others.  How could I do this and
> participate in the comunity?

You could try an open source project. Get involved with that,
start by fixing bugs or testing or writing documentation.

Or even hang out here and answer some questions. They come at all levels
and as you gain experience you can answer more advanced
topics.

Or do both... :-)

-- 
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


____________________________________________________________
Affordable Wireless Plans
Set up is easy. Get online in minutes.
Starting at only $9.95 per month! 
www.netzero.net?refcd=nzmem0216

From alan.gauld at yahoo.co.uk  Tue Jul 19 04:19:07 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 19 Jul 2016 09:19:07 +0100
Subject: [Tutor] The Way
In-Reply-To: <20160718.223602.16331.0@webmail03.dca.untd.com>
References: <20160718.223602.16331.0@webmail03.dca.untd.com>
Message-ID: <nmknpq$2vi$1@ger.gmane.org>

On 19/07/16 06:36, monikajg at netzero.net wrote:
> How do you get involved in open source project?

Generally you just visit the project homepage and there will be
information there. For example for Python itself you can go to:

https://wiki.python.org/moin/Community

And for Blender

https://www.blender.org/get-involved/

For smaller projects you can simply email the author.
Although you should probably download and read the source
first and have a look to see if its something you could handle.

-- 
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 sanchezquibus at gmail.com  Tue Jul 19 07:31:58 2016
From: sanchezquibus at gmail.com (=?UTF-8?Q?Marc_S=C3=A0nchez_Quibus?=)
Date: Tue, 19 Jul 2016 13:31:58 +0200
Subject: [Tutor] Help me out please
Message-ID: <CAGcE6NNRiDq6WbUE0UwmSL2v-vXKZPkxvTJ_z9GGt339Gdtf2w@mail.gmail.com>

Hi,
First of all I'm gonan introduce myself. My name is Marc and I'm a student
and also a python's programmer begginer. I've been studying/learning python
and now I need some help to finish my project.
I have two scripts, one of them in python (the main script) and the other
one written in html. Well, is just a brief javascript (an app) that I took
by Github. I need to change a variable inside this html script. I was
wondering wether I could change this variable from my python script or not.
Is there some way to do it?
Thanks in advance and sorry for the inconvenience.

-- 
*Marc S?nchez Quibus*

From tushargoyal357 at gmail.com  Tue Jul 19 03:43:18 2016
From: tushargoyal357 at gmail.com (Tushar Goyal)
Date: Tue, 19 Jul 2016 13:13:18 +0530
Subject: [Tutor] Need Your help
Message-ID: <CACBE4YP_jOeRk4P=4AAQF=imnhMLxQ49XeHnU5aVw7un1XoPZg@mail.gmail.com>

I'm creating a mobile application [ http://e-aadhaarcard.in ] and I'm using
python for a desktop server. However, I don't have access to a static IP on
the desktop, but do have a website. Is it possible to connect from mobile
http website -> desktop server and back?

If I got you right, I would skip the website entirely. Just connect
directly to your desktop from the mobile, using a dynamic DNS service.
Maybe the bump you need could be: http://dnslookup.me/dynamic-dns/

From alan.gauld at yahoo.co.uk  Tue Jul 19 09:50:49 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 19 Jul 2016 14:50:49 +0100
Subject: [Tutor] Need Your help
In-Reply-To: <CACBE4YP_jOeRk4P=4AAQF=imnhMLxQ49XeHnU5aVw7un1XoPZg@mail.gmail.com>
References: <CACBE4YP_jOeRk4P=4AAQF=imnhMLxQ49XeHnU5aVw7un1XoPZg@mail.gmail.com>
Message-ID: <nmlb7n$tjv$1@ger.gmane.org>


> I'm creating a mobile application [ http://e-aadhaarcard.in ] and I'm using
> python for a desktop server. However, I don't have access to a static IP on
> the desktop, but do have a website. Is it possible to connect from mobile
> http website -> desktop server and back?

That all depends on how your website is set up.
Ultimately the app needs an IP address to connect to.
Regardless of how the actual IP address is allocated
(DHCP or static) there needs to be a translation between
the web site logical address name (www.foo.com) and
the actual IP address (123.234.2.1).

If you have the web site registered with some kind of DNS
setup that translates the logical address to the IP address
Then the app just needs to use the logical address and it
all should just 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 alan.gauld at yahoo.co.uk  Tue Jul 19 09:57:39 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 19 Jul 2016 14:57:39 +0100
Subject: [Tutor] Help me out please
In-Reply-To: <CAGcE6NNRiDq6WbUE0UwmSL2v-vXKZPkxvTJ_z9GGt339Gdtf2w@mail.gmail.com>
References: <CAGcE6NNRiDq6WbUE0UwmSL2v-vXKZPkxvTJ_z9GGt339Gdtf2w@mail.gmail.com>
Message-ID: <nmlbkh$4v8$1@ger.gmane.org>

On 19/07/16 12:31, Marc S?nchez Quibus wrote:

> and now I need some help to finish my project.
> I have two scripts, one of them in python (the main script) and the other
> one written in html. Well, is just a brief javascript (an app) that I took
> by Github. I need to change a variable inside this html script. I was
> wondering wether I could change this variable from my python script or not.
> Is there some way to do it?

The easiest way is to put the entire html code into a string
inside a module:

# file: myhtml.py
########
html = """
<html><body><h1>Hello %s</h1><body></html>
"""

Then import that and use string formatting to insert the variable

#file: myscript.py
import myhtml
myvar = "World"
print myhtml.html % myvar

Instead of printing you could overwrite the original html file.

Or you could write a web based app using a framework like Flask
or Pylons and call your myscript.py from a web url and get it
to just serve the html string directly.

We don't know enough about your system and how the two
scripts are related to say more than that. But it might
give you some ideas.


-- 
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 bgailer at gmail.com  Tue Jul 19 09:59:51 2016
From: bgailer at gmail.com (Bob Gailer)
Date: Tue, 19 Jul 2016 09:59:51 -0400
Subject: [Tutor] Help me out please
In-Reply-To: <CAGcE6NNRiDq6WbUE0UwmSL2v-vXKZPkxvTJ_z9GGt339Gdtf2w@mail.gmail.com>
References: <CAGcE6NNRiDq6WbUE0UwmSL2v-vXKZPkxvTJ_z9GGt339Gdtf2w@mail.gmail.com>
Message-ID: <CAP1rxO61m+OCczcEqxSq2K-w1B92vDBaeCjc9JcN7ntq73=JHg@mail.gmail.com>

On Jul 19, 2016 9:24 AM, "Marc S?nchez Quibus" <sanchezquibus at gmail.com>
wrote:
>
> Hi,
> First of all I'm gonan introduce myself. My name is Marc and I'm a student
> and also a python's programmer begginer. I've been studying/learning
python
> and now I need some help to finish my project.
> I have two scripts, one of them in python (the main script) and the other
> one written in html. Well, is just a brief javascript (an app) that I took
> by Github. I need to change a variable inside this html script. I was
> wondering wether I could change this variable from my python script or
not.
> Is there some way to do it?

There might be. Tell us more about your situation.

> Thanks in advance and sorry for the inconvenience.

Since we are here to help, the only inconvenience his when we don't get
enough information. That seems to be typical for first time questioners.

From nitinchandra1 at gmail.com  Tue Jul 19 14:43:36 2016
From: nitinchandra1 at gmail.com (nitin chandra)
Date: Wed, 20 Jul 2016 00:13:36 +0530
Subject: [Tutor] python cgi single double quotes
Message-ID: <CAFSKaewdfD-XuvYSXBb0ARfdV=hpoH7xHfG6RNPjxR=VHUhSSQ@mail.gmail.com>

Hi

I wrote python+cgi script on hostgator server and I could embed html like:-

code folder :- /home/userName/public_html/*.cgi

#!/usr/bin/env python

print "Content-Type:text/html\n\n"

print
print """<html>
...

<script type='text/javascript'
src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js?ver=3.0.1'></script>
<script type='text/javascript' src='js/infinite-rotator.js'></script>

...

</html>"""

The above style / way of coding works. Even on my laptop where the
code is in /var/www/<projDir>

Now I have taken a VPS, using command line, I installed apache2.4,
python 2.7, but I am not able to use the same code with triple quotes
(""") to open and close the code block.

I am forced to use

#!/usr/bin/env python

import cgi
import psycopg2

print "Content-type:text/html\r\n\r\n"
print '<html>'
print '....'
print '...'
print '</html>'

Do I need to do some thing to apache config such that I can use Triple
quote to embed.

Also, if I ReUse some of the previous code, it give 500 error.

Any solutions ?

Thanks

Nitin

From alan.gauld at yahoo.co.uk  Tue Jul 19 15:16:22 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 19 Jul 2016 20:16:22 +0100
Subject: [Tutor] python cgi single double quotes
In-Reply-To: <CAFSKaewdfD-XuvYSXBb0ARfdV=hpoH7xHfG6RNPjxR=VHUhSSQ@mail.gmail.com>
References: <CAFSKaewdfD-XuvYSXBb0ARfdV=hpoH7xHfG6RNPjxR=VHUhSSQ@mail.gmail.com>
Message-ID: <nmlua5$kuo$1@ger.gmane.org>

On 19/07/16 19:43, nitin chandra wrote:

> Now I have taken a VPS, using command line, I installed apache2.4,
> python 2.7, but I am not able to use the same code with triple quotes
> (""") to open and close the code block.
> 
> I am forced to use
> 
> print "Content-type:text/html\r\n\r\n"
> print '<html>'
> print '....'

> Do I need to do some thing to apache config such that I can use Triple
> quote to embed.

Triple quotes should work anywhere Python works.
But first I'd check your python environment.
Which interpreter is actually running for example?

Try

import sys
...
print "<p> + "sys.version + "</p>"
...

The 500 error sounds like an apache setup or maybe permissions
issue. Are your files readable/executable by Apache?

-- 
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 zuhair72h at yahoo.com  Tue Jul 19 18:14:59 2016
From: zuhair72h at yahoo.com (zuhair ali)
Date: Tue, 19 Jul 2016 22:14:59 +0000 (UTC)
Subject: [Tutor] pyrouge
References: <1033420412.2063002.1468966499108.JavaMail.yahoo.ref@mail.yahoo.com>
Message-ID: <1033420412.2063002.1468966499108.JavaMail.yahoo@mail.yahoo.com>

Hatd I sirI used pyrouge?package for evaluation rouge package and ?I have one problem that i don't know how to create settings.ini file and what i put in this file. This file found in Rouge155().py please can you help me.

From alan.gauld at yahoo.co.uk  Tue Jul 19 19:24:26 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 20 Jul 2016 00:24:26 +0100
Subject: [Tutor] pyrouge
In-Reply-To: <1033420412.2063002.1468966499108.JavaMail.yahoo@mail.yahoo.com>
References: <1033420412.2063002.1468966499108.JavaMail.yahoo.ref@mail.yahoo.com>
 <1033420412.2063002.1468966499108.JavaMail.yahoo@mail.yahoo.com>
Message-ID: <nmmcr8$ph5$1@ger.gmane.org>

On 19/07/16 23:14, zuhair ali via Tutor wrote:
> I used pyrouge package for evaluation rouge package
> and  I have one problem that i don't know how to
> create settings.ini file and what i put in this file.

This list is for the Python language and its standard
library so rouge() is a bit off topic. Whether you get
any help will depend on whether anyone here has ever
used it.

You will likely get more help on the pyrouge support
forum if such exists. A quick look at the web site
suggests not.

Failing that you could try the main python list or
even emailing the pyrouge author. Although of the
3 contributors only Federico Barrios seems to have
an email address!

-- 
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 Jul 19 21:53:07 2016
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 20 Jul 2016 11:53:07 +1000
Subject: [Tutor] pyrouge
In-Reply-To: <1033420412.2063002.1468966499108.JavaMail.yahoo@mail.yahoo.com>
References: <1033420412.2063002.1468966499108.JavaMail.yahoo.ref@mail.yahoo.com>
 <1033420412.2063002.1468966499108.JavaMail.yahoo@mail.yahoo.com>
Message-ID: <20160720015306.GA27919@ando.pearwood.info>

On Tue, Jul 19, 2016 at 10:14:59PM +0000, zuhair ali via Tutor wrote:

> Hatd I sirI used pyrouge?package for evaluation rouge package and ?I 
> have one problem that i don't know how to create settings.ini file and 
> what i put in this file. This file found in Rouge155().py please can 
> you help me.


I am sorry, I don't know pyrouge. Nut have you tried these?

https://www.google.com.au/search?q=pyrouge+settings.ini

https://duckduckgo.com/?q=pyrouge%20settings.ini

You could try just creating an empty file "settings.ini" and putting it 
where pyrouge expects to find it.


-- 
Steve

From ben+python at benfinney.id.au  Wed Jul 20 03:48:23 2016
From: ben+python at benfinney.id.au (Ben Finney)
Date: Wed, 20 Jul 2016 17:48:23 +1000
Subject: [Tutor] Writing decorators?
References: <CA+Q8_Jes1FV=1rHOZLSODAkRCtiUBOAnp5ygUQsXWi-F-co7RQ@mail.gmail.com>
 <v2m36dxb1m.ln2@news.c0t0d0s0.de>
Message-ID: <858twwsqbc.fsf@benfinney.id.au>

Michael Welle <mwe012008 at gmx.net> writes:

> Somewhere in this thread (or the one talking about decorators after
> this thread) it was said that a decorator 'changes a function'. I not
> a native English speaker, so it could just be a language problem. But
> to me it seems the function is replaced, not changed?

That's correct.

Don't be surprised, though, if the concept ?replace the object
referenced by ?foo? with a different object and discard the prior object
at that reference? is glossed to ?change ?foo?? in casual usage :-)

-- 
 \      ?Hey Homer! You're late for English!? ?Pff! English, who needs |
  `\          that? I'm never going to England!? ?Barney & Homer, _The |
_o__)                                                        Simpsons_ |
Ben Finney


From Joaquin.Alzola at lebara.com  Tue Jul 19 09:36:39 2016
From: Joaquin.Alzola at lebara.com (Joaquin Alzola)
Date: Tue, 19 Jul 2016 13:36:39 +0000
Subject: [Tutor] Need Your help
In-Reply-To: <CACBE4YP_jOeRk4P=4AAQF=imnhMLxQ49XeHnU5aVw7un1XoPZg@mail.gmail.com>
References: <CACBE4YP_jOeRk4P=4AAQF=imnhMLxQ49XeHnU5aVw7un1XoPZg@mail.gmail.com>
Message-ID: <DB5PR07MB0806EC0DDF3B08E405BE06F4F0370@DB5PR07MB0806.eurprd07.prod.outlook.com>


>I'm creating a mobile application [ http://e-aadhaarcard.in ] and I'm using python for a desktop server. However, I don't have access to a static IP on the desktop, but do have a website. Is it possible to connect from mobile http website -> desktop server >and back?

Try using a LAN so all your devices have a 192.168.X.X address. You can set it in your PC and Mobile manually or through DHCP.
You will be communicating through IP base between your desktop and mobile. That way you can test your application.

Also you can ask your IT department to assign a permanent IP if you want to test real live.
This email is confidential and may be subject to privilege. If you are not the intended recipient, please do not copy or disclose its content but contact the sender immediately upon receipt.

From nitinchandra1 at gmail.com  Wed Jul 20 04:23:12 2016
From: nitinchandra1 at gmail.com (nitin chandra)
Date: Wed, 20 Jul 2016 13:53:12 +0530
Subject: [Tutor] python cgi single double quotes
In-Reply-To: <nmlua5$kuo$1@ger.gmane.org>
References: <CAFSKaewdfD-XuvYSXBb0ARfdV=hpoH7xHfG6RNPjxR=VHUhSSQ@mail.gmail.com>
 <nmlua5$kuo$1@ger.gmane.org>
Message-ID: <CAFSKaezKKooWFiS=57xFj+fby1_jT1Zru5MTCCRvgadUJtbt9w@mail.gmail.com>

Hi Alan,


vimal at Ubuntu-1404-trusty-64-minimal:~$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print sys.version
2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2]
>>>

Should I test the above from within html code too ?

Also, for testing and configuration purpose, I have set 755 / 777
permissions to dir / files respectively.

Thank you,

Nitin Chandra



On 20 July 2016 at 00:46, Alan Gauld via Tutor <tutor at python.org> wrote:
> On 19/07/16 19:43, nitin chandra wrote:
>
>> Now I have taken a VPS, using command line, I installed apache2.4,
>> python 2.7, but I am not able to use the same code with triple quotes
>> (""") to open and close the code block.
>>
>> I am forced to use
>>
>> print "Content-type:text/html\r\n\r\n"
>> print '<html>'
>> print '....'
>
>> Do I need to do some thing to apache config such that I can use Triple
>> quote to embed.
>
> Triple quotes should work anywhere Python works.
> But first I'd check your python environment.
> Which interpreter is actually running for example?
>
> Try
>
> import sys
> ...
> print "<p> + "sys.version + "</p>"
> ...
>
> The 500 error sounds like an apache setup or maybe permissions
> issue. Are your files readable/executable by Apache?
>
> --
> 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 yahoo.co.uk  Wed Jul 20 04:27:42 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 20 Jul 2016 09:27:42 +0100
Subject: [Tutor] Writing decorators?
In-Reply-To: <g4o36dx711.ln2@news.c0t0d0s0.de>
References: <CA+Q8_Jes1FV=1rHOZLSODAkRCtiUBOAnp5ygUQsXWi-F-co7RQ@mail.gmail.com>
 <v2m36dxb1m.ln2@news.c0t0d0s0.de> <858twwsqbc.fsf@benfinney.id.au>
 <g4o36dx711.ln2@news.c0t0d0s0.de>
Message-ID: <nmnclt$sg8$1@ger.gmane.org>

On 20/07/16 09:08, Michael Welle wrote:

>> Don't be surprised, though, if the concept ?replace the object
>> referenced by ?foo? with a different object and discard the prior object
>> at that reference? is glossed to ?change ?foo?? in casual usage :-)
> I'm a bit surprised to see that kind of sloppy use of language on a
> Python list ;). But you are right, human language is imprecise. 

Its not really sloppy. In English change means alter and
the function referenced by foo is altered by a decorator.

For example we could reasonably say that

foo = lambda x: x+1

creates a function called foo
And we can therefore also say that

foo = lambda x: x+2

changes the function foo.

Decorators change the function in a similar way.
It depends on whether you are referring to the function
name or the function object. So the use of change is not
necessarily sloppy but it could be imprecise. :-)

-- 
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 yahoo.co.uk  Wed Jul 20 04:44:10 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 20 Jul 2016 09:44:10 +0100
Subject: [Tutor] python cgi single double quotes
In-Reply-To: <CAFSKaezKKooWFiS=57xFj+fby1_jT1Zru5MTCCRvgadUJtbt9w@mail.gmail.com>
References: <CAFSKaewdfD-XuvYSXBb0ARfdV=hpoH7xHfG6RNPjxR=VHUhSSQ@mail.gmail.com>
 <nmlua5$kuo$1@ger.gmane.org>
 <CAFSKaezKKooWFiS=57xFj+fby1_jT1Zru5MTCCRvgadUJtbt9w@mail.gmail.com>
Message-ID: <nmndko$8p6$1@ger.gmane.org>

On 20/07/16 09:23, nitin chandra wrote:

> vimal at Ubuntu-1404-trusty-64-minimal:~$ python
> Python 2.7.6 (default, Jun 22 2015, 17:58:13)
> [GCC 4.8.2] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import sys
>>>> print sys.version
> 2.7.6 (default, Jun 22 2015, 17:58:13)
> [GCC 4.8.2]
>>>>
> 
> Should I test the above from within html code too ?

Yes, that's what I meant to imply by putting it
inside <p> markers:

>> import sys
>> ...
>> print "<p> + "sys.version + "</p>"
>> ...

The idea is to make sure that the web server is
running the same version of Python that you are.

-- 
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 nitinchandra1 at gmail.com  Wed Jul 20 05:09:25 2016
From: nitinchandra1 at gmail.com (nitin chandra)
Date: Wed, 20 Jul 2016 14:39:25 +0530
Subject: [Tutor] python cgi single double quotes
In-Reply-To: <nmndko$8p6$1@ger.gmane.org>
References: <CAFSKaewdfD-XuvYSXBb0ARfdV=hpoH7xHfG6RNPjxR=VHUhSSQ@mail.gmail.com>
 <nmlua5$kuo$1@ger.gmane.org>
 <CAFSKaezKKooWFiS=57xFj+fby1_jT1Zru5MTCCRvgadUJtbt9w@mail.gmail.com>
 <nmndko$8p6$1@ger.gmane.org>
Message-ID: <CAFSKaezC0iWaORdL5pqUZS=ZmqSiaB=oayaJCvg6kLNw2SF-0w@mail.gmail.com>

On inserting the line ...

print "<p> + "sys.version + "</p>"

required slight correction

print "<p>" + sys.version + "</p>"

and the following script and its output are below :-
----------------------------------------
#!/usr/bin/env python

import sys
import cgi
import psycopg2

print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>Hello Word - First CGI Program</title>'
print '</head>'
print '<body>'
print '<h2>Hello Word! This is my first CGI program</h2>'
print "<p>"+ sys.version + "</p>"
print 'First name: <input type="text" name="fname"><br>'
print '</body>'
print '</html>'

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

Hello Word! This is my first CGI program

2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2]

First name:

On 20 July 2016 at 14:14, Alan Gauld via Tutor <tutor at python.org> wrote:
> On 20/07/16 09:23, nitin chandra wrote:
>
>> vimal at Ubuntu-1404-trusty-64-minimal:~$ python
>> Python 2.7.6 (default, Jun 22 2015, 17:58:13)
>> [GCC 4.8.2] on linux2
>> Type "help", "copyright", "credits" or "license" for more information.
>>>>> import sys
>>>>> print sys.version
>> 2.7.6 (default, Jun 22 2015, 17:58:13)
>> [GCC 4.8.2]
>>>>>
>>
>> Should I test the above from within html code too ?
>
> Yes, that's what I meant to imply by putting it
> inside <p> markers:
>
>>> import sys
>>> ...
>>> print "<p> + "sys.version + "</p>"
>>> ...
>
> The idea is to make sure that the web server is
> running the same version of Python that you are.
>
> --
> 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 __peter__ at web.de  Wed Jul 20 05:45:04 2016
From: __peter__ at web.de (Peter Otten)
Date: Wed, 20 Jul 2016 11:45:04 +0200
Subject: [Tutor] python cgi single double quotes
References: <CAFSKaewdfD-XuvYSXBb0ARfdV=hpoH7xHfG6RNPjxR=VHUhSSQ@mail.gmail.com>
 <nmlua5$kuo$1@ger.gmane.org>
 <CAFSKaezKKooWFiS=57xFj+fby1_jT1Zru5MTCCRvgadUJtbt9w@mail.gmail.com>
 <nmndko$8p6$1@ger.gmane.org>
 <CAFSKaezC0iWaORdL5pqUZS=ZmqSiaB=oayaJCvg6kLNw2SF-0w@mail.gmail.com>
Message-ID: <nmnh74$4pe$1@ger.gmane.org>

nitin chandra wrote:

> On inserting the line ...
> 
> print "<p> + "sys.version + "</p>"
> 
> required slight correction
> 
> print "<p>" + sys.version + "</p>"
> 
> and the following script and its output are below :-
> ----------------------------------------
> #!/usr/bin/env python
> 
> import sys
> import cgi
> import psycopg2
> 
> print "Content-type:text/html\r\n\r\n"
> print '<html>'
> print '<head>'
> print '<title>Hello Word - First CGI Program</title>'
> print '</head>'
> print '<body>'
> print '<h2>Hello Word! This is my first CGI program</h2>'
> print "<p>"+ sys.version + "</p>"
> print 'First name: <input type="text" name="fname"><br>'
> print '</body>'
> print '</html>'
> 
> ---------------------------------------------------
> 
> Hello Word! This is my first CGI program
> 
> 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2]
> 
> First name:

If you got that from your server like in the session below...

$ cat first.py
#!/usr/bin/env python

import sys
import cgi
import psycopg2

print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>Hello Word - First CGI Program</title>'
print '</head>'
print '<body>'
print '<h2>Hello Word! This is my first CGI program</h2>'
print "<p>"+ sys.version + "</p>"
print 'First name: <input type="text" name="fname"><br>'
print '</body>'
print '</html>'
$ curl http://myhost/somewhere/first.py

<html>
<head>
<title>Hello Word - First CGI Program</title>
</head>
<body>
<h2>Hello Word! This is my first CGI program</h2>
<p>2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2]</p>
First name: <input type="text" name="fname"><br>
</body>
</html>

... the following should also work:

$ cat second.py
#!/usr/bin/env python

import sys
import cgi
import psycopg2

print """Content-type:text/html\r\n\r\n
<html>
<head>
<title>Hello Word - First CGI Program</title>
</head>
<body>
<h2>Hello Word! This is my first CGI program</h2>
<p>{version}</p>
First name: <input type="text" name="fname"><br>
</body>
</html>
""".format(version=sys.version)
$ curl http://myhost/somewhere/second.py

<html>
<head>
<title>Hello Word - First CGI Program</title>
</head>
<body>
<h2>Hello Word! This is my first CGI program</h2>
<p>2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2]</p>
First name: <input type="text" name="fname"><br>
</body>
</html>

If it does you can start looking for the actual problem. I don't expect it 
to have anything to do with your choice of quoting characters, as long as 
you write legal Python 2.


From nitinchandra1 at gmail.com  Wed Jul 20 06:16:54 2016
From: nitinchandra1 at gmail.com (nitin chandra)
Date: Wed, 20 Jul 2016 15:46:54 +0530
Subject: [Tutor] python cgi single double quotes
In-Reply-To: <nmnh74$4pe$1@ger.gmane.org>
References: <CAFSKaewdfD-XuvYSXBb0ARfdV=hpoH7xHfG6RNPjxR=VHUhSSQ@mail.gmail.com>
 <nmlua5$kuo$1@ger.gmane.org>
 <CAFSKaezKKooWFiS=57xFj+fby1_jT1Zru5MTCCRvgadUJtbt9w@mail.gmail.com>
 <nmndko$8p6$1@ger.gmane.org>
 <CAFSKaezC0iWaORdL5pqUZS=ZmqSiaB=oayaJCvg6kLNw2SF-0w@mail.gmail.com>
 <nmnh74$4pe$1@ger.gmane.org>
Message-ID: <CAFSKaey6g7xMp2M9mfPv04HjtiSrt2Ch79EA=JxMnCssKUz+Lw@mail.gmail.com>

Ran both the method

#!/usr/bin/env python

import cgi
import psycopg2
import sys

print """Content-type:text/html\r\n\r\n"""
print """<html>
<head>
<title>Hello Word - First CGI Program</title>
</head>
<body>
<h2>Hello Word! This is my first CGI program</h2>
<p>{version}</p>
First name: <input type="text" name="fname"><br>
</body>
</html>""".format(version=sys.version)

and its output (below)

nitin at nitin-Ideapad-Z570:~$ curl http://passtms.in/vimal.cgi

<html>
<head>
<title>Hello Word - First CGI Program</title>
</head>
<body>
<h2>Hello Word! This is my first CGI program</h2>
<p>2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2]</p>
First name: <input type="text" name="fname"><br>
</body>
</html>
nitin at nitin-Ideapad-Z570:~$

In the first instance also it the same :
--------------------------------------------------------------
#!/usr/bin/env python

import sys
import cgi
import psycopg2

print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>Hello Word - First CGI Program</title>'
print '</head>'
print '<body>'
print '<h2>Hello Word! This is my first CGI program</h2>'
print "<p>"+ sys.version + "</p>"
print 'First name: <input type="text" name="fname"><br>'
print '</body>'
print '</html>'


output (below):-

nitin at nitin-Ideapad-Z570:~$ curl http://passtms.in/vimal.py

<html>
<head>
<title>Hello Word - First CGI Program</title>
</head>
<body>
<h2>Hello Word! This is my first CGI program</h2>
<p>2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2]</p>
First name: <input type="text" name="fname"><br>
</body>
</html>

On 20 July 2016 at 15:15, Peter Otten <__peter__ at web.de> wrote:
> nitin chandra wrote:
>
>> On inserting the line ...
>>
>> print "<p> + "sys.version + "</p>"
>>
>> required slight correction
>>
>> print "<p>" + sys.version + "</p>"
>>
>> and the following script and its output are below :-
>> ----------------------------------------
>> #!/usr/bin/env python
>>
>> import sys
>> import cgi
>> import psycopg2
>>
>> print "Content-type:text/html\r\n\r\n"
>> print '<html>'
>> print '<head>'
>> print '<title>Hello Word - First CGI Program</title>'
>> print '</head>'
>> print '<body>'
>> print '<h2>Hello Word! This is my first CGI program</h2>'
>> print "<p>"+ sys.version + "</p>"
>> print 'First name: <input type="text" name="fname"><br>'
>> print '</body>'
>> print '</html>'
>>
>> ---------------------------------------------------
>>
>> Hello Word! This is my first CGI program
>>
>> 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2]
>>
>> First name:
>
> If you got that from your server like in the session below...
>
> $ cat first.py
> #!/usr/bin/env python
>
> import sys
> import cgi
> import psycopg2
>
> print "Content-type:text/html\r\n\r\n"
> print '<html>'
> print '<head>'
> print '<title>Hello Word - First CGI Program</title>'
> print '</head>'
> print '<body>'
> print '<h2>Hello Word! This is my first CGI program</h2>'
> print "<p>"+ sys.version + "</p>"
> print 'First name: <input type="text" name="fname"><br>'
> print '</body>'
> print '</html>'
> $ curl http://myhost/somewhere/first.py
>
> <html>
> <head>
> <title>Hello Word - First CGI Program</title>
> </head>
> <body>
> <h2>Hello Word! This is my first CGI program</h2>
> <p>2.7.6 (default, Jun 22 2015, 17:58:13)
> [GCC 4.8.2]</p>
> First name: <input type="text" name="fname"><br>
> </body>
> </html>
>
> ... the following should also work:
>
> $ cat second.py
> #!/usr/bin/env python
>
> import sys
> import cgi
> import psycopg2
>
> print """Content-type:text/html\r\n\r\n
> <html>
> <head>
> <title>Hello Word - First CGI Program</title>
> </head>
> <body>
> <h2>Hello Word! This is my first CGI program</h2>
> <p>{version}</p>
> First name: <input type="text" name="fname"><br>
> </body>
> </html>
> """.format(version=sys.version)
> $ curl http://myhost/somewhere/second.py
>
> <html>
> <head>
> <title>Hello Word - First CGI Program</title>
> </head>
> <body>
> <h2>Hello Word! This is my first CGI program</h2>
> <p>2.7.6 (default, Jun 22 2015, 17:58:13)
> [GCC 4.8.2]</p>
> First name: <input type="text" name="fname"><br>
> </body>
> </html>
>
> If it does you can start looking for the actual problem. I don't expect it
> to have anything to do with your choice of quoting characters, as long as
> you write legal Python 2.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

From ben+python at benfinney.id.au  Wed Jul 20 07:47:53 2016
From: ben+python at benfinney.id.au (Ben Finney)
Date: Wed, 20 Jul 2016 21:47:53 +1000
Subject: [Tutor] Writing decorators?
References: <CA+Q8_Jes1FV=1rHOZLSODAkRCtiUBOAnp5ygUQsXWi-F-co7RQ@mail.gmail.com>
 <v2m36dxb1m.ln2@news.c0t0d0s0.de> <858twwsqbc.fsf@benfinney.id.au>
 <g4o36dx711.ln2@news.c0t0d0s0.de> <nmnclt$sg8$1@ger.gmane.org>
 <3ur36dxrco.ln2@news.c0t0d0s0.de>
Message-ID: <85zipcr0nq.fsf@benfinney.id.au>

Michael Welle <mwe012008 at gmx.net> writes:

> so 'the function has changed' really means 'the reference has
> changed'? Strange.

Humans think in strage ways :-)

Really, though, it shouldn't be too surprising. The *perception* is that
the reference (a name, or an index in a sequence, or whatever) remains
unchanged; at least, you still address the reference exactly the same
way. ?foo? in the code remains ?foo?.

But what you get from that reference is different. So, because what I
get when I refer to ?foo? is different after some operation than what
it was prior to that operation, it is natural to speak loosely about
?this operation has changed foo?.

> If you hear 'function foo', do you think of the reference 'foo' or do
> you think of the referenced thing, the function object? It might be
> context dependent, but usually I think about the latter.

It is normal for us to think of them as one, because in Python the
*only* way to get an object is through some specific reference. Our
natural language doesn't easily handle the separable but linked
concepts.

> But it might just be a language problem.

Which is another way of saying thta it's a human thinking problem. Try
not to have overly strict expectations of how people think about it,
while also striving to express ourselves precisely.

-- 
 \              ?Dvorak users of the world flgkd!? ?Kirsten Chevalier, |
  `\                                                rec.humor.oracle.d |
_o__)                                                                  |
Ben Finney


From __peter__ at web.de  Wed Jul 20 07:54:40 2016
From: __peter__ at web.de (Peter Otten)
Date: Wed, 20 Jul 2016 13:54:40 +0200
Subject: [Tutor] python cgi single double quotes
References: <CAFSKaewdfD-XuvYSXBb0ARfdV=hpoH7xHfG6RNPjxR=VHUhSSQ@mail.gmail.com>
 <nmlua5$kuo$1@ger.gmane.org>
 <CAFSKaezKKooWFiS=57xFj+fby1_jT1Zru5MTCCRvgadUJtbt9w@mail.gmail.com>
 <nmndko$8p6$1@ger.gmane.org>
 <CAFSKaezC0iWaORdL5pqUZS=ZmqSiaB=oayaJCvg6kLNw2SF-0w@mail.gmail.com>
 <nmnh74$4pe$1@ger.gmane.org>
 <CAFSKaey6g7xMp2M9mfPv04HjtiSrt2Ch79EA=JxMnCssKUz+Lw@mail.gmail.com>
Message-ID: <nmnoq8$seo$1@ger.gmane.org>

nitin chandra wrote:

> Ran both the method

So everything seems to be working as expected. When you go back to your 
original script you can enable tracebacks rendered as html with

#!/usr/bin/env python
import cgitb
cgitb.enable()

... # your code

Provided there are no syntax errors in the script this should simplify 
detecting any exceptions the code may raise. If there is a traceback that 
doesn't make sense to you post it here to see if we can help.


From steve at pearwood.info  Wed Jul 20 08:03:57 2016
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 20 Jul 2016 22:03:57 +1000
Subject: [Tutor] Writing decorators?
In-Reply-To: <v2m36dxb1m.ln2@news.c0t0d0s0.de>
References: <CA+Q8_Jes1FV=1rHOZLSODAkRCtiUBOAnp5ygUQsXWi-F-co7RQ@mail.gmail.com>
 <v2m36dxb1m.ln2@news.c0t0d0s0.de>
Message-ID: <20160720120356.GC27919@ando.pearwood.info>

On Wed, Jul 20, 2016 at 09:33:19AM +0200, Michael Welle wrote:

> Somewhere in this thread (or the one talking about decorators after this
> thread) it was said that a decorator 'changes a function'. I not a
> native English speaker, so it could just be a language problem. But to
> me it seems the function is replaced, not changed?

It might have been me that used the term "changes a function".

A decorator can do anything. It can replace the function with a 
completely new one, ignoring the original function. It can wrap the 
original function in a closure, returning the wrapper. (The wrapper then 
calls the original function.) It can turn the function into a class, or 
a class into a function, or return something altogether different. It 
can modify the function and return it, or cause some side-effect and 
then return the original function with no changes made.

For example, here is a decorator that ensures that the function has a 
doc string, and inserts one if it doesn't:

def ensure_docstring(func):
    if func.__doc__ is None:
        func.__doc__ = "Please see the Fine Manual for '%s'" % func.__name__
    return func

@ensure_docstring
def myfunc(args):
    pass


In this case, the function object is actually changed, not replaced.

The most common form of decorator wraps the original function inside a 
new function, as a closure, and returns the wrapper:

def decorate(func):
    @functools.wraps(func)
    def inner(*args):
        print("inside the wrapper")
        result = func(*args)
        print("original returns %r" % result)
        return result  # can modify the result
    return inner

Even though the decorator is returning a new function, the original is 
still hidden deep inside that "inner" function, as part of the closure, 
so in a sense, it is just a change to that original: it is *wrapped* in 
another function, which does some pre-processing or post-processing, but 
the original still does most of the work.


Does that help explain matters?


-- 
Steve


From nitinchandra1 at gmail.com  Wed Jul 20 08:53:18 2016
From: nitinchandra1 at gmail.com (nitin chandra)
Date: Wed, 20 Jul 2016 18:23:18 +0530
Subject: [Tutor] python cgi single double quotes
In-Reply-To: <nmnoq8$seo$1@ger.gmane.org>
References: <CAFSKaewdfD-XuvYSXBb0ARfdV=hpoH7xHfG6RNPjxR=VHUhSSQ@mail.gmail.com>
 <nmlua5$kuo$1@ger.gmane.org>
 <CAFSKaezKKooWFiS=57xFj+fby1_jT1Zru5MTCCRvgadUJtbt9w@mail.gmail.com>
 <nmndko$8p6$1@ger.gmane.org>
 <CAFSKaezC0iWaORdL5pqUZS=ZmqSiaB=oayaJCvg6kLNw2SF-0w@mail.gmail.com>
 <nmnh74$4pe$1@ger.gmane.org>
 <CAFSKaey6g7xMp2M9mfPv04HjtiSrt2Ch79EA=JxMnCssKUz+Lw@mail.gmail.com>
 <nmnoq8$seo$1@ger.gmane.org>
Message-ID: <CAFSKaewMq5r3YsRihwP9aJqifgiXD16NJr=vuSdBCqPH8ziA5w@mail.gmail.com>

Me a little embarrassed :P ... but now when I retyped the code ... it
seems to be working....

Alan, Peter .. .Thank you.



On 20 July 2016 at 17:24, Peter Otten <__peter__ at web.de> wrote:
> nitin chandra wrote:
>
>> Ran both the method
>
> So everything seems to be working as expected. When you go back to your
> original script you can enable tracebacks rendered as html with
>
> #!/usr/bin/env python
> import cgitb
> cgitb.enable()
>
> ... # your code
>
> Provided there are no syntax errors in the script this should simplify
> detecting any exceptions the code may raise. If there is a traceback that
> doesn't make sense to you post it here to see if we can help.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

From steve at pearwood.info  Wed Jul 20 09:00:32 2016
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 20 Jul 2016 23:00:32 +1000
Subject: [Tutor] strange behavior of matrix**matrix
In-Reply-To: <e3415180-efb1-ba13-2193-fb28f36a847e@toya.net.pl>
References: <6ac21b06-4fb0-88d5-5cfb-166cf79f2642@toya.net.pl>
 <20160717152300.GT27919@ando.pearwood.info>
 <e3415180-efb1-ba13-2193-fb28f36a847e@toya.net.pl>
Message-ID: <20160720130031.GD27919@ando.pearwood.info>

On Wed, Jul 20, 2016 at 10:27:50AM +0200, AB wrote:
> Hello
> 
> W dniu 2016-07-17 o 17:23, Steven D'Aprano pisze:
> >[...]
> >What result did you expect? 2**-1 as an int32 cannot be 0.5, as that's a
> >float.
> 
> I expected 0.5: as 2^(-1) is in fact 1/2, and as in Python 3 division of 
> two integers 1/2 produces float 0.5, I naturally expected the case of 
> arrays to be consistent with this behavior.

Ah, but the exponentiation operator ** is not the division operator / 
and is not guaranteed to give the same results.

It looks to me that numpy has array[ints]/int coerce to array[floats], 
but array[ints]**int remains an array[ints]. In that case, they have to 
choose between 2**-1 rounds down to 0 or rounds up to 1, and they chose 
rounding down.

Would I make the same decision? Probably not.


> >I'm not really sure about the rules that numpy uses for coercing from
> >one type to another, but I'm not surprised by this result. I don't know
> >if it is documented anywhere, but it seems like the sort of thing numpy
> >would do.
> 
> I'm only learning Python, so the behavior of version 3 is natural to me.

That's why it was changed :-)



> >Here's another similar example:
> >
> >py> np.array([0])**-1
> >__main__:1: RuntimeWarning: divide by zero encountered in power
> >__main__:1: RuntimeWarning: invalid value encountered in power
> >array([-2147483648])
> 
> In my eye it's not similar - 1/0 should always produce an error, so the 
> behavior is exactly as expected.

The point is that the numpy functions seem to me to be designed to be as 
fast as possible, not as correct as possible. There's no integer value 
to represent INFINITY, like for floats, and for some reason the numpy 
people didn't want to halt the calculation with an error, so they have 
to return *something*, and it has to be a 32-bit signed integer:

-2147483648 is 32 "1" bits (including the sign), so that makes a good 
error value, at least if you think like a C programmer.

[...]
> I thought that this may be a 'sin of omission', to be corrected in some 
> future versions of numpy/scipy.

If you report it as a bug on the numpy bug tracker, they will hopefully 
either explain why they think its not a bug, or fix it.



-- 
Steve

From alan.gauld at yahoo.co.uk  Wed Jul 20 13:09:42 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 20 Jul 2016 18:09:42 +0100
Subject: [Tutor] Writing decorators?
In-Reply-To: <31b46dxqsg.ln2@news.c0t0d0s0.de>
References: <CA+Q8_Jes1FV=1rHOZLSODAkRCtiUBOAnp5ygUQsXWi-F-co7RQ@mail.gmail.com>
 <v2m36dxb1m.ln2@news.c0t0d0s0.de> <20160720120356.GC27919@ando.pearwood.info>
 <31b46dxqsg.ln2@news.c0t0d0s0.de>
Message-ID: <nmob8l$dr1$1@ger.gmane.org>

On 20/07/16 14:30, Michael Welle wrote:

> Now it gets interesting ;). Can you give me a hint on how to modify the
> code of the function in a decorator or even give a small example,
> please? Would I take the route with the bytecode attribute __code__
> (IIRC)? Or use the inspect module? 

Steven changed the function object by modifying the __doc__
attribute. It is probably possible to modify the __code__ too
but I'd strongly recommend that you don't. It's very likely to
result in something so "clever"/complex that it will never
be maintainable, and maintainability beats nearly everything
else in programming priorities.

If you cannot do what you want by wrapping the original
function you should probably just rewrite it to do what
you want. Or, if you own the code, refactor it into chunks
and combine the chunks into a new high level function.

-- 
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  Wed Jul 20 14:54:33 2016
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 21 Jul 2016 04:54:33 +1000
Subject: [Tutor] Writing decorators?
In-Reply-To: <31b46dxqsg.ln2@news.c0t0d0s0.de>
References: <CA+Q8_Jes1FV=1rHOZLSODAkRCtiUBOAnp5ygUQsXWi-F-co7RQ@mail.gmail.com>
 <v2m36dxb1m.ln2@news.c0t0d0s0.de> <20160720120356.GC27919@ando.pearwood.info>
 <31b46dxqsg.ln2@news.c0t0d0s0.de>
Message-ID: <20160720185433.GE27919@ando.pearwood.info>

On Wed, Jul 20, 2016 at 03:30:43PM +0200, Michael Welle wrote:

> > It [a decorator]
> > can modify the function and return it,
>
> Now it gets interesting ;). Can you give me a hint on how to modify the
> code of the function in a decorator or even give a small example,
> please? Would I take the route with the bytecode attribute __code__
> (IIRC)? Or use the inspect module? 

The inspect module is not really designed for changing objects, only for 
inspecting them. (Reading, not writing.)

Function code objects are immutable, so you cannot change them in place, 
only replace them with a new code object:

py> def f():
...     print("f")
...
py> def g():
...     print("g")
...
py> f()
f
py> f.__code__ = g.__code__
py> f()
g


The code object itself is very complex, and badly documented:

py> help(f.__code__)

Help on code object:

class code(object)
 |  code(argcount, kwonlyargcount, nlocals, stacksize, flags, codestring,
 |        constants, names, varnames, filename, name, firstlineno,
 |        lnotab[, freevars[, cellvars]])
 |
 |  Create a code object.  Not for the faint of heart.


so in practice the way to create them is by actually defining a 
function, then extracting its __code__ object. But if you're going to do 
that, why not just use the function?

There are a couple of projects designed to let you manipulate the 
byte-code of functions, but because the byte-code format is not part of 
the public Python API, it tends to change from version to version. If 
you use the wrong byte-code, you can crash the interpeter and cause a 
segmentation fault or core dump.

However, there is some talk about creating a interface to modify a 
function's abstract syntax tree. At the moment consider that to be just 
talk, but its more likely than a supported interface to edit byte-code. 

But for those brave, or silly, enough, here are some resources for 
editing byte-code to get you started:

http://www.voidspace.org.uk/python/articles/code_blocks.shtml
https://wiki.python.org/moin/ByteplayDoc


There are ways to modify functions apart from changing their code. For 
example, you can change argument defaults, add attributes to the 
function object, change the global namespace that the function works 
with. I have an experimental project that modifies functions so that 
instead of searching for variables in this order:

locals
nonlocals
globals
builtins


it uses:

locals
nonlocals
custom namespace set by the user
globals
builtins

(Technically, I don't "modify" the function, since some parts of the 
function are immutable and cannot be changed. Instead I replace it with 
a new function, copied from the original but with a slight 
modification.)


If you are interested in that, see the discussion that starts here:

https://mail.python.org/pipermail/python-list/2016-July/711177.html

The original version of the code I gave uses a metaclass; the version I 
have now also supports being called as a decorator.



-- 
Steve

From alan.gauld at yahoo.co.uk  Wed Jul 20 19:11:24 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 21 Jul 2016 00:11:24 +0100
Subject: [Tutor] python programmin problem
In-Reply-To: <20160720.141109.7713.1@webmail09.dca.untd.com>
References: <20160720.141109.7713.1@webmail09.dca.untd.com>
Message-ID: <5790051C.6050908@yahoo.co.uk>

On 20/07/16 22:11, monikajg at netzero.net wrote:
> ... if not in python, then in pseudo code.

The first question to ask is can you do it without a computer?
In other words given

input [1,7,2,3,5,4,6]

Can you first of all produce a list of all valid runs?

[1,2,3,5,6] and [1,2,3,4,6] both have length 5

I also see shorter runs:

[7] and [4,6] for example.

Can you manually create a list of all valid runs?

Once you can do that can you write a program to
generate that as a list of lists in Python?

If so then the answer to your question is a matter of
finding the length of the longest valid run which
should be fairly easy.

-- 
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 yahoo.co.uk  Wed Jul 20 20:26:59 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 21 Jul 2016 01:26:59 +0100
Subject: [Tutor] python programmin problem
In-Reply-To: <20160720.161449.5694.1@webmail10.dca.untd.com>
References: <20160720.161449.5694.1@webmail10.dca.untd.com>
Message-ID: <579016D3.1020808@yahoo.co.uk>

On 21/07/16 00:14, monikajg at netzero.net wrote:
> IM not able to figure out algorithm to find the runs.
> Here is the code I have:

OK, Forget about code for now. just focus on what is being asked.

> > The first question to ask is can you do it without a computer?
> > In other words given
> >
> > input [1,7,2,3,5,4,6]
> >
> > Can you first of all produce a list of all valid runs?

Lets try it manually. Start with 1

run = []
1 > run[-1] so add it to the run -> [1]
1 is followed by 7 which >run[-1] so add it to the run -> [1,7]
7 is followed by 2 which <run[-1] so delete 7 from the run -> [1]
2 is now greater than run[-1] so add it to the run -> [1,2]
2 is followed by 3 which is > run[-1] so add it to the run -> [1,2,3]
3 is followed by 5 which is > run[-1] so add it to the run -> [1,2,3,5]
5 is followed by 4 which is <run[-1]  so delete run[-1] - [1,2,3]
4 is now >run[-1] so add it to the run -> [1,2,3,4]
4 is followed by 6 which is > run[-1] so add it to the run -> [1,2,3,4,6]
6 is not followed by anything, run complete.

Can you see an algorithm there that you can code?
Its not quite complete because it never catches the [1,2,3,5,6] case
but its a start. And there are probably more efficient algorithms too,
but we are interested in easy to code here not speed.

-- 
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 monikajg at netzero.net  Wed Jul 20 17:11:09 2016
From: monikajg at netzero.net (monikajg at netzero.net)
Date: Wed, 20 Jul 2016 21:11:09 GMT
Subject: [Tutor] python programmin problem
Message-ID: <20160720.141109.7713.1@webmail09.dca.untd.com>

Hi:
Can somebody please provide answer to following python programming question? I have spent days on it and cannot come up with any code that would make any sense for it so I cannot provide you any code. But I would appreciate the answer very much, if not in python, then in pseudo code.
Thank you very much
Monika

Here is the problem:
Given a list of integers, return the progress of the test
The progress is defined as the length of the longest run of strictly increasing scores "with gaps allowed".
That is the length of the longest group of numbers such that each number in that block is strictly larger than the previous number, and the group can be formed by choosing some subset of values in the order they appear in the original
list. All values are integers.
input [1,7,2,3,5,4,6] returns 5
[1,2,3,5,6] and [1,2,3,4,6] both have length 5 and are longer than any other runs
Returning 7 is incorrect for [1,2,3,4,5,6,7] as it changes the ordering of the original sequence.
Input [1,2,3,4] the run [1,2,3,4] is the entire test and has lenght 4. returns 4
Input [4, 3, 2, 1] returns 1 each result is a run of 1. so we return 1
Input [1,2,0,4,5] return 5 longest run [1,2,4,5] has lenght 4



____________________________________________________________
Affordable Wireless Plans
Set up is easy. Get online in minutes.
Starting at only $9.95 per month! 
www.netzero.net?refcd=nzmem0216

From monikajg at netzero.net  Wed Jul 20 19:14:49 2016
From: monikajg at netzero.net (monikajg at netzero.net)
Date: Wed, 20 Jul 2016 23:14:49 GMT
Subject: [Tutor] python programmin problem
Message-ID: <20160720.161449.5694.1@webmail10.dca.untd.com>

IM not able to figure out algorithm to find the runs.
Here is the code I have:

def ProgressCalc(items):
    counts = [items[0]]
    for i in range(1, len(items)-1):
        print "for loop", items[i], items[i + 1]
        if counts[- 1] < items[i]:
            counts += [items[i]]
            print "inside", items[i], items[i - 1], counts

    print counts


    counts = [items[0]]
    for i in range(1, len(items) - 1):
        print "for loop", items[i], items[i + 1]
        if counts[- 1] <= items[i] and items[i] < items[i + 1]:
            counts += [items[i]]
            print "inside", items[i], items[i - 1], counts
        elif counts[- 1] <= items[i] and items[i] > items[i + 1]:
            counts += [items[i]]
            i += 2
    print counts
ProgressCalc(items)    

---------- Original Message ----------
From: Alan Gauld <alan.gauld at yahoo.co.uk>
To: "monikajg at netzero.net" <monikajg at netzero.net>
Cc: tutor at python.org
Subject: Re: python programmin problem
Date: Thu, 21 Jul 2016 00:11:24 +0100

On 20/07/16 22:11, monikajg at netzero.net wrote:
> ... if not in python, then in pseudo code.

The first question to ask is can you do it without a computer?
In other words given

input [1,7,2,3,5,4,6]

Can you first of all produce a list of all valid runs?

[1,2,3,5,6] and [1,2,3,4,6] both have length 5

I also see shorter runs:

[7] and [4,6] for example.

Can you manually create a list of all valid runs?

Once you can do that can you write a program to
generate that as a list of lists in Python?

If so then the answer to your question is a matter of
finding the length of the longest valid run which
should be fairly easy.

-- 
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


____________________________________________________________
Affordable Wireless Plans
Set up is easy. Get online in minutes.
Starting at only $9.95 per month! 
www.netzero.net?refcd=nzmem0216

From dyoo at hashcollision.org  Thu Jul 21 01:22:19 2016
From: dyoo at hashcollision.org (Danny Yoo)
Date: Wed, 20 Jul 2016 22:22:19 -0700
Subject: [Tutor] python programmin problem
In-Reply-To: <20160720.141109.7713.1@webmail09.dca.untd.com>
References: <20160720.141109.7713.1@webmail09.dca.untd.com>
Message-ID: <CAGZAPF7W9guDRvY86Mg0a965m75w8VLXGWSKWe7t=ibPZOn=kA@mail.gmail.com>

On Wed, Jul 20, 2016 at 2:11 PM, monikajg at netzero.net
<monikajg at netzero.net> wrote:
> Hi:
> Can somebody please provide answer to following python programming question? I have spent days on it and cannot come up with any code that would make any sense for it so I cannot provide you any code. But I would appreciate the answer very much, if not in python, then in pseudo code.
> Thank you very much
> Monika
>
> Here is the problem:
> Given a list of integers, return the progress of the test
> The progress is defined as the length of the longest run of strictly increasing scores "with gaps allowed".


If I understand the question being asked, this is often presented as an
exercise for the technique of "dynamic programming".

    https://en.wikipedia.org/wiki/Dynamic_programming

However, your question hasn't used the term "dynamic programming".

Are you familiar with this term?

If so, have you been exposed to other problems that can be solved with
"dynamic programming"?

Your problem is a rough restatement of the "longest increasing
subsequence" problem.

    https://en.wikipedia.org/wiki/Longest_increasing_subsequence

Unfortunately, solving this problem is a bit out of scope for Python
tutor because it's more advanced than the material we typically talk
about here (basic Python programming).  I don't think we can help
very much.


You may get better help by talking with your instructor or study group.

From dyoo at hashcollision.org  Thu Jul 21 01:38:05 2016
From: dyoo at hashcollision.org (Danny Yoo)
Date: Wed, 20 Jul 2016 22:38:05 -0700
Subject: [Tutor] Help me out please
In-Reply-To: <CAGcE6NNRiDq6WbUE0UwmSL2v-vXKZPkxvTJ_z9GGt339Gdtf2w@mail.gmail.com>
References: <CAGcE6NNRiDq6WbUE0UwmSL2v-vXKZPkxvTJ_z9GGt339Gdtf2w@mail.gmail.com>
Message-ID: <CAGZAPF63HRzZb0SUFSQKxp8f8i5NvR4g+TLoyhtE3-gpsR0U=Q@mail.gmail.com>

On Tue, Jul 19, 2016 at 4:31 AM, Marc S?nchez Quibus
<sanchezquibus at gmail.com> wrote:
> Hi,
> First of all I'm gonan introduce myself. My name is Marc and I'm a student
> and also a python's programmer begginer. I've been studying/learning python
> and now I need some help to finish my project.
> I have two scripts, one of them in python (the main script) and the other
> one written in html. Well, is just a brief javascript (an app) that I took
> by Github. I need to change a variable inside this html script. I was
> wondering wether I could change this variable from my python script or not.
> Is there some way to do it?

Hi Marc,

Yes.  You might want to read something like this to get some
background.  Phil Greenspun's Guide to Web Publishing:

    http://philip.greenspun.com/panda/

Specifically, the chapter "Sites that are really progarms".

    http://philip.greenspun.com/panda/server-programming

You mentioned that you have two scripts, one in Python and the other in HTML.

A web site can be seen as this: something that (1) takes in a web
request sent by a browser, and (2) spits out a web response.

A static web site takes in a web request, looks for an appropriate
file, and prints that file back as a web response.  But that's not the
only way we can build web responses.  A programmatic web site can take
that request and *generate* a web page on the fly.  A web site can
actually be a program: not just a plain text file.


There are a lot of resources to teach how to write programs that serve
web sites.  Another by the same author is
http://philip.greenspun.com/seia/, which goes into a lot more detail.

From night_skystar at hotmail.com  Thu Jul 21 07:50:37 2016
From: night_skystar at hotmail.com (la Y)
Date: Thu, 21 Jul 2016 11:50:37 +0000
Subject: [Tutor] need help with socket / fuzzer not sure the while loop
 condition is wrong
Message-ID: <HK2PR0301MB097921218E5BF3A96DA0D03C99090@HK2PR0301MB0979.apcprd03.prod.outlook.com>

need help with socket / fuzzer not sure the while loop condition is wrong - its superpose to fuzz testing programs over till program crashes but seems to have some errors.



import os
import sys
import datetime
import socket


def fuzzer():
    #fuzzer
    #user attack coordinates and junk
    currentEta = datetime.datetime.now()
    targetIP = raw_input("hello what is the target IP destinaition address: ")
    socketPort = int(raw_input("what port number : "))

    while ( socketPort < 4 ) and (socketPort <= 65535):
        socketPort = int(socketPort)

    junkData = raw_input("paste your junk for fuzzing [pattern create would be perfered]")



    # Symbolic name meaning all available interface
    #  Arbitrary non-privileged port
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((targetIP , socketPort ))
    s.listen(1)
    conn, addr = s.accept()
    print ("Connected by",+ addr)

    counter = 0
    print(currentEta)
    print("Current Phase 1 initated")
    print(targetIP)
    print(socketPort)
    print(junkData)

    print(":sending:=================> fuzzie fuzzie")

    while conn.open(counter,junkData,data):
        counter =+ 1
        junkData = junkData + 1
        print(counter)
        print(junkData)
        data = conn.recv(1024)
        if not data: break
        conn.sendall(junkData)
        conn.open()


#option selection
print("Please Select an option")
options = input("1: Fuzzer n/ 2: Port Scanner ")

if options == 1:
    #run
    fuzzer()
elif options == 0:
    exit()


From alan.gauld at yahoo.co.uk  Thu Jul 21 14:04:35 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 21 Jul 2016 19:04:35 +0100
Subject: [Tutor] need help with socket / fuzzer not sure the while loop
 condition is wrong
In-Reply-To: <HK2PR0301MB097921218E5BF3A96DA0D03C99090@HK2PR0301MB0979.apcprd03.prod.outlook.com>
References: <HK2PR0301MB097921218E5BF3A96DA0D03C99090@HK2PR0301MB0979.apcprd03.prod.outlook.com>
Message-ID: <nmr2ri$3dr$1@ger.gmane.org>

On 21/07/16 12:50, la Y wrote:
> need help with socket / fuzzer 


UI've no idea what fuzzer means but...

> not sure the while loop condition is wrong

> def fuzzer():
>     #fuzzer
>     #user attack coordinates and junk
>     currentEta = datetime.datetime.now()
>     targetIP = raw_input("hello what is the target IP destinaition address: ")
>     socketPort = int(raw_input("what port number : "))
> 
>     while ( socketPort < 4 ) and (socketPort <= 65535):
>         socketPort = int(socketPort)

This makes no sense at all.

The socketPort is already an int because you make it so
on the raw_input line.

If it is <4 it will also be less than 65535 so the "and"
test is superfluous.

And if it is <4 the while loop will run forever because
you never change the value of socketPort.

if
x = int(n)
then
int(x) == x

is always true

I've no idea what the loop is intended to do so I can't
comment on whether you need to just delete it or whether
you need to modify it somehow.


-- 
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  Thu Jul 21 16:17:48 2016
From: dyoo at hashcollision.org (Danny Yoo)
Date: Thu, 21 Jul 2016 13:17:48 -0700
Subject: [Tutor] Fwd: Re:  Help me out please
In-Reply-To: <CAGZAPF732FQ+u1BMm+erBmu8tz8UHZHuU0_Gx4GjaAinY7Phow@mail.gmail.com>
References: <CAGcE6NNRiDq6WbUE0UwmSL2v-vXKZPkxvTJ_z9GGt339Gdtf2w@mail.gmail.com>
 <CAGZAPF63HRzZb0SUFSQKxp8f8i5NvR4g+TLoyhtE3-gpsR0U=Q@mail.gmail.com>
 <CAGcE6NPV0D9XBiDdJCTDYZVFBmXLmrf4QKmbxcbwuz=61tq-Lw@mail.gmail.com>
 <CAGZAPF732FQ+u1BMm+erBmu8tz8UHZHuU0_Gx4GjaAinY7Phow@mail.gmail.com>
Message-ID: <CAGZAPF4CQTE0+-5t55WPJSyFLrJs7tCC1CFde1hhmGXNi5sQbA@mail.gmail.com>

Apologies: I don't have time at the moment to answer.  Forwarding to the
mailing list!
---------- Forwarded message ----------
From: "Marc S?nchez Quibus" <sanchezquibus at gmail.com>
Date: Jul 21, 2016 12:08 AM
Subject: Re: [Tutor] Help me out please
To: "Danny Yoo" <dyoo at hashcollision.org>
Cc:

Thanks for your fast reply. I'm gonna explain a little bit more about my
problem to be more understood.
Well, I have two scripts. One in Python and the other one in html.
Inside the html's script you can find out these lines:

<script>
    initLatencymon(
        '#latencyMON',
        {},
        { measurements:[*3679333, 3793762*]}
        );
</script>

I need to change these *bold *variables from the Python's script. Inside
this one, there are just some prints, system's functions and so on. I would
like to create, at least, some variable in python to select the value of
the varible in HTML. Better if it could be chosen as input( ). Either some
variable or a function. If you need more infromation let me know.
Thanks in advance.
Marc

2016-07-21 7:38 GMT+02:00 Danny Yoo <dyoo at hashcollision.org>:

> On Tue, Jul 19, 2016 at 4:31 AM, Marc S?nchez Quibus
> <sanchezquibus at gmail.com> wrote:
> > Hi,
> > First of all I'm gonan introduce myself. My name is Marc and I'm a
> student
> > and also a python's programmer begginer. I've been studying/learning
> python
> > and now I need some help to finish my project.
> > I have two scripts, one of them in python (the main script) and the other
> > one written in html. Well, is just a brief javascript (an app) that I
> took
> > by Github. I need to change a variable inside this html script. I was
> > wondering wether I could change this variable from my python script or
> not.
> > Is there some way to do it?
>
> Hi Marc,
>
> Yes.  You might want to read something like this to get some
> background.  Phil Greenspun's Guide to Web Publishing:
>
>     http://philip.greenspun.com/panda/
>
> Specifically, the chapter "Sites that are really progarms".
>
>     http://philip.greenspun.com/panda/server-programming
>
> You mentioned that you have two scripts, one in Python and the other in
> HTML.
>
> A web site can be seen as this: something that (1) takes in a web
> request sent by a browser, and (2) spits out a web response.
>
> A static web site takes in a web request, looks for an appropriate
> file, and prints that file back as a web response.  But that's not the
> only way we can build web responses.  A programmatic web site can take
> that request and *generate* a web page on the fly.  A web site can
> actually be a program: not just a plain text file.
>
>
> There are a lot of resources to teach how to write programs that serve
> web sites.  Another by the same author is
> http://philip.greenspun.com/seia/, which goes into a lot more detail.
>



-- 
*Marc S?nchez Quibus*

From alan.gauld at yahoo.co.uk  Thu Jul 21 17:53:02 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 21 Jul 2016 22:53:02 +0100
Subject: [Tutor] Fwd: Re: Help me out please
In-Reply-To: <CAGZAPF4CQTE0+-5t55WPJSyFLrJs7tCC1CFde1hhmGXNi5sQbA@mail.gmail.com>
References: <CAGcE6NNRiDq6WbUE0UwmSL2v-vXKZPkxvTJ_z9GGt339Gdtf2w@mail.gmail.com>
 <CAGZAPF63HRzZb0SUFSQKxp8f8i5NvR4g+TLoyhtE3-gpsR0U=Q@mail.gmail.com>
 <CAGcE6NPV0D9XBiDdJCTDYZVFBmXLmrf4QKmbxcbwuz=61tq-Lw@mail.gmail.com>
 <CAGZAPF732FQ+u1BMm+erBmu8tz8UHZHuU0_Gx4GjaAinY7Phow@mail.gmail.com>
 <CAGZAPF4CQTE0+-5t55WPJSyFLrJs7tCC1CFde1hhmGXNi5sQbA@mail.gmail.com>
Message-ID: <nmrg7s$o10$1@ger.gmane.org>

On 21/07/16 21:17, Danny Yoo wrote:

> Well, I have two scripts. One in Python and the other one in html.
> Inside the html's script you can find out these lines:
> 
> <script>
>     initLatencymon(
>         '#latencyMON',
>         {},
>         { measurements:[*3679333, 3793762*]}
>         );
> </script>
> 
> I need to change these *bold *variables from the Python's script. 

That's technically not too difficult at a file level, especially if
you use an html parser like Beautiful Soup. But whether that's the
best way depends on how the files are used.

How is the html file accessed? Is it independent of the python script?
In other words doers the python script run as a batch job that only
updates the values occasionally? Or regularly? (How often?) or is it on
demand - some other trigger starts the Python script?
Or does the Python script somehow start from an action by the html script?

Its all very vague just saying you have two files.
WE need to understand the intended interaction between them.

If it is just a daily or hourly update then the html parser
route is probably adequate. If its driven by an external
trigger then it might be ok but might not.

And if its driven by the html script itself then we almost
certainly need a redesign of how you are doing things.

So can you start by explaining the use case scenario
for these interactions. How do the file get executed?
What triggers them?

How do they interact (if, indeed, they do)?

-- 
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 yahoo.co.uk  Fri Jul 22 02:30:31 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 22 Jul 2016 07:30:31 +0100
Subject: [Tutor] python programmin problem
In-Reply-To: <20160721.220249.428.0@webmail11.dca.untd.com>
References: <20160721.220249.428.0@webmail11.dca.untd.com>
Message-ID: <5791BD87.3080308@yahoo.co.uk>


Forwarding to list. Please use reply-all when responding to tutor messages.

As Danny suggested this is quite a complex problem. I wasn't sure whether
it was just the programming or the bigger algorithm issue you were stuck on.

For now I'd stick with the code you have and think about how to use that
to build up a list of runs and then find the longest. Hint: Start
testing at
progressive items in your initial sequence.

Hopefully somebody else can pick this up as I have to go away for a fewys...

Alan G.

On 22/07/16 06:02, monikajg at netzero.net wrote:
> Hi:
> Thank you so much for your suggestion. I was able to turn it into the code but Im stuck on catching the [1,2,3,5,6] case case. Could you please be so kind and give me a hint? I apologize for not having much experience on this but things like that were never taught in any of the classes I took and I have nowhere else to ask.
> Thank you so much.
> Monika
>
>
> Here is my code:
>
>     run = []
>     for i in range(len(items)):
>         if i == 0:
>             run += [items[i]]
>             continue
>         else:
>             if items[i - 1] < items[i]:
>                 run +=[ items[i]]
>             elif items[i - 1] > items[i]:
>                 del run[-1]
>                 run += [items[i]]
>         print run
>
> ---------- Original Message ----------
> From: Alan Gauld via Tutor <tutor at python.org>
> To: "monikajg at netzero.net" <monikajg at netzero.net>
> Cc: tutor at python.org
> Subject: Re: [Tutor] python programmin problem
> Date: Thu, 21 Jul 2016 01:26:59 +0100
>
> On 21/07/16 00:14, monikajg at netzero.net wrote:
>> IM not able to figure out algorithm to find the runs.
>> Here is the code I have:
> OK, Forget about code for now. just focus on what is being asked.
>
>>> The first question to ask is can you do it without a computer?
>>> In other words given
>>>
>>> input [1,7,2,3,5,4,6]
>>>
>>> Can you first of all produce a list of all valid runs?
> Lets try it manually. Start with 1
>
> run = []
> 1 > run[-1] so add it to the run -> [1]
> 1 is followed by 7 which >run[-1] so add it to the run -> [1,7]
> 7 is followed by 2 which <run[-1] so delete 7 from the run -> [1]
> 2 is now greater than run[-1] so add it to the run -> [1,2]
> 2 is followed by 3 which is > run[-1] so add it to the run -> [1,2,3]
> 3 is followed by 5 which is > run[-1] so add it to the run -> [1,2,3,5]
> 5 is followed by 4 which is <run[-1]  so delete run[-1] - [1,2,3]
> 4 is now >run[-1] so add it to the run -> [1,2,3,4]
> 4 is followed by 6 which is > run[-1] so add it to the run -> [1,2,3,4,6]
> 6 is not followed by anything, run complete.
>
> Can you see an algorithm there that you can code?
> Its not quite complete because it never catches the [1,2,3,5,6] case
> but its a start. And there are probably more efficient algorithms too,
> but we are interested in easy to code here not speed.
>


-- 
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  Sat Jul 23 03:13:36 2016
From: dyoo at hashcollision.org (Danny Yoo)
Date: Sat, 23 Jul 2016 00:13:36 -0700
Subject: [Tutor] python programmin problem
In-Reply-To: <5791BD87.3080308@yahoo.co.uk>
References: <20160721.220249.428.0@webmail11.dca.untd.com>
 <5791BD87.3080308@yahoo.co.uk>
Message-ID: <CAGZAPF6-FXpRs75jOjHiTdpBdie_RRmNeiB3LNYJfoCvjq57-g@mail.gmail.com>

On Thu, Jul 21, 2016 at 11:30 PM, Alan Gauld via Tutor <tutor at python.org> wrote:
>
> Forwarding to list. Please use reply-all when responding to tutor messages.
>
> As Danny suggested this is quite a complex problem. I wasn't sure whether
> it was just the programming or the bigger algorithm issue you were stuck on.

[warning: large message ahead.]


This problem is unfortunately not something you can just code by
trying to hack it till it works.  At this level of difficulty, these
kinds of problems are *not* easy: they require some understanding of
fundamentals in algorithms, not Python.  That is, the actual coding of
this is not the hard part.  A direct solution to this problem is a
couple of lines and involves nothing more loops and arrays.  The
difficulty is understanding how to use solutions of sub-problems
toward the general large problem.


I should state this more strongly: trying to hack the solution is not
going to work.  I have to ignore the code presented in this thread
because there's very little to preserve.  The approach of trying to
look at only the very previous element is simply not viable.  The most
direct approach I know to do this is by talking about this in terms of
subproblems.


Here is a sketch of the idea:

Let's put on our magical thinking cap, and say that we'd like to
design a function L(A, m) with the following funny property:

For array A of length N, and for an integer k < N:

  L(A, k) is the length of the longest increasing subsequence of the
prefix of A with length k, where that subsequence needs to include the
k'th element too.

What is L?  This L function tries to capture the idea of having a
*partial* solution that involves a portion of the array A.


Why is it helpful?  Because of two crucial things:

    1.  If we know L(A, 1), L(A, 2), ... all the way to L(A, N), then
we can just look at the maximum value of those pieces.  That's going
to be a solution to the general problem.


    2.  For a subproblem L(A, k), if we know the values for L(A, 1),
L(A, 2), ... , L(A, k-1), then we can compute L(A, k) by looking at
those other subproblems: the result of L(A, k) is related to them.

How so?

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


As a concrete example, consider a list A = [5, 8, 6, 7].


* What is L(A, 1)?  We want the length of the longest subsequence of
the prefix [5] that includes the 5.  And that's just 1.

   L(A, 1) = 1.

That is, we're starting from scratch: we can't do better than just
pick the 5 as the start of our subsequence.  Since our subsequence
just has [5], that's a subsequence of length 1.


* What is L(A, 2)?  We want the length of the longest subsequence of
the prefix [5, 8] that includes the 8.  Why does knowing L(A, 1) help
us?  Because we know L(A, 1) is 1.  What does that mean?  We look at
L(A, 1) to see if maybe we can pick the subsequence that it is
measuring, and augment it.


We know L(A, 1) is the length of the longest sequence that ends up
including the first element of A, so we know that subsequence ends
with a [... 5].  And we can extend that subsequence so it look like
[..., 5, 8].  And we know that such an extension will be of length 2.
Can we do any better?  There are no other subproblems, so no.

That is, L(A, 2) = 2.


* What is L(A, 3)?  We want the length of the longest subsequence of
the prefix [5, 8, 6] that includes the 6.

    We look at L(A, 1): can we just extend [..., 5] with a 6?  Yes,
and that gives us 2 as a possible answer for L(A, 3).  Why 2?  Because
L(A, 1) = 1, and if we extend the subsequence measured by L(A, 1), we
make it one element longer, so 1 + 1 = 2.

    Can we do better?

    We look at L(A, 2): can we just extend [..., 8] with a 6?  No.

Ok, so L(A, 3) = 2.


* What is L(A, 4)?  We want the length of the longest subsequence of
the prefix [5, 8, 6, 7] that includes the 7.

   We look at L(A, 1):.  Can we just extend [..., 5] with a 7?  Yes,
and that gives us 2 as a possible answer for L(A, 4).

   Can we do better?

   We look at L(A, 2).  Can we just extend [..., 8] with a 7?  No.

   Can we do better?

   We look at L(A, 3).  Can we just extend [..., 6] with a 7?  Yes,
and that gives us 3 as a possible answer for L(A, 4).  Why 3?  Because
L(A, 3) = 2, and if we extend the subsequence measured by L(A, 3), we
make it one element longer, so 2+1 = 3.


Ok, we've got L(A, 1), L(A, 2), L(A, 3), and L(A, 4).

Which one was the largest?  3.  What's the subsequence that's of
length 3?  We know it's [5, 6, 7], and that's length 3, so that seems
to match.

So the length of the longest subsequence of the whole A is 3.

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


Generalizing: when we're looking for a solution for L(A, k), we can
look at the prior values L(A, 1), L(A, 2), ... L(A, k), because those
represent the lengths of other longest subsequences that we can extend
by including the k'th element.  But we've got to look to see if the
extension is valid ifrst, and that requires looking at elements of A
at the respective positions.  Once we do this, we can then pick the
one that gives us the longest valid extension.

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

You need to try to do similar reasoning for smaller examples to
convince yourself that this approach works in general.  For example,
try it on the input [5, 8, 3].
.


This is the kind of process that's expected when solving this class of
problems.  If you haven't seen this style of attacking a problem by
relating to smaller subproblems, then we strongly urge you to please
talk with your professor or study group.

From jf_byrnes at comcast.net  Sat Jul 23 11:38:52 2016
From: jf_byrnes at comcast.net (Jim Byrnes)
Date: Sat, 23 Jul 2016 10:38:52 -0500
Subject: [Tutor] Variable in tkinter?
Message-ID: <nn032c$j1t$1@ger.gmane.org>

I have been working my way through a Python 3 book and got to the 
chapter on tkinter. The following is a segment of a example program that 
works:

# the views
frame = tkinter.Frame(window)
frame.pack()
button = tkinter.Button(frame, text='Up', command=click_up)
button.pack()
button = tkinter.Button(frame, text='Down', command=click_down)
button.pack()
label = tkinter.Label(frame, textvariable=counter)
label.pack()

when I first looked at it I thought it would not work, thinking that the 
second reference to button = would over write the first one. Obviously 
that is wrong because the program does work.  Could someone explain to 
me why it works?

Regards,  Jim


From amonroe at columbus.rr.com  Sat Jul 23 13:55:03 2016
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Sat, 23 Jul 2016 13:55:03 -0400
Subject: [Tutor] Variable in tkinter?
In-Reply-To: <nn032c$j1t$1@ger.gmane.org>
References: <nn032c$j1t$1@ger.gmane.org>
Message-ID: <633613714.20160723135503@columbus.rr.com>

> button = tkinter.Button(frame, text='Up', command=click_up)
> button = tkinter.Button(frame, text='Down', command=click_down)


> when I first looked at it I thought it would not work, thinking that the
> second reference to button = would over write the first one.

It DOES overwrite it, in this sense:

The first button is a thing that exists because Button() generates it.
"button" is a word you can now use to refer to that thing.

Later on, the second call to Button() generates a new, separate thing.
"button" is now a word you can use to refer to the second thing,
but *the first thing doesn't cease to exist*.

Alan



From beachkidken at gmail.com  Sun Jul 24 11:38:06 2016
From: beachkidken at gmail.com (Ken G.)
Date: Sun, 24 Jul 2016 11:38:06 -0400
Subject: [Tutor] Program won't print out in Windows 10
Message-ID: <0e28e522-73d0-d756-3908-46a71530aae3@gmail.com>

While the following program prints out fine using

Python 2.7.6 in Ubuntu 14.04.4 as developed using

Geany 1.23.1, same program won't print out to printer

under Windows 10 Pro (64 bit). Geany uses there is

version 1.28 using Python 2.7.12. I can use CTRL-P

to print out the listing.

=================================

# hello2.py

import os

print
print "Hello World!"
print
pr = os.popen("lpr", "w")
for i in range(1,8):
     pr.write("\n")
pr.write("\n")
pr.write("\t\t01  02  03  04  05")
pr.write("\n")
pr.close
print
print("\tPlease wait several moments for printer to catch up.")
print

===================================

Thanking you readers in advance in resolving this non

Windows printing issue.


From steve at pearwood.info  Sun Jul 24 12:28:18 2016
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 25 Jul 2016 02:28:18 +1000
Subject: [Tutor] Program won't print out in Windows 10
In-Reply-To: <0e28e522-73d0-d756-3908-46a71530aae3@gmail.com>
References: <0e28e522-73d0-d756-3908-46a71530aae3@gmail.com>
Message-ID: <20160724162816.GO27919@ando.pearwood.info>

On Sun, Jul 24, 2016 at 11:38:06AM -0400, Ken G. wrote:
> While the following program prints out fine using
> Python 2.7.6 in Ubuntu 14.04.4 as developed using
> Geany 1.23.1, same program won't print out to printer
> under Windows 10 Pro (64 bit). Geany uses there is
> version 1.28 using Python 2.7.12. I can use CTRL-P
> to print out the listing.

The critical piece of code that does the printing is the external 
function "lpr". This is not part of Python: it is a Unix/Linux command 
that controls the "line printer". On some machines lpr doesn't exist and 
it may be called "lp" instead.

Does lpr or lp exist on Windows 10? I can see it exists in Windows 7.

If you open up a Windows shell, the command.com or cmd.exe or whatever 
it is called, and enter "lpr", what happens?

Perhaps you are getting a permissions error. Perhaps lpr simply isn't 
installed, or isn't configured properly, or can't find your printer.

Once you get lpr working from the Windows 10 command line, then and only 
then can you hope to get it working from Python.


-- 
Steve

From steve at pearwood.info  Sun Jul 24 12:29:34 2016
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 25 Jul 2016 02:29:34 +1000
Subject: [Tutor] Variable in tkinter?
In-Reply-To: <633613714.20160723135503@columbus.rr.com>
References: <nn032c$j1t$1@ger.gmane.org>
 <633613714.20160723135503@columbus.rr.com>
Message-ID: <20160724162934.GP27919@ando.pearwood.info>

On Sat, Jul 23, 2016 at 01:55:03PM -0400, R. Alan Monroe wrote:
> > button = tkinter.Button(frame, text='Up', command=click_up)
> > button = tkinter.Button(frame, text='Down', command=click_down)
> 
> 
> > when I first looked at it I thought it would not work, thinking that the
> > second reference to button = would over write the first one.
> 
> It DOES overwrite it, in this sense:
> 
> The first button is a thing that exists because Button() generates it.
> "button" is a word you can now use to refer to that thing.
> 
> Later on, the second call to Button() generates a new, separate thing.
> "button" is now a word you can use to refer to the second thing,
> but *the first thing doesn't cease to exist*.

Why not? Why isn't the first button not garbage collected?




-- 
Steve

From __peter__ at web.de  Sun Jul 24 13:20:51 2016
From: __peter__ at web.de (Peter Otten)
Date: Sun, 24 Jul 2016 19:20:51 +0200
Subject: [Tutor] Variable in tkinter?
References: <nn032c$j1t$1@ger.gmane.org>
 <633613714.20160723135503@columbus.rr.com>
 <20160724162934.GP27919@ando.pearwood.info>
Message-ID: <nn2tdm$qak$1@ger.gmane.org>

Steven D'Aprano wrote:

> On Sat, Jul 23, 2016 at 01:55:03PM -0400, R. Alan Monroe wrote:
>> > button = tkinter.Button(frame, text='Up', command=click_up)
>> > button = tkinter.Button(frame, text='Down', command=click_down)
>> 
>> 
>> > when I first looked at it I thought it would not work, thinking that
>> > the second reference to button = would over write the first one.
>> 
>> It DOES overwrite it, in this sense:
>> 
>> The first button is a thing that exists because Button() generates it.
>> "button" is a word you can now use to refer to that thing.
>> 
>> Later on, the second call to Button() generates a new, separate thing.
>> "button" is now a word you can use to refer to the second thing,
>> but *the first thing doesn't cease to exist*.
> 
> Why not? Why isn't the first button not garbage collected?

The answer is of course always the same: because there is another reference.
The hard part is also always the same: how can that reference be found?

Here's a way to do it in this case:

$ cat tksnippet.py
import tkinter

window = tkinter.Tk()

def click_up():
    pass

def click_down():
    pass

counter = tkinter.StringVar()

frame = tkinter.Frame(window)
frame.pack()
button = tkinter.Button(frame, text='Up', command=click_up)
button.pack()

print("button whose reference we are going to overwrite:")
print(repr(button), button)

button = tkinter.Button(frame, text='Down', command=click_down)
button.pack()

label = tkinter.Label(frame, textvariable=counter)
label.pack()
$ python3 -i tksnippet.py 
button whose reference we are going to overwrite:
<tkinter.Button object at 0x7f5412a9ca90> .139999066974024.139999067097744
>>> forgotten_button = 
frame.nametowidget(".139999066974024.139999067097744")
>>> forgotten_button
<tkinter.Button object at 0x7f5412a9ca90>
>>> forgotten_button["text"]
'Up'

So it is indeed the up-button rather than a reused memory address.

The above snippet is only for demonstration purposes; if you plan to access 
a widget later-on you should always use the straightforward approach and 
keep a reference around in your own code.



From alan.gauld at yahoo.co.uk  Sun Jul 24 15:08:35 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 24 Jul 2016 20:08:35 +0100
Subject: [Tutor] Variable in tkinter?
In-Reply-To: <nn032c$j1t$1@ger.gmane.org>
References: <nn032c$j1t$1@ger.gmane.org>
Message-ID: <nn33nj$l5r$1@ger.gmane.org>

On 23/07/16 16:38, Jim Byrnes wrote:

> # the views
> frame = tkinter.Frame(window)
> frame.pack()
> button = tkinter.Button(frame, text='Up', command=click_up)
> button.pack()
> button = tkinter.Button(frame, text='Down', command=click_down)
> button.pack()

> that is wrong because the program does work.  Could someone explain to 
> me why it works?

Others have pointed out that a hidden reference to the buttons exists.
In fact Tkinter, in common with most GUIIs, works by building a tree of
objects starting at the top level window and then working down thru'
each lower level.

Usuially in Tkinter we start with  a line like

top = tkinter.Tk()   # create the topmost widget

Then when we create subwidgets, like your frame we
pass the outer widget as the parent:

frame = tkinter.Frame(top)

Then when you create the buttons you pass frame
as the first argument which makes frame the parent
of the buttons.

What happens is that when you create the widget the
parent object adds your new instance to its list of
child widgets. And that's the hidden reference that keeps
your button alive even after you overwrite the button
variable.

You can access the widget tree of any widget using
its 'children' attribute:


>>> import tkinter as tk
>>> top = tk.Tk()
>>> f = tk.Frame(top)
>>> f.pack()
>>> tk.Label(f,text="Hello there!").pack()
>>> f.children
{'140411123026128': <tkinter.Label object at 0x7fb4031c48d0>}
>>>

But it's not very user friendly so if you need to access
a widget after creating it its better to use a unique
variable to store a reference.

-- 
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 monikajg at netzero.net  Sat Jul 23 12:26:45 2016
From: monikajg at netzero.net (monikajg at netzero.net)
Date: Sat, 23 Jul 2016 16:26:45 GMT
Subject: [Tutor] python programmin problem
Message-ID: <20160723.092645.23877.0@webmail08.dca.untd.com>

IM sorry I do not understand:

For array A of length N, and for an integer k < N:
-- By k do you mean value of k or position of k in the list?

  L(A, k) is the length of the longest increasing subsequence of the
prefix of A with length k, where that subsequence needs to include the
k'th element too.

What is L?  This L function tries to capture the idea of having a
*partial* solution that involves a portion of the array A.


Why is it helpful?  Because of two crucial things:

    1.  If we know L(A, 1), L(A, 2), ... all the way to L(A, N), then
we can just look at the maximum value of those pieces.  That's going
to be a solution to the general problem.
-- By maximum value do you mean I have to sum up the values in the list? Why?


    2.  For a subproblem L(A, k), if we know the values for L(A, 1),
L(A, 2), ... , L(A, k-1), then we can compute L(A, k) by looking at
those other subproblems: the result of L(A, k) is related to them.
-- How do we find those subproblems? And then how do you relate them to the main problem?

Can you please explain more in details? 
Thank you so much
Monika
---------- Original Message ----------
From: Danny Yoo <dyoo at hashcollision.org>
To: Alan Gauld <alan.gauld at yahoo.co.uk>
Cc: "monikajg at netzero.net" <monikajg at netzero.net>, tutor <tutor at python.org>
Subject: Re: [Tutor] python programmin problem
Date: Sat, 23 Jul 2016 00:13:36 -0700

On Thu, Jul 21, 2016 at 11:30 PM, Alan Gauld via Tutor <tutor at python.org> wrote:
>
> Forwarding to list. Please use reply-all when responding to tutor messages.
>
> As Danny suggested this is quite a complex problem. I wasn't sure whether
> it was just the programming or the bigger algorithm issue you were stuck on.

[warning: large message ahead.]


This problem is unfortunately not something you can just code by
trying to hack it till it works.  At this level of difficulty, these
kinds of problems are *not* easy: they require some understanding of
fundamentals in algorithms, not Python.  That is, the actual coding of
this is not the hard part.  A direct solution to this problem is a
couple of lines and involves nothing more loops and arrays.  The
difficulty is understanding how to use solutions of sub-problems
toward the general large problem.


I should state this more strongly: trying to hack the solution is not
going to work.  I have to ignore the code presented in this thread
because there's very little to preserve.  The approach of trying to
look at only the very previous element is simply not viable.  The most
direct approach I know to do this is by talking about this in terms of
subproblems.


Here is a sketch of the idea:

Let's put on our magical thinking cap, and say that we'd like to
design a function L(A, m) with the following funny property:

For array A of length N, and for an integer k < N:

  L(A, k) is the length of the longest increasing subsequence of the
prefix of A with length k, where that subsequence needs to include the
k'th element too.

What is L?  This L function tries to capture the idea of having a
*partial* solution that involves a portion of the array A.


Why is it helpful?  Because of two crucial things:

    1.  If we know L(A, 1), L(A, 2), ... all the way to L(A, N), then
we can just look at the maximum value of those pieces.  That's going
to be a solution to the general problem.


    2.  For a subproblem L(A, k), if we know the values for L(A, 1),
L(A, 2), ... , L(A, k-1), then we can compute L(A, k) by looking at
those other subproblems: the result of L(A, k) is related to them.

How so?

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


As a concrete example, consider a list A = [5, 8, 6, 7].


* What is L(A, 1)?  We want the length of the longest subsequence of
the prefix [5] that includes the 5.  And that's just 1.

   L(A, 1) = 1.

That is, we're starting from scratch: we can't do better than just
pick the 5 as the start of our subsequence.  Since our subsequence
just has [5], that's a subsequence of length 1.


* What is L(A, 2)?  We want the length of the longest subsequence of
the prefix [5, 8] that includes the 8.  Why does knowing L(A, 1) help
us?  Because we know L(A, 1) is 1.  What does that mean?  We look at
L(A, 1) to see if maybe we can pick the subsequence that it is
measuring, and augment it.


We know L(A, 1) is the length of the longest sequence that ends up
including the first element of A, so we know that subsequence ends
with a [... 5].  And we can extend that subsequence so it look like
[..., 5, 8].  And we know that such an extension will be of length 2.
Can we do any better?  There are no other subproblems, so no.

That is, L(A, 2) = 2.


* What is L(A, 3)?  We want the length of the longest subsequence of
the prefix [5, 8, 6] that includes the 6.

    We look at L(A, 1): can we just extend [..., 5] with a 6?  Yes,
and that gives us 2 as a possible answer for L(A, 3).  Why 2?  Because
L(A, 1) = 1, and if we extend the subsequence measured by L(A, 1), we
make it one element longer, so 1 + 1 = 2.

    Can we do better?

    We look at L(A, 2): can we just extend [..., 8] with a 6?  No.

Ok, so L(A, 3) = 2.


* What is L(A, 4)?  We want the length of the longest subsequence of
the prefix [5, 8, 6, 7] that includes the 7.

   We look at L(A, 1):.  Can we just extend [..., 5] with a 7?  Yes,
and that gives us 2 as a possible answer for L(A, 4).

   Can we do better?

   We look at L(A, 2).  Can we just extend [..., 8] with a 7?  No.

   Can we do better?

   We look at L(A, 3).  Can we just extend [..., 6] with a 7?  Yes,
and that gives us 3 as a possible answer for L(A, 4).  Why 3?  Because
L(A, 3) = 2, and if we extend the subsequence measured by L(A, 3), we
make it one element longer, so 2+1 = 3.


Ok, we've got L(A, 1), L(A, 2), L(A, 3), and L(A, 4).

Which one was the largest?  3.  What's the subsequence that's of
length 3?  We know it's [5, 6, 7], and that's length 3, so that seems
to match.

So the length of the longest subsequence of the whole A is 3.

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


Generalizing: when we're looking for a solution for L(A, k), we can
look at the prior values L(A, 1), L(A, 2), ... L(A, k), because those
represent the lengths of other longest subsequences that we can extend
by including the k'th element.  But we've got to look to see if the
extension is valid ifrst, and that requires looking at elements of A
at the respective positions.  Once we do this, we can then pick the
one that gives us the longest valid extension.

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

You need to try to do similar reasoning for smaller examples to
convince yourself that this approach works in general.  For example,
try it on the input [5, 8, 3].
.


This is the kind of process that's expected when solving this class of
problems.  If you haven't seen this style of attacking a problem by
relating to smaller subproblems, then we strongly urge you to please
talk with your professor or study group.
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


____________________________________________________________
Affordable Wireless Plans
Set up is easy. Get online in minutes.
Starting at only $9.95 per month! 
www.netzero.net?refcd=nzmem0216

From diliupg at gmail.com  Fri Jul 22 03:38:02 2016
From: diliupg at gmail.com (DiliupG)
Date: Fri, 22 Jul 2016 13:08:02 +0530
Subject: [Tutor] (no subject)
Message-ID: <CAMxbqSOA1PG8nRFpg5hDJiYEj0cYZXpD43+VaRJ39yX7Sk760g@mail.gmail.com>

I am using Python 2.7.12 on Windows 10

filename = "??? ???????? ????????.txt"
Why can't I get Python to print the name out?

filename =  "??? ???????? ????????.txt"
Unsupported characters in input

filename = u"??? ???????? ????????.txt"
Unsupported characters in input

above is the python ide output

Even from within a program I cant get this to print.

any help? Please dont ask me to use python 3.

:)

-- 
Kalasuri Diliup Gabadamudalige

http://www.diliupg.com
http://soft.diliupg.com/

**********************************************************************************************
This e-mail is confidential. It may also be legally privileged. If you are
not the intended recipient or have received it in error, please delete it
and all copies from your system and notify the sender immediately by return
e-mail. Any unauthorized reading, reproducing, printing or further
dissemination of this e-mail or its contents is strictly prohibited and may
be unlawful. Internet communications cannot be guaranteed to be timely,
secure, error or virus-free. The sender does not accept liability for any
errors or omissions.
**********************************************************************************************

From ing.jdj at gmail.com  Sat Jul 23 04:12:55 2016
From: ing.jdj at gmail.com (=?UTF-8?Q?Jos=C3=A9_de_Jesus_Marquez_Rangel?=)
Date: Sat, 23 Jul 2016 03:42:55 -0430
Subject: [Tutor] Help with error in paramiko
Message-ID: <CAKOV8800aKtOCvJr0KLYRjdarotfdLAr2LznzhTWKYk2GjFs7A@mail.gmail.com>

Hello.

I have a problem because when I connect to the remote server via SSH gives
me an error with paramiko library, but I connect to the same server with
programs like putty, ssh and another there is no error.

Here the screenshot:

*Script.*
[image: Im?genes integradas 1]

*the result of run*
[image: Im?genes integradas 7]



*the result of log.*

The problem is when the ZAHO command with the library in the logs can see
the error highlighted runs.


*[image: Im?genes integradas 6]*

*PD: *The feature of the remote server unknown but the script work on the
Linux server.


Feature the computer client.

Windows 7 64bits.
Python3.4
Library paramiko,

From marcus.luetolf at bluewin.ch  Sat Jul 23 15:06:14 2016
From: marcus.luetolf at bluewin.ch (=?iso-8859-1?Q?marcus_l=FCtolf?=)
Date: Sat, 23 Jul 2016 21:06:14 +0200
Subject: [Tutor] installing openpyxl
Message-ID: <013001d1e515$4c0190e0$e404b2a0$@bluewin.ch>

Dear Experts,

following instructions in a youtube video I thought I finally succeded to
install openpyxl.
However I got the traceback below:

>>> import openpyxl

Traceback (most recent call last):

  File "<pyshell#0>", line 1, in <module>

    import openpyxl

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\__init__.py", line 29, in <module>

    from openpyxl.workbook import Workbook

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\workbook\__init__.py", line 5, in <module>

    from .workbook import Workbook

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\workbook\workbook.py", line 8, in <module>

    from openpyxl.worksheet import Worksheet

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\worksheet\__init__.py", line 4, in <module>

    from .worksheet import Worksheet

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\worksheet\worksheet.py", line 34, in <module>

    from openpyxl.cell import Cell

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\cell\__init__.py", line 4, in <module>

    from .cell import Cell, WriteOnlyCell

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\cell\cell.py", line 30, in <module>

    from openpyxl.utils.datetime  import (

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\utils\datetime.py", line 13, in <module>

    from jdcal import (

ImportError: No module named 'jdcal'

 

How do I get ?jdcal? ?
Tanks everybody for help, Marcus.























..

 

dear Experts,


could someone please tell me what exactly I have to type in my a) Python 35
? command line or 

b) desktopcomputer ( W10, 64bit)-command line in ordert to install openpyxl
which I downloaded in

C:\Users\marcus\Downloads on my computer. 
I have used all kinds of commands with ?pip install? at the end, all
unsuccessful.

 

Thanks for help.

Marcus.

 



---
Diese E-Mail wurde von Avast Antivirus-Software auf Viren gepr?ft.
https://www.avast.com/antivirus

From marcus.luetolf at bluewin.ch  Sun Jul 24 15:04:11 2016
From: marcus.luetolf at bluewin.ch (=?iso-8859-1?Q?marcus_l=FCtolf?=)
Date: Sun, 24 Jul 2016 21:04:11 +0200
Subject: [Tutor] installing openpyxl, problem solved
Message-ID: <01f901d1e5de$2cae5ce0$860b16a0$@bluewin.ch>

Dear Experts, problem solved, don?t bother, Marcus.


































.

 

Dear Experts,

following instructions in a youtube video I thought I finally succeded to
install openpyxl.
However I got the traceback below:

>>> import openpyxl

Traceback (most recent call last):

  File "<pyshell#0>", line 1, in <module>

    import openpyxl

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\__init__.py", line 29, in <module>

    from openpyxl.workbook import Workbook

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\workbook\__init__.py", line 5, in <module>

    from .workbook import Workbook

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\workbook\workbook.py", line 8, in <module>

    from openpyxl.worksheet import Worksheet

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\worksheet\__init__.py", line 4, in <module>

    from .worksheet import Worksheet

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\worksheet\worksheet.py", line 34, in <module>

    from openpyxl.cell import Cell

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\cell\__init__.py", line 4, in <module>

    from .cell import Cell, WriteOnlyCell

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\cell\cell.py", line 30, in <module>

    from openpyxl.utils.datetime  import (

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\utils\datetime.py", line 13, in <module>

    from jdcal import (

ImportError: No module named 'jdcal'

 

How do I get ?jdcal? ?
Tanks everybody for help, Marcus.























..

 

dear Experts,


could someone please tell me what exactly I have to type in my a) Python 35
? command line or 

b) desktopcomputer ( W10, 64bit)-command line in ordert to install openpyxl
which I downloaded in

C:\Users\marcus\Downloads on my computer. 
I have used all kinds of commands with ?pip install? at the end, all
unsuccessful.

 

Thanks for help.

Marcus.

 



---
Diese E-Mail wurde von Avast Antivirus-Software auf Viren gepr?ft.
https://www.avast.com/antivirus

From jf_byrnes at comcast.net  Sun Jul 24 15:27:06 2016
From: jf_byrnes at comcast.net (Jim Byrnes)
Date: Sun, 24 Jul 2016 14:27:06 -0500
Subject: [Tutor] Variable in tkinter?
In-Reply-To: <nn33nj$l5r$1@ger.gmane.org>
References: <nn032c$j1t$1@ger.gmane.org> <nn33nj$l5r$1@ger.gmane.org>
Message-ID: <nn34qa$5dv$1@ger.gmane.org>

On 07/24/2016 02:08 PM, Alan Gauld via Tutor wrote:
> On 23/07/16 16:38, Jim Byrnes wrote:
>
>> # the views
>> frame = tkinter.Frame(window)
>> frame.pack()
>> button = tkinter.Button(frame, text='Up', command=click_up)
>> button.pack()
>> button = tkinter.Button(frame, text='Down', command=click_down)
>> button.pack()
>
>> that is wrong because the program does work.  Could someone explain to
>> me why it works?
>
> Others have pointed out that a hidden reference to the buttons exists.
> In fact Tkinter, in common with most GUIIs, works by building a tree of
> objects starting at the top level window and then working down thru'
> each lower level.
>
> Usuially in Tkinter we start with  a line like
>
> top = tkinter.Tk()   # create the topmost widget
>
> Then when we create subwidgets, like your frame we
> pass the outer widget as the parent:
>
> frame = tkinter.Frame(top)
>
> Then when you create the buttons you pass frame
> as the first argument which makes frame the parent
> of the buttons.
>
> What happens is that when you create the widget the
> parent object adds your new instance to its list of
> child widgets. And that's the hidden reference that keeps
> your button alive even after you overwrite the button
> variable.
>
> You can access the widget tree of any widget using
> its 'children' attribute:
>
>
>>>> import tkinter as tk
>>>> top = tk.Tk()
>>>> f = tk.Frame(top)
>>>> f.pack()
>>>> tk.Label(f,text="Hello there!").pack()
>>>> f.children
> {'140411123026128': <tkinter.Label object at 0x7fb4031c48d0>}
>>>>
>
> But it's not very user friendly so if you need to access
> a widget after creating it its better to use a unique
> variable to store a reference.
>

Thanks Peter and Alan,

After I proved to myself that it worked and I thought about it, I 
suspected it had to do with a reference.  It's nice to have it confirmed 
is such a clear manner.

Regards,  Jim


From mail at timgolden.me.uk  Sun Jul 24 15:54:33 2016
From: mail at timgolden.me.uk (Tim Golden)
Date: Sun, 24 Jul 2016 20:54:33 +0100
Subject: [Tutor] Program won't print out in Windows 10
In-Reply-To: <0e28e522-73d0-d756-3908-46a71530aae3@gmail.com>
References: <0e28e522-73d0-d756-3908-46a71530aae3@gmail.com>
Message-ID: <e58c1555-c9fd-9232-1791-b33453d4aa41@timgolden.me.uk>

On 24/07/2016 16:38, Ken G. wrote:
> While the following program prints out fine using
>
> Python 2.7.6 in Ubuntu 14.04.4 as developed using
>
> Geany 1.23.1, same program won't print out to printer
>
> under Windows 10 Pro (64 bit). Geany uses there is
>
> version 1.28 using Python 2.7.12. I can use CTRL-P
>
> to print out the listing.

> Thanking you readers in advance in resolving this non
>
> Windows printing issue.

Rather: user believing that what works under Linux will work under 
Windows issue :)

You might find this page helpful:

http://timgolden.me.uk/python/win32_how_do_i/print.html

TJG

From dyoo at hashcollision.org  Sun Jul 24 15:58:08 2016
From: dyoo at hashcollision.org (Danny Yoo)
Date: Sun, 24 Jul 2016 12:58:08 -0700
Subject: [Tutor] python programmin problem
In-Reply-To: <20160723.092645.23877.0@webmail08.dca.untd.com>
References: <20160723.092645.23877.0@webmail08.dca.untd.com>
Message-ID: <CAGZAPF5fL1N+4NNAAJ-n_dUFUyQ9fim+oEc33C5OaCF2=J6k6w@mail.gmail.com>

On Jul 23, 2016 9:27 AM, "monikajg at netzero.net" <monikajg at netzero.net>
wrote:
>
> IM sorry I do not understand:
>
> For array A of length N, and for an integer k < N:
> -- By k do you mean value of k or position of k in the list?
>

The letter 'k' is typically intended to be used as an index, a position
into a list.  I'm trying to say that k had to be pointed somewhere in the
list by constraining it to be less than the size of the list.

>
>     1.  If we know L(A, 1), L(A, 2), ... all the way to L(A, N), then
> we can just look at the maximum value of those pieces.  That's going
> to be a solution to the general problem.
> -- By maximum value do you mean I have to sum up the values in the list?
Why?

"Maximum" is a notion of comparing and picking out the biggest thing we
see.  It doesn't have to do with addition.

If we have a bunch of numbers, we can do a lot more than just add then
together. Numbers are more interesting than that.

Both summation and maximum-finding are operations that are intended to take
a bunch of bits of information in order to discover something new.  So,
conceptually speaking, there *is* a deep, underlying connection.  But I
don't think that's what you're intending to talk about.

>     2.  For a subproblem L(A, k), if we know the values for L(A, 1),
> L(A, 2), ... , L(A, k-1), then we can compute L(A, k) by looking at
> those other subproblems: the result of L(A, k) is related to them.
> -- How do we find those subproblems? And then how do you relate them to
the main problem?
>
> Can you please explain more in details?

Unfortunately, no.  This is the wrong venue.

Please: I strongly encourage you to talk with your professor or study
group: it really does sound like this is the first time you've seen these
kinds of concepts.  Longest common subsequence is not the ideal problem to
use to introduce these concepts: it is meant to help you *master* them.  I
would not dare trying to use it as a first example into learning dynamic
programming.

You probably want to use a problem that has fewer moving parts.  Your
instructor likely has a much nicer introductory problem so that you can
learn the patterns of thinking through these problems.

Anyway, hope that makes sense.

From danny.yoo at gmail.com  Sun Jul 24 16:28:11 2016
From: danny.yoo at gmail.com (Danny Yoo)
Date: Sun, 24 Jul 2016 13:28:11 -0700
Subject: [Tutor] python programmin problem
In-Reply-To: <CAGZAPF6QLO6GSUWnFaYVHovi8Q1-7Eop2T++YTr_8uWqfGb1OQ@mail.gmail.com>
References: <20160723.092645.23877.0@webmail08.dca.untd.com>
 <CAGZAPF5fL1N+4NNAAJ-n_dUFUyQ9fim+oEc33C5OaCF2=J6k6w@mail.gmail.com>
 <CAGZAPF4dZEWTy8LxtDaNeKDGFTUpi7Ms6anxJuHSTKFfN+KEaQ@mail.gmail.com>
 <CAGZAPF6QLO6GSUWnFaYVHovi8Q1-7Eop2T++YTr_8uWqfGb1OQ@mail.gmail.com>
Message-ID: <CAGZAPF4B272dnHsymGjv9VcXucd87EOFUotOfyKfMBPKSVyFJA@mail.gmail.com>

> You probably want to use a problem that has fewer moving parts.  Your
instructor likely has a much nicer introductory problem so that you can
learn the patterns of thinking through these problems.

Just to add: there are online resources you can use for this.  Khan
Academy, for example:
https://www.khanacademy.org/computing/computer-science/algorithms.  For
self study, i can also recommend Introduction to Algorithms.
https://mitpress.mit.edu/books/introduction-algorithms.

When I'm using the term "subproblem", I'm mentally recalling the training I
received from learning about recursion.  Recursion is much more than about
functions calling themselves. That is, if we've learned about recursion and
thought: "why use recursion when you have loops?", then we've missed a key
point, which is this: it's intended to teach how to think about subproblems
and synthesizing from them.  That's the answer I should have given to your
question about thinking about subproblems.

From alan.gauld at yahoo.co.uk  Sun Jul 24 19:21:10 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 25 Jul 2016 00:21:10 +0100
Subject: [Tutor] python programmin problem
In-Reply-To: <CAGZAPF5fL1N+4NNAAJ-n_dUFUyQ9fim+oEc33C5OaCF2=J6k6w@mail.gmail.com>
References: <20160723.092645.23877.0@webmail08.dca.untd.com>
 <CAGZAPF5fL1N+4NNAAJ-n_dUFUyQ9fim+oEc33C5OaCF2=J6k6w@mail.gmail.com>
Message-ID: <nn3ih6$6ro$1@ger.gmane.org>

On 24/07/16 20:58, Danny Yoo wrote:

> Please: I strongly encourage you to talk with your professor or study
> group: it really does sound like this is the first time you've seen these
> kinds of concepts.  

I agree with Danny, you should talk to your teacher.
I suspect the teacher may have set the problem without appreciating
the full extent of the complexity involved. It certainly doesn't
seem like you are properly equipped to solve it. Maybe he/she can
provide a simpler subset of problem.

Of course this assumes you have a teacher to ask? Your original
post doesn't state where you found the problem, it may be you
just picked it up on a web site or book  and have unwittingly
bitten off more than you are ready to chew just now?

It also depends a bit on whether the intent is to learn about
Python programming or about algorithms. If its the latter then
you might just want to ask on a different (math based) forum.
But if its Python you are interested in then find an easier
problem for now. Otherwise you will lose sight of the Python
problem in trying to solve the math one.

-- 
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 yahoo.co.uk  Sun Jul 24 19:24:20 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 25 Jul 2016 00:24:20 +0100
Subject: [Tutor] Help with error in paramiko
In-Reply-To: <CAKOV8800aKtOCvJr0KLYRjdarotfdLAr2LznzhTWKYk2GjFs7A@mail.gmail.com>
References: <CAKOV8800aKtOCvJr0KLYRjdarotfdLAr2LznzhTWKYk2GjFs7A@mail.gmail.com>
Message-ID: <nn3in4$94t$1@ger.gmane.org>

On 23/07/16 09:12, Jos? de Jesus Marquez Rangel wrote:
> Hello.
> 
> I have a problem because when I connect to the remote server via SSH gives
> me an error with paramiko library, but I connect to the same server with
> programs like putty, ssh and another there is no error.
> 
> Here the screenshot:
> 
> *Script.*
> [image: Im?genes integradas 1]
> 
> *the result of run*
> [image: Im?genes integradas 7]
> 

This is a text based forum and as such your images didn't make it
through the server. If possible just copy/paste the text into a mail
message.

Also paramiko is really outside the scope of this group (core language
and standard library) so you might do better on a paramiko forum
such as their mailing list:

 paramiko at librelist.com


-- 
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 yahoo.co.uk  Sun Jul 24 19:25:38 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 25 Jul 2016 00:25:38 +0100
Subject: [Tutor] installing openpyxl, problem solved
In-Reply-To: <01f901d1e5de$2cae5ce0$860b16a0$@bluewin.ch>
References: <01f901d1e5de$2cae5ce0$860b16a0$@bluewin.ch>
Message-ID: <nn3ipi$94t$2@ger.gmane.org>

On 24/07/16 20:04, marcus l?tolf wrote:
> Dear Experts, problem solved, don?t bother, Marcus.


For the sake of the archive can you post a short
mail stating what the solution was?


-- 
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 monikajg at netzero.net  Sun Jul 24 19:30:40 2016
From: monikajg at netzero.net (monikajg at netzero.net)
Date: Sun, 24 Jul 2016 23:30:40 GMT
Subject: [Tutor] python programmin problem
Message-ID: <20160724.163040.26810.0@webmail13.dca.untd.com>

Thank you all for your answers. I do not have a teacher or any body else who could guide me. I have taken all python classes offered in my area and many on line.
The question is one of questions asked by interviews for a qa position that also does some automation with python. Im just trying to learn so that I could get a job. Nobody offers manual qa jobs anymore so I am working on updating my skills.

---------- Original Message ----------
From: Alan Gauld via Tutor <tutor at python.org>
To: tutor at python.org
Subject: Re: [Tutor] python programmin problem
Date: Mon, 25 Jul 2016 00:21:10 +0100

On 24/07/16 20:58, Danny Yoo wrote:

> Please: I strongly encourage you to talk with your professor or study
> group: it really does sound like this is the first time you've seen these
> kinds of concepts.  

I agree with Danny, you should talk to your teacher.
I suspect the teacher may have set the problem without appreciating
the full extent of the complexity involved. It certainly doesn't
seem like you are properly equipped to solve it. Maybe he/she can
provide a simpler subset of problem.

Of course this assumes you have a teacher to ask? Your original
post doesn't state where you found the problem, it may be you
just picked it up on a web site or book  and have unwittingly
bitten off more than you are ready to chew just now?

It also depends a bit on whether the intent is to learn about
Python programming or about algorithms. If its the latter then
you might just want to ask on a different (math based) forum.
But if its Python you are interested in then find an easier
problem for now. Otherwise you will lose sight of the Python
problem in trying to solve the math one.

-- 
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


____________________________________________________________
Affordable Wireless Plans
Set up is easy. Get online in minutes.
Starting at only $9.95 per month! 
www.netzero.net?refcd=nzmem0216

From rus.cahimb at gmail.com  Mon Jul 25 00:15:42 2016
From: rus.cahimb at gmail.com (Ramanathan Muthaiah)
Date: Mon, 25 Jul 2016 04:15:42 +0000
Subject: [Tutor] (no subject)
In-Reply-To: <CAMxbqSOA1PG8nRFpg5hDJiYEj0cYZXpD43+VaRJ39yX7Sk760g@mail.gmail.com>
References: <CAMxbqSOA1PG8nRFpg5hDJiYEj0cYZXpD43+VaRJ39yX7Sk760g@mail.gmail.com>
Message-ID: <CAGBd0eqRtoj5zR5=S_V3uY0fT2JK2P1AGbTtPBRg0Vn1mSAkbg@mail.gmail.com>

Hi Dilip,

This error has nothing to do with Python or it's versions.
OS does not have the support for these unicode characters. You need to fix
that.


> filename = "??? ???????? ????????.txt"
> Why can't I get Python to print the name out?
>
> filename =  "??? ???????? ????????.txt"
> Unsupported characters in input
>

--
regards
Ram

From steve at pearwood.info  Mon Jul 25 06:28:29 2016
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 25 Jul 2016 20:28:29 +1000
Subject: [Tutor] (no subject)
In-Reply-To: <CAMxbqSOA1PG8nRFpg5hDJiYEj0cYZXpD43+VaRJ39yX7Sk760g@mail.gmail.com>
References: <CAMxbqSOA1PG8nRFpg5hDJiYEj0cYZXpD43+VaRJ39yX7Sk760g@mail.gmail.com>
Message-ID: <20160725102828.GR27919@ando.pearwood.info>

On Fri, Jul 22, 2016 at 01:08:02PM +0530, DiliupG wrote:
> I am using Python 2.7.12 on Windows 10

Two errors:

- first error is that Unicode strings in Python 2 need to be written as 
unicode objects, with a "u" prefix in the delimiter:

# ASCII byte string:
"Hello World"

# Unicode string:

u"??? ?"

ASCII strings "..." cannot give you the right results except by 
accident. You must use unicode strings u"..."

- Second possible problem: using Windows, which may not support the 
characters you are trying to use. I don't know -- try it and see. If it 
still doesn't work, then blame Windows. I know that Linux and Mac OS X 
both use UTF-8 for filenames, and so support all of Unicode. But 
Windows, I'm not sure. It might be localised to only use Latin-1 
(Western European) or similar.


-- 
Steve

From eryksun at gmail.com  Mon Jul 25 07:19:46 2016
From: eryksun at gmail.com (eryk sun)
Date: Mon, 25 Jul 2016 11:19:46 +0000
Subject: [Tutor] (no subject)
In-Reply-To: <CAMxbqSOA1PG8nRFpg5hDJiYEj0cYZXpD43+VaRJ39yX7Sk760g@mail.gmail.com>
References: <CAMxbqSOA1PG8nRFpg5hDJiYEj0cYZXpD43+VaRJ39yX7Sk760g@mail.gmail.com>
Message-ID: <CACL+1atrJb_kpSDSqig3XW7wAjx408vLdZXXfPkM=sHwrQ3UoQ@mail.gmail.com>

On Fri, Jul 22, 2016 at 7:38 AM, DiliupG <diliupg at gmail.com> wrote:
> I am using Python 2.7.12 on Windows 10
>
> filename = u"??? ???????? ????????.txt"
> Unsupported characters in input

That error message is from IDLE. I'm not an expert with IDLE, so I
don't know what the following hack potentially breaks, but it does
allow entering the above Unicode filename in the interactive
interpreter.

Edit "Python27\Lib\idlelib\IOBinding.py". Look for the following
section on line 34:

    if sys.platform == 'win32':
        # On Windows, we could use "mbcs". However, to give the user
        # a portable encoding name, we need to find the code page
        try:
            encoding = locale.getdefaultlocale()[1]
            codecs.lookup(encoding)
        except LookupError:
            pass

Replace the encoding value with "utf-8" as follows:

            # encoding = locale.getdefaultlocale()[1]
            encoding = "utf-8"

When you restart IDLE, you should see that sys.stdin.encoding is now "utf-8".

IOBinding.encoding is used by ModifiedInterpreter.runsource in
PyShell.py. When the encoding is UTF-8, it passes the Unicode source
string directly to InteractiveInterpreter.runsource, where it gets
compiled using the built-in compile() function.

Note that IDLE uses the Tk GUI toolkit, which -- at least with Python
Tkinter on Windows -- is limited to the first 65,536 Unicode
characters, i.e the Basic Multilingual Plane. The BMP includes
Sinhalese, so your filename string is fine.

From eryksun at gmail.com  Mon Jul 25 07:55:20 2016
From: eryksun at gmail.com (eryk sun)
Date: Mon, 25 Jul 2016 11:55:20 +0000
Subject: [Tutor] (no subject)
In-Reply-To: <20160725102828.GR27919@ando.pearwood.info>
References: <CAMxbqSOA1PG8nRFpg5hDJiYEj0cYZXpD43+VaRJ39yX7Sk760g@mail.gmail.com>
 <20160725102828.GR27919@ando.pearwood.info>
Message-ID: <CACL+1at5ppfPvP1BtTV+hd644XQMb+A2wM7uCrBkUggCbDGJmw@mail.gmail.com>

On Mon, Jul 25, 2016 at 10:28 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> I know that Linux and Mac OS X both use UTF-8 for filenames, and so support all
> of Unicode. But Windows, I'm not sure. It might be localised to only use Latin-1
> (Western European) or similar.

Windows filesystems (e.g. NTFS, ReFS, UDF, exFAT, FAT32) use Unicode
[1], i.e. UTF-16, as does the Windows wide-character API. Using 16-bit
wchar_t strings is a problem for C standard functions such as fopen,
which require 8-bit null-terminated strings, so the Windows C runtime
also supports wide-character alternatives such as _wfopen.

Python's os and io functions use Windows wide-character APIs for
unicode arguments, even in 2.x. Unfortunately some 2.x modules such as
subprocess use only the 8-bit API (e.g. 2.x Popen calls CreateProcessA
instead of CreateProcessW).

[1]: https://msdn.microsoft.com/en-us/library/ee681827#limits

From marcus.luetolf at bluewin.ch  Mon Jul 25 14:59:50 2016
From: marcus.luetolf at bluewin.ch (=?iso-8859-1?Q?marcus_l=FCtolf?=)
Date: Mon, 25 Jul 2016 20:59:50 +0200
Subject: [Tutor] installing openpyxl, problem still n o t solved
Message-ID: <b8a201d1e6a6$bbb647e0$3322d7a0$@bluewin.ch>

Dear Experts, 

I was too optimistic. Module ?jdcal? ist indeed installed.
However, I get another trace back concerning ?et_xmlfile? even after I
downloaded and saved it the same way as I did with ?jdcal?.

Since I haven?t got any responses to my previous calls for help ? my problem
might be too unimportant - I just try it another time:

Why got ?jdcal? accepted and ?et_xmlfile? not ?
I must say I unzipped both files directly in
C:\Users\marcus\AppData\local\Programs\Python\Python35\Lib\site-packages.

The command  >pip install was rejected as SyntaxError : invalid syntax.
Thanks for any kind of help, Marcus.

 

 

>>> import openpyxl

Traceback (most recent call last):

  File "<pyshell#0>", line 1, in <module>

    import openpyxl

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\__init__.py", line 29, in <module>

    from openpyxl.workbook import Workbook

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\workbook\__init__.py", line 5, in <module>

    from .workbook import Workbook

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\workbook\workbook.py", line 8, in <module>

    from openpyxl.worksheet import Worksheet

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\worksheet\__init__.py", line 4, in <module>

    from .worksheet import Worksheet

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\worksheet\worksheet.py", line 34, in <module>

    from openpyxl.cell import Cell

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\cell\__init__.py", line 4, in <module>

    from .cell import Cell, WriteOnlyCell

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\cell\cell.py", line 44, in <module>

    from openpyxl.styles import numbers, is_date_format

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\styles\__init__.py", line 5, in <module>

    from .alignment import Alignment

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\styles\alignment.py", line 6, in <module>

    from openpyxl.descriptors import Bool, MinMax, Min, Alias, NoneSet

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\descriptors\__init__.py", line 5, in <module>

    from .sequence import Sequence

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\descriptors\sequence.py", line 5, in <module>

    from openpyxl.xml.functions import Element

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\xml\functions.py", line 51, in <module>

    from et_xmlfile import xmlfile

ImportError: No module named 'et_xmlfile'

>>> 

 

 

 

 

 

Dear Experts, problem solved, don?t bother, Marcus.


































.

 

Dear Experts,

following instructions in a youtube video I thought I finally succeded to
install openpyxl.
However I got the traceback below:

>>> import openpyxl

Traceback (most recent call last):

  File "<pyshell#0>", line 1, in <module>

    import openpyxl

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\__init__.py", line 29, in <module>

    from openpyxl.workbook import Workbook

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\workbook\__init__.py", line 5, in <module>

    from .workbook import Workbook

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\workbook\workbook.py", line 8, in <module>

    from openpyxl.worksheet import Worksheet

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\worksheet\__init__.py", line 4, in <module>

    from .worksheet import Worksheet

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\worksheet\worksheet.py", line 34, in <module>

    from openpyxl.cell import Cell

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\cell\__init__.py", line 4, in <module>

    from .cell import Cell, WriteOnlyCell

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\cell\cell.py", line 30, in <module>

    from openpyxl.utils.datetime  import (

  File
"C:\Users\marcus\AppData\Local\Programs\Python\Python35\lib\site-packages\op
enpyxl\utils\datetime.py", line 13, in <module>

    from jdcal import (

ImportError: No module named 'jdcal'

 

How do I get ?jdcal? ?
Tanks everybody for help, Marcus.























..

 

dear Experts,


could someone please tell me what exactly I have to type in my a) Python 35
? command line or 

b) desktopcomputer ( W10, 64bit)-command line in ordert to install openpyxl
which I downloaded in

C:\Users\marcus\Downloads on my computer. 
I have used all kinds of commands with ?pip install? at the end, all
unsuccessful.

 

Thanks for help.

Marcus.

 



---
Diese E-Mail wurde von Avast Antivirus-Software auf Viren gepr?ft.
https://www.avast.com/antivirus

From alan.gauld at yahoo.co.uk  Mon Jul 25 18:34:11 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 25 Jul 2016 23:34:11 +0100
Subject: [Tutor] installing openpyxl, problem still n o t solved
In-Reply-To: <b8a201d1e6a6$bbb647e0$3322d7a0$@bluewin.ch>
References: <b8a201d1e6a6$bbb647e0$3322d7a0$@bluewin.ch>
Message-ID: <nn6453$f56$1@ger.gmane.org>

On 25/07/16 19:59, marcus l?tolf wrote:

> The command  >pip install was rejected as SyntaxError : invalid syntax.
> Thanks for any kind of help, Marcus.

If you get a syntax error that suggests you are running it
from the Python >>> prompt.
That's wrong. You should run pip from the command prompt
of your OS.


-- 
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 Jul 25 23:57:37 2016
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 26 Jul 2016 13:57:37 +1000
Subject: [Tutor] installing openpyxl, problem still n o t solved
In-Reply-To: <b8a201d1e6a6$bbb647e0$3322d7a0$@bluewin.ch>
References: <b8a201d1e6a6$bbb647e0$3322d7a0$@bluewin.ch>
Message-ID: <20160726035736.GS27919@ando.pearwood.info>

Hello Marcus,

I'm afraid it is very difficult for me to understand your email. Your 
email contains weird control characters as shown here:

On Mon, Jul 25, 2016 at 08:59:50PM +0200, marcus l?tolf wrote:
> Dear Experts, 
> 
> I was too optimistic. Module ?jdcal? ist indeed installed.
> However, I get another trace back concerning ?et_xmlfile? even after I
> downloaded and saved it the same way as I did with ?jdcal?.

I think the reason is that your email program is setting the wrong 
encoding: your email claims to be Latin-1 but obviously isn't.

I think this may be because you are using Microsoft Word as the email 
editor, and inserting "smart quotes", probably ??. Smart quotes are not 
part of Latin-1, but Outlook is (wrongly!) setting a header saying that 
it is using Latin-1.

You should be able to fix this by:

- turning of Smart Quotes and using ordinary '' or "" quotes instead of 
  curly quotes ?? or ??

- teaching Outlook to use UTF-8 instead of the cp1252 encoding

- or at least have Outlook say it is using cp1252 instead of wrongly 
  claiming to be using Latin-1

That will help us be able to read your emails.

Another problem is that I actually don't understand what you are saying. 
First you say that you were too optimistic, at the beginning of the 
email. Then in the middle of the email you say you have solved your 
problem, and we should not bother. Then at the beginning you say that 
you need help. None of these parts are quoted:

   > Quoted text

   Not quoted text


so it all looks like part of the same email, which is confusing: have 
you solved the problem? Not solved it?

If we understood your questions better, perhaps we could answer them.


> Since I haven?t got any responses to my previous calls for help ? my problem
> might be too unimportant - I just try it another time:
> 
> Why got ?jdcal? accepted and ?et_xmlfile? not ?
> I must say I unzipped both files directly in
> C:\Users\marcus\AppData\local\Programs\Python\Python35\Lib\site-packages.

Are you talking about this?

https://pypi.python.org/pypi/et_xmlfile

You should unzip it into your home directory, and then run the setup.py 
file in the top directory. I think the command will be:

python setup.py install

as administrator or root superuser. On Linux/Mac you may be able to use:

sudo python setup.py install


> The command  >pip install was rejected as SyntaxError : invalid syntax.
> Thanks for any kind of help, Marcus.


You need to run pip from the operating system's shell, not from inside 
Python. Python's default prompt is ">>>". Most shells use "$" or "%" as 
the prompt.



-- 
Steve

From eryksun at gmail.com  Tue Jul 26 01:22:28 2016
From: eryksun at gmail.com (eryk sun)
Date: Tue, 26 Jul 2016 05:22:28 +0000
Subject: [Tutor] (no subject)
In-Reply-To: <CAMxbqSOgR_LhV8YbCnHXTCgBLgo6H77nnuYGg_bQK=k+K9SMtg@mail.gmail.com>
References: <CAMxbqSOA1PG8nRFpg5hDJiYEj0cYZXpD43+VaRJ39yX7Sk760g@mail.gmail.com>
 <20160725102828.GR27919@ando.pearwood.info>
 <CACL+1at5ppfPvP1BtTV+hd644XQMb+A2wM7uCrBkUggCbDGJmw@mail.gmail.com>
 <CAMxbqSM0BESX0JQHmS4pDqh1LfRse4_eyN42e2P3=HKQzz6+mg@mail.gmail.com>
 <CAMxbqSOgR_LhV8YbCnHXTCgBLgo6H77nnuYGg_bQK=k+K9SMtg@mail.gmail.com>
Message-ID: <CACL+1avHAxQgfS-WnnAT-XJ9Z+izNZdt3FjWzEJ7O8f9MeUBCw@mail.gmail.com>

On Tue, Jul 26, 2016 at 4:39 AM, DiliupG <diliupg at gmail.com> wrote:
> I am reading in a list of file names with the following code.
>
>     def get_filelist(self):
>         """"""
>         app = QtGui.QApplication(sys.argv)
>         a = QtGui.QFileDialog.getOpenFileNames()
>
>         filelist = []
>         if a:
>             for name in a:
>                 a = unicode(name)
>
>                 filelist.append(a)
>
>         return filelist
>
> mainprg.filelist = mainprg.get_filelist()
>
> filelist = mainprg.filelist
>
> for name in filelist:
>     print name             < ---- THIS IS WHERE THE PROBLEM IS

This is an output problem, which is unrelated to the IDLE input error
that you initially reported. But IDLE isn't (at least shouldn't be)
used for deployed applications. It's a development environment.

Generally if you're using Qt then you're not creating a console
application that prints to stdout, but instead the program outputs
text to a Qt widget such as a QTextEdit. That said, if you need to print
Unicode text to the Windows console, for whatever reason (maybe
debugging), then pip install and enable the win_unicode_console
module.

From diliupg at gmail.com  Tue Jul 26 00:41:00 2016
From: diliupg at gmail.com (DiliupG)
Date: Tue, 26 Jul 2016 10:11:00 +0530
Subject: [Tutor] (no subject)
In-Reply-To: <20160725102828.GR27919@ando.pearwood.info>
References: <CAMxbqSOA1PG8nRFpg5hDJiYEj0cYZXpD43+VaRJ39yX7Sk760g@mail.gmail.com>
 <20160725102828.GR27919@ando.pearwood.info>
Message-ID: <CAMxbqSNs-WZijxr0AkZZ-GfidjxKsQBbyXOwaRgKB8yYUrnE2Q@mail.gmail.com>

Thank you for the responses.
Some filenames I use are in Unicode in this script and there is no display
or typing problem in Windows (Vista, 7 and 10). Filenames and text in word
processing and text files are ALL displayed properly WITHOUT any errors by
the Windows system.

When I use a standard font in the local language there is no problem at all
but I need to retype ALL display text in all the Python programs which is a
tedious task.

Having read all answers is there no way this can be done without modifing
code on my computer? Thepurpose is to deliver a WIndows software for ALL
Windows users.

I am reading in a list of file names with the following code.

    def get_filelist(self):
        """"""
        app = QtGui.QApplication(sys.argv)
        a = QtGui.QFileDialog.getOpenFileNames()

        filelist = []
        if a:
            for name in a:
                a = unicode(name)

                filelist.append(a)

        return filelist

mainprg.filelist = mainprg.get_filelist()

filelist = mainprg.filelist

for name in filelist:
    print name             < ---- THIS IS WHERE THE PROBLEM IS

Thanks for feed back.

On Mon, Jul 25, 2016 at 3:58 PM, Steven D'Aprano <steve at pearwood.info>
wrote:

> On Fri, Jul 22, 2016 at 01:08:02PM +0530, DiliupG wrote:
> > I am using Python 2.7.12 on Windows 10
>
> Two errors:
>
> - first error is that Unicode strings in Python 2 need to be written as
> unicode objects, with a "u" prefix in the delimiter:
>
> # ASCII byte string:
> "Hello World"
>
> # Unicode string:
>
> u"??? ?"
>
> ASCII strings "..." cannot give you the right results except by
> accident. You must use unicode strings u"..."
>
> - Second possible problem: using Windows, which may not support the
> characters you are trying to use. I don't know -- try it and see. If it
> still doesn't work, then blame Windows. I know that Linux and Mac OS X
> both use UTF-8 for filenames, and so support all of Unicode. But
> Windows, I'm not sure. It might be localised to only use Latin-1
> (Western European) or similar.
>
>
> --
> Steve
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Kalasuri Diliup Gabadamudalige

http://www.diliupg.com
http://soft.diliupg.com/

**********************************************************************************************
This e-mail is confidential. It may also be legally privileged. If you are
not the intended recipient or have received it in error, please delete it
and all copies from your system and notify the sender immediately by return
e-mail. Any unauthorized reading, reproducing, printing or further
dissemination of this e-mail or its contents is strictly prohibited and may
be unlawful. Internet communications cannot be guaranteed to be timely,
secure, error or virus-free. The sender does not accept liability for any
errors or omissions.
**********************************************************************************************

From diliupg at gmail.com  Tue Jul 26 01:23:17 2016
From: diliupg at gmail.com (DiliupG)
Date: Tue, 26 Jul 2016 10:53:17 +0530
Subject: [Tutor] (no subject)
In-Reply-To: <CAMxbqSNs-WZijxr0AkZZ-GfidjxKsQBbyXOwaRgKB8yYUrnE2Q@mail.gmail.com>
References: <CAMxbqSOA1PG8nRFpg5hDJiYEj0cYZXpD43+VaRJ39yX7Sk760g@mail.gmail.com>
 <20160725102828.GR27919@ando.pearwood.info>
 <CAMxbqSNs-WZijxr0AkZZ-GfidjxKsQBbyXOwaRgKB8yYUrnE2Q@mail.gmail.com>
Message-ID: <CAMxbqSM1z_e87R26zZWamnU2pJiRTnnOh3NY0zmOg2AgWnjzdw@mail.gmail.com>

Thanks for the support.

Mu main problem was in the editor I was using which I did not mention.

I was using Wing IDE Pro instead of the Python IDE. BY the answer given by
erik sun I applied the same idea to th Wing IDE i/o to utf-8 and everything
worked. Thanks for your support and pardon me for not supplying all the
info.

On Tue, Jul 26, 2016 at 10:11 AM, DiliupG <diliupg at gmail.com> wrote:

> Thank you for the responses.
> Some filenames I use are in Unicode in this script and there is no display
> or typing problem in Windows (Vista, 7 and 10). Filenames and text in word
> processing and text files are ALL displayed properly WITHOUT any errors by
> the Windows system.
>
> When I use a standard font in the local language there is no problem at
> all but I need to retype ALL display text in all the Python programs which
> is a tedious task.
>
> Having read all answers is there no way this can be done without modifing
> code on my computer? Thepurpose is to deliver a WIndows software for ALL
> Windows users.
>
> I am reading in a list of file names with the following code.
>
>     def get_filelist(self):
>         """"""
>         app = QtGui.QApplication(sys.argv)
>         a = QtGui.QFileDialog.getOpenFileNames()
>
>         filelist = []
>         if a:
>             for name in a:
>                 a = unicode(name)
>
>                 filelist.append(a)
>
>         return filelist
>
> mainprg.filelist = mainprg.get_filelist()
>
> filelist = mainprg.filelist
>
> for name in filelist:
>     print name             < ---- THIS IS WHERE THE PROBLEM IS
>
> Thanks for feed back.
>
> On Mon, Jul 25, 2016 at 3:58 PM, Steven D'Aprano <steve at pearwood.info>
> wrote:
>
>> On Fri, Jul 22, 2016 at 01:08:02PM +0530, DiliupG wrote:
>> > I am using Python 2.7.12 on Windows 10
>>
>> Two errors:
>>
>> - first error is that Unicode strings in Python 2 need to be written as
>> unicode objects, with a "u" prefix in the delimiter:
>>
>> # ASCII byte string:
>> "Hello World"
>>
>> # Unicode string:
>>
>> u"??? ?"
>>
>> ASCII strings "..." cannot give you the right results except by
>> accident. You must use unicode strings u"..."
>>
>> - Second possible problem: using Windows, which may not support the
>> characters you are trying to use. I don't know -- try it and see. If it
>> still doesn't work, then blame Windows. I know that Linux and Mac OS X
>> both use UTF-8 for filenames, and so support all of Unicode. But
>> Windows, I'm not sure. It might be localised to only use Latin-1
>> (Western European) or similar.
>>
>>
>> --
>> Steve
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
>
>
>
> --
> Kalasuri Diliup Gabadamudalige
>
> http://www.diliupg.com
> http://soft.diliupg.com/
>
>
> **********************************************************************************************
> This e-mail is confidential. It may also be legally privileged. If you are
> not the intended recipient or have received it in error, please delete it
> and all copies from your system and notify the sender immediately by return
> e-mail. Any unauthorized reading, reproducing, printing or further
> dissemination of this e-mail or its contents is strictly prohibited and may
> be unlawful. Internet communications cannot be guaranteed to be timely,
> secure, error or virus-free. The sender does not accept liability for any
> errors or omissions.
>
> **********************************************************************************************
>
>


-- 
Kalasuri Diliup Gabadamudalige

http://www.diliupg.com
http://soft.diliupg.com/

**********************************************************************************************
This e-mail is confidential. It may also be legally privileged. If you are
not the intended recipient or have received it in error, please delete it
and all copies from your system and notify the sender immediately by return
e-mail. Any unauthorized reading, reproducing, printing or further
dissemination of this e-mail or its contents is strictly prohibited and may
be unlawful. Internet communications cannot be guaranteed to be timely,
secure, error or virus-free. The sender does not accept liability for any
errors or omissions.
**********************************************************************************************

From crusier at gmail.com  Tue Jul 26 12:02:26 2016
From: crusier at gmail.com (Crusier)
Date: Tue, 26 Jul 2016 09:02:26 -0700
Subject: [Tutor] Beautiful Soup
Message-ID: <CAC7HCj-BBK3QH1mo_mw-mhmLOC2+GjS6Y2xy7DfPtXEN-Y6K=w@mail.gmail.com>

I am using Python 3 on Windows 7.

However, I am unable to download some of the data listed in the web
site as follows:

453.IMC               98.28M           18.44M          4.32        5.33
1499.Optiver         70.91M            13.29M          3.12        5.34
7387.????       52.72M            9.84M            2.32        5.36

When I use Google Chrome and use 'View Page Source', the data does not
show up at all. However, when I use 'Inspect', I can able to read the
data.


<th>1453.IMC</th>
<td>98.28M</td>
<td>18.44M</td>
<td>4.32</td>
<td>5.33</td>

<th>1499.Optiver </th>
<td> 70.91M</td>
<td>13.29M </td>
<td>3.12</td>
<td>5.34</td>

Please kindly explain to me if the data is hide in CSS Style sheet or
is there any way to retrieve the data listed.

Thank you

Regards,
Crusier



from bs4 import BeautifulSoup
import urllib
import requests




stock_code = ('00939', '0001')

def web_scraper(stock_code):

    broker_url = 'http://data.tsci.com.cn/stock/'
    end_url = '/STK_Broker.htm'

    for code in stock_code:

        new_url  = broker_url + code + end_url
        response = requests.get(new_url)
        html = response.content
        soup = BeautifulSoup(html, "html.parser")
        Buylist = soup.find_all('div', id ="BuyingSeats")
        Selllist = soup.find_all('div', id ="SellSeats")


        print(Buylist)
        print(Selllist)



web_scraper(stock_code)

From jf_byrnes at comcast.net  Tue Jul 26 23:44:42 2016
From: jf_byrnes at comcast.net (Jim Byrnes)
Date: Tue, 26 Jul 2016 22:44:42 -0500
Subject: [Tutor] OOP help needed
Message-ID: <nn9ana$8f5$1@ger.gmane.org>

OOP has always driven me crazy.  I read the material and follow the 
examples until I feel I understand them, but when I try to implement it 
I end up with an error filled mess.

So I decided to give it another try.  When I got to the chapter on 
tkinter I decided to solve all the exercises using OOP even though the 
book solutions did not use OOP. The first one went fine:

#exer1.py

import tkinter

class Goodbye:
   def __init__(self):

     self.frame = tkinter.Frame(window)
     self.frame.pack()

     self.goodbye_button = tkinter.Button(self.frame, text='Goodbye',
       #command=quit)
       command=lambda: quit() )
     self.goodbye_button.pack()

   def quit():
     self.window.destroy()

if __name__=='__main__':
   window = tkinter.Tk()
   myapp = Goodbye()
   window.mainloop()

The second one was more trouble but I finally got it to work.

# exer2.py

import tkinter

class Count:

   def __init__(self):
     ''' Increment a button labeled 0, by 1 with each click '''
     self.frame = tkinter.Frame(window)
     self.frame.pack()
     self.label = tkinter.StringVar()
     self.label.set('0')
     self.count_btn = tkinter.Button(self.frame, textvariable=self.label,
       command=lambda: self.increment(self.label ))
     self.count_btn.pack()

   def increment(self, label):
     count = int(self.label.get())
     self.label.set(str(count + 1))

if __name__ == '__main__':
   window = tkinter.Tk()
   myapp = Count()
   window.mainloop()

I am having trouble understanding the difference between the two lines 
that contain lambda: command= .In exer1.py I can do command=lambda: 
quit().  In exer2.py if I do command=lambda: increment(self.label) I get 
this error:

Exception in Tkinter callback
Traceback (most recent call last):
   File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__
     return self.func(*args)
   File "exer2.py", line 14, in <lambda>
     command=lambda: increment(self.label ))
NameError: name 'increment' is not defined

Why do I get this error?  The situations look the same to me but they 
must be different somehow and I just don't see the difference.

Thanks,  Jim


From ben+python at benfinney.id.au  Wed Jul 27 00:38:16 2016
From: ben+python at benfinney.id.au (Ben Finney)
Date: Wed, 27 Jul 2016 14:38:16 +1000
Subject: [Tutor] OOP help needed
References: <nn9ana$8f5$1@ger.gmane.org>
Message-ID: <85lh0npufb.fsf@benfinney.id.au>

Jim Byrnes <jf_byrnes at comcast.net> writes:

> So I decided to give it another try. When I got to the chapter on
> tkinter I decided to solve all the exercises using OOP even though the
> book solutions did not use OOP.

Hmm, that sounds ill advised.

OOP is one tool among many; trying to apply it where it's a poor fit
will result in bad design and probably avoidable errors.

When learning to use a hacksaw, trying to solve everything using that
tool merely to learn it, would be a poor choice.

> # exer2.py
>
> import tkinter
>
> class Count:
>
>   def __init__(self):
>     ''' Increment a button labeled 0, by 1 with each click '''
>     [?]
>     self.count_btn = tkinter.Button(self.frame, textvariable=self.label,
>       command=lambda: self.increment(self.label ))

Here you address the ?self.increment? name, which should work.

>   def increment(self, label):
>     count = int(self.label.get())
>     self.label.set(str(count + 1))

This is the method that an instance will address via ?self.increment?.

> In exer2.py if I do command=lambda: increment(self.label)

The lambda expression creates a function, and that function then behaves
like any other function. Within that function, the name ?increment? is
not defined; within the scope where the function was defined, the name
?increment? is also not defined. Within the global scope the name
?increment? is not defined.

So yes, you'll get NameError from that code.

> Why do I get this error?  The situations look the same to me

The difference is that when you invoke ?self.instance?, the lookup of
?self? succeeds because it's defined within the function (you defined it
in the parameters of ?__init__?, so ?__init__? knows that name when it
is running).

You never defined the name ?increment? within the function, nor within
the global scope. And you shouldn't because there's no need: you access
the instance's own method by accessing the instance first: you ask for
?the ?instance? attribute from the ?self? object?: ?self.instance?.

-- 
 \             ?I believe our future depends powerfully on how well we |
  `\     understand this cosmos, in which we float like a mote of dust |
_o__)                 in the morning sky.? ?Carl Sagan, _Cosmos_, 1980 |
Ben Finney


From __peter__ at web.de  Wed Jul 27 04:12:22 2016
From: __peter__ at web.de (Peter Otten)
Date: Wed, 27 Jul 2016 10:12:22 +0200
Subject: [Tutor] OOP help needed
References: <nn9ana$8f5$1@ger.gmane.org>
Message-ID: <nn9qd8$bl4$1@ger.gmane.org>

Jim Byrnes wrote:

> OOP has always driven me crazy.  I read the material and follow the
> examples until I feel I understand them, but when I try to implement it
> I end up with an error filled mess.
> 
> So I decided to give it another try.  When I got to the chapter on
> tkinter I decided to solve all the exercises using OOP even though the
> book solutions did not use OOP. The first one went fine:

No, it didn't. The Goodbye.quit() method is missing the self argument and 
uses the inexistent self.window attribute.
You don't see these bugs when you run the script because there is a global 
quit()... let's say function... that is called instead of the method. 

You can put a print() into Goodbye.quit() to verify the above.
 
> #exer1.py
> 
> import tkinter
> 
> class Goodbye:
>    def __init__(self):
> 
>      self.frame = tkinter.Frame(window)
>      self.frame.pack()
> 
>      self.goodbye_button = tkinter.Button(self.frame, text='Goodbye',
>        #command=quit)
>        command=lambda: quit() )

The lambda is superfluous -- command=quit will already invoke the global 
quit(). But what you actually intended is achieved with command=self.quit.
self.quit is called "bound method".

>      self.goodbye_button.pack()
> 
>    def quit():
       print("you'll never see this")
>      self.window.destroy()
> 
> if __name__=='__main__':
>    window = tkinter.Tk()
>    myapp = Goodbye()
>    window.mainloop()



From programbellworking at gmail.com  Tue Jul 26 21:39:58 2016
From: programbellworking at gmail.com (kanishk srivastava)
Date: Tue, 26 Jul 2016 21:39:58 -0400
Subject: [Tutor] Python Programming for the absolute beginner 3e Ch3
 Challenge 1
Message-ID: <CALPdCSJ3jYnCbfZrV1V8p1LFfDGkPOcXD04+L1ppnOQVidxvRg@mail.gmail.com>

Hello,

I am working through Michael Dawson's book - Python Programming for
absolute beginners 3e.

Completed chapter 3, but unable to solve challenge 1.

Below code is what I have written but unsure on how to have the program
generate the message at random. Any help will be appreciated.

# Fortune Cookie
# Demonstrates random message generation


print("\t\tFortune Cookie")
print("\t\tWelcome user!")

# fortune messages
message1 = "the earth is a school learn in it."
message2 = "be calm when confronting an emergency crisis."
message3 = "you never hesitate to tackle the most difficult problems."
message4 = "hard words break no bones, fine words butter no parsnips."
message5 = "Make all you can, save all you can, give all you can."

import random


print("Your today's fortune  ")

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


Thanks
Kyo

From alan.gauld at yahoo.co.uk  Wed Jul 27 05:04:43 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 27 Jul 2016 10:04:43 +0100
Subject: [Tutor] OOP help needed
In-Reply-To: <nn9ana$8f5$1@ger.gmane.org>
References: <nn9ana$8f5$1@ger.gmane.org>
Message-ID: <nn9tfb$si0$1@ger.gmane.org>

On 27/07/16 04:44, Jim Byrnes wrote:
> OOP has always driven me crazy.  I read the material and follow the 
> examples until I feel I understand them, but when I try to implement it 
> I end up with an error filled mess.

That suggests that its not the OOP concept thats confusing
you but the language syntax. How to turn the concept into code?

> So I decided to give it another try.  When I got to the chapter on 
> tkinter I decided to solve all the exercises using OOP even though the 
> book solutions did not use OOP. The first one went fine:

Actually not as fine as you thought. In effect you got lucky by
making a mistake that still resulted in your code doing
approximately what you expected. But it didn't really do
what you thought it did.

> import tkinter
> 
> class Goodbye:
>    def __init__(self):
> 
>      self.frame = tkinter.Frame(window)
>      self.frame.pack()

You are using a global variable as your parent here. It would be
better to pass that in as an argument. Or better still to make
the call to Tk() inside the __init__ method. That's not really
an OOP thing though just a general good practice issue.
It's best to avoid relying on global variables in your
functions.

>      self.goodbye_button = tkinter.Button(self.frame, text='Goodbye',
>        #command=quit)
>        command=lambda: quit() )
>      self.goodbye_button.pack()

Here you assign quit to the button's command. That's OK because
there is a top level built-in function called quit which exits
the interpreter. It's a bit of a brutal way to exit your GUI
but it works.

But I guess you really wanted to call your quit method. Remember
to access anything in your class you have to use the self
prefix, so you should have said:

command=self.quit

or

command=lambda: self.quit()

Lambda doesn't really help in this case but it doesn't do
any harm either.

>    def quit():
>      self.window.destroy()

When you define a method inside a class you need to
explicitly include the self parameter. So this should be:

    def quit(self):
      self.window.destroy()

But there's a snag, you don't store the window inside the
class. So self.window will cause an error. You either need
a line like

self.window = window

in your__init__ method

or use the global window variable like

    def quit():
      window.destroy()

My preference would be to create a self.window instance variable,
inside init()then access the self.window in quit(). You would also
call mainloop() using self.window in your init()

> if __name__=='__main__':
>    window = tkinter.Tk()
>    myapp = Goodbye()
>    window.mainloop()

So if you took my advice this section of code would look like:

if __name__=='__main__':
    Goodbye()


and init() would look like:

def __init__(self):
     self.window = tkinter.Tk()
     self.frame = tkinter.Frame(self.window)
     self.frame.pack()

     self.goodbye_button = tkinter.Button(self.frame, text='Goodbye',
                                          command=self.quit)
     self.goodbye_button.pack()

     self.window.mainloop()

If you read through that and understand it, it should give
you the clues as to why the second one behaved as it did.


-- 
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 yahoo.co.uk  Wed Jul 27 05:13:50 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 27 Jul 2016 10:13:50 +0100
Subject: [Tutor] Python Programming for the absolute beginner 3e Ch3
 Challenge 1
In-Reply-To: <CALPdCSJ3jYnCbfZrV1V8p1LFfDGkPOcXD04+L1ppnOQVidxvRg@mail.gmail.com>
References: <CALPdCSJ3jYnCbfZrV1V8p1LFfDGkPOcXD04+L1ppnOQVidxvRg@mail.gmail.com>
Message-ID: <nn9u0e$5d7$1@ger.gmane.org>

On 27/07/16 02:39, kanishk srivastava wrote:
> Hello,
> 
> I am working through Michael Dawson's book - Python Programming for
> absolute beginners 3e.
> 
> Completed chapter 3, but unable to solve challenge 1.

I don't know the book so don't know how much you
know yet. So thee are some suggestions below that
might not make sense to you because you haven't
covered the material. Apologies in advance!

> print("\t\tFortune Cookie")
> print("\t\tWelcome user!")
> 
> # fortune messages
> message1 = "the earth is a school learn in it."
> message2 = "be calm when confronting an emergency crisis."
> message3 = "you never hesitate to tackle the most difficult problems."
> message4 = "hard words break no bones, fine words butter no parsnips."
> message5 = "Make all you can, save all you can, give all you can."

Have you covered lists? Rather than a set of numbered messages you could
put them in a list and access each message by index:

messages = ["the earth is a school learn in it.",
            "be calm when confronting an emergency crisis.",
            "you never hesitate to tackle the most difficult problems.",
            "hard words break no bones, fine words butter no parsnips.",
            "Make all you can, save all you can, give all you can."
           ]

And access them with

messages[0], messages[1], ... messages[4]

Although in this case you don't even need to do that,
read on...

> import random

I don't know how many of the random module functions you cover
but there are a lot of them. One of them, random.choice(aList),
selects a random item from a list. So now that you have a list
of messages it becomes trivial to select a random message from
the list:

> print("Your today's fortune  ")

use print(random.choice(messages)) here

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 jf_byrnes at comcast.net  Wed Jul 27 14:19:47 2016
From: jf_byrnes at comcast.net (Jim Byrnes)
Date: Wed, 27 Jul 2016 13:19:47 -0500
Subject: [Tutor] OOP help needed
In-Reply-To: <85lh0npufb.fsf@benfinney.id.au>
References: <nn9ana$8f5$1@ger.gmane.org> <85lh0npufb.fsf@benfinney.id.au>
Message-ID: <nnau04$l26$1@ger.gmane.org>

On 07/26/2016 11:38 PM, Ben Finney wrote:
> Jim Byrnes <jf_byrnes at comcast.net> writes:
>
>> So I decided to give it another try. When I got to the chapter on
>> tkinter I decided to solve all the exercises using OOP even though the
>> book solutions did not use OOP.
>
> Hmm, that sounds ill advised.
>
> OOP is one tool among many; trying to apply it where it's a poor fit
> will result in bad design and probably avoidable errors.
>
> When learning to use a hacksaw, trying to solve everything using that
> tool merely to learn it, would be a poor choice.

With anything more complex I would agree.  I am simply trying to get 
myself thinking about how OOP works and there aren't enough exercises in 
the book calling for OOP to give me much repetition.

>> # exer2.py
>>
>> import tkinter
>>
>> class Count:
>>
>>   def __init__(self):
>>     ''' Increment a button labeled 0, by 1 with each click '''
>>     [?]
>>     self.count_btn = tkinter.Button(self.frame, textvariable=self.label,
>>       command=lambda: self.increment(self.label ))
>
> Here you address the ?self.increment? name, which should work.
>
>>   def increment(self, label):
>>     count = int(self.label.get())
>>     self.label.set(str(count + 1))
>
> This is the method that an instance will address via ?self.increment?.
>
>> In exer2.py if I do command=lambda: increment(self.label)
>
> The lambda expression creates a function, and that function then behaves
> like any other function. Within that function, the name ?increment? is
> not defined; within the scope where the function was defined, the name
> ?increment? is also not defined. Within the global scope the name
> ?increment? is not defined.
>
> So yes, you'll get NameError from that code.
>
>> Why do I get this error?  The situations look the same to me
>
> The difference is that when you invoke ?self.instance?, the lookup of
> ?self? succeeds because it's defined within the function (you defined it
> in the parameters of ?__init__?, so ?__init__? knows that name when it
> is running).
>
> You never defined the name ?increment? within the function, nor within
> the global scope. And you shouldn't because there's no need: you access
> the instance's own method by accessing the instance first: you ask for
> ?the ?instance? attribute from the ?self? object?: ?self.instance?.
>

OK thank you.

Regards,  Jim



From jf_byrnes at comcast.net  Wed Jul 27 14:25:18 2016
From: jf_byrnes at comcast.net (Jim Byrnes)
Date: Wed, 27 Jul 2016 13:25:18 -0500
Subject: [Tutor] OOP help needed
In-Reply-To: <nn9qd8$bl4$1@ger.gmane.org>
References: <nn9ana$8f5$1@ger.gmane.org> <nn9qd8$bl4$1@ger.gmane.org>
Message-ID: <nnauaf$vo$1@ger.gmane.org>

On 07/27/2016 03:12 AM, Peter Otten wrote:
> Jim Byrnes wrote:
>
>> OOP has always driven me crazy.  I read the material and follow the
>> examples until I feel I understand them, but when I try to implement it
>> I end up with an error filled mess.
>>
>> So I decided to give it another try.  When I got to the chapter on
>> tkinter I decided to solve all the exercises using OOP even though the
>> book solutions did not use OOP. The first one went fine:
>
> No, it didn't. The Goodbye.quit() method is missing the self argument and
> uses the inexistent self.window attribute.
> You don't see these bugs when you run the script because there is a global
> quit()... let's say function... that is called instead of the method.
>
> You can put a print() into Goodbye.quit() to verify the above.

OK right.  I ended up concentrating on exer2 when the problem was in 
exer1.  I should have known better than using quit() as a name.

>> #exer1.py
>>
>> import tkinter
>>
>> class Goodbye:
>>    def __init__(self):
>>
>>      self.frame = tkinter.Frame(window)
>>      self.frame.pack()
>>
>>      self.goodbye_button = tkinter.Button(self.frame, text='Goodbye',
>>        #command=quit)
>>        command=lambda: quit() )
>
> The lambda is superfluous -- command=quit will already invoke the global
> quit(). But what you actually intended is achieved with command=self.quit.
> self.quit is called "bound method".

Ok, thanks.

>>      self.goodbye_button.pack()
>>
>>    def quit():
>        print("you'll never see this")
>>      self.window.destroy()
>>
>> if __name__=='__main__':
>>    window = tkinter.Tk()
>>    myapp = Goodbye()
>>    window.mainloop()
>

Regards,  Jim



From jf_byrnes at comcast.net  Wed Jul 27 14:38:59 2016
From: jf_byrnes at comcast.net (Jim Byrnes)
Date: Wed, 27 Jul 2016 13:38:59 -0500
Subject: [Tutor] OOP help needed
In-Reply-To: <nn9tfb$si0$1@ger.gmane.org>
References: <nn9ana$8f5$1@ger.gmane.org> <nn9tfb$si0$1@ger.gmane.org>
Message-ID: <nnav43$pub$1@ger.gmane.org>

On 07/27/2016 04:04 AM, Alan Gauld via Tutor wrote:
> On 27/07/16 04:44, Jim Byrnes wrote:
>> OOP has always driven me crazy.  I read the material and follow the
>> examples until I feel I understand them, but when I try to implement it
>> I end up with an error filled mess.
>
> That suggests that its not the OOP concept thats confusing
> you but the language syntax. How to turn the concept into code?

That's exactly my problem, which is why I am solving problems with OOP 
when it's not necessary.  I wanted the practice.

>> So I decided to give it another try.  When I got to the chapter on
>> tkinter I decided to solve all the exercises using OOP even though the
>> book solutions did not use OOP. The first one went fine:
>
> Actually not as fine as you thought. In effect you got lucky by
> making a mistake that still resulted in your code doing
> approximately what you expected. But it didn't really do
> what you thought it did.
>
>> import tkinter
>>
>> class Goodbye:
>>    def __init__(self):
>>
>>      self.frame = tkinter.Frame(window)
>>      self.frame.pack()
>
> You are using a global variable as your parent here. It would be
> better to pass that in as an argument. Or better still to make
> the call to Tk() inside the __init__ method. That's not really
> an OOP thing though just a general good practice issue.
> It's best to avoid relying on global variables in your
> functions.

Ok thanks.  When I wrote that I was mimicking the style used in the 
book. I have read about avoiding globals if possible, but didn't think 
it through.

>>      self.goodbye_button = tkinter.Button(self.frame, text='Goodbye',
>>        #command=quit)
>>        command=lambda: quit() )
>>      self.goodbye_button.pack()
>
> Here you assign quit to the button's command. That's OK because
> there is a top level built-in function called quit which exits
> the interpreter. It's a bit of a brutal way to exit your GUI
> but it works.
>
> But I guess you really wanted to call your quit method. Remember
> to access anything in your class you have to use the self
> prefix, so you should have said:
>
> command=self.quit
>
> or
>
> command=lambda: self.quit()
>
> Lambda doesn't really help in this case but it doesn't do
> any harm either.
>
>>    def quit():
>>      self.window.destroy()
>
> When you define a method inside a class you need to
> explicitly include the self parameter. So this should be:
>
>     def quit(self):
>       self.window.destroy()
>
> But there's a snag, you don't store the window inside the
> class. So self.window will cause an error. You either need
> a line like
>
> self.window = window
>
> in your__init__ method
>
> or use the global window variable like
>
>     def quit():
>       window.destroy()
>
> My preference would be to create a self.window instance variable,
> inside init()then access the self.window in quit(). You would also
> call mainloop() using self.window in your init()
>
>> if __name__=='__main__':
>>    window = tkinter.Tk()
>>    myapp = Goodbye()
>>    window.mainloop()
>
> So if you took my advice this section of code would look like:
>
> if __name__=='__main__':
>     Goodbye()
>
>
> and init() would look like:
>
> def __init__(self):
>      self.window = tkinter.Tk()
>      self.frame = tkinter.Frame(self.window)
>      self.frame.pack()
>
>      self.goodbye_button = tkinter.Button(self.frame, text='Goodbye',
>                                           command=self.quit)
>      self.goodbye_button.pack()
>
>      self.window.mainloop()
>
> If you read through that and understand it, it should give
> you the clues as to why the second one behaved as it did.
>
>

Ok thanks.  I don't want to belabor the point but I basically had it 
that way because I didn't know any better. Now I know of a 
different/better way to do it.

Regards,  Jim


From dyoo at hashcollision.org  Thu Jul 28 00:30:18 2016
From: dyoo at hashcollision.org (Danny Yoo)
Date: Wed, 27 Jul 2016 21:30:18 -0700
Subject: [Tutor] python programmin problem
In-Reply-To: <20160724.163040.26810.0@webmail13.dca.untd.com>
References: <20160724.163040.26810.0@webmail13.dca.untd.com>
Message-ID: <CAGZAPF65_9c5KihtY7kZ6H3pX4xjC3WPQ5+yCZABpUpFYAZ_tQ@mail.gmail.com>

On Sun, Jul 24, 2016 at 4:30 PM, monikajg at netzero.net
<monikajg at netzero.net> wrote:
> Thank you all for your answers. I do not have a teacher or any body else who could guide me. I have taken all python classes offered in my area and many on line.
> The question is one of questions asked by interviews for a qa position that also does some automation with python.


If you're training for problems like this, then look for something
less focused on a specific programming language.  As we said earlier,
solving these kinds of problems isn't really a matter of Python
programming at this level: you want to look specifically for material
about algorithms.


For this kind of thing, definitely look into something like the
"Develop a strong understanding of algorithms and data structures"
recommendations at:

    https://www.google.com/about/careers/students/guide-to-technical-development.html


I've also heard very good things about Skiena's "The Algorithm Design Manual":

    http://www.algorist.com/

The author has a bunch of videos and lecture material online that
might help you:

    http://www3.cs.stonybrook.edu/~algorith/video-lectures/

In particular, see Lectures 18 and 19.

*Especially Lecture 19*.


You will see a problem being explained that you should be *very*
interested in.  :)  Here's a link just to give you a taste:

    https://youtu.be/0yjebrZXJ9A?t=3m


I hope that this helps point you in the right direction.  Good luck!

From dyoo at hashcollision.org  Thu Jul 28 00:42:25 2016
From: dyoo at hashcollision.org (Danny Yoo)
Date: Wed, 27 Jul 2016 21:42:25 -0700
Subject: [Tutor] python programmin problem
In-Reply-To: <CAGZAPF65_9c5KihtY7kZ6H3pX4xjC3WPQ5+yCZABpUpFYAZ_tQ@mail.gmail.com>
References: <20160724.163040.26810.0@webmail13.dca.untd.com>
 <CAGZAPF65_9c5KihtY7kZ6H3pX4xjC3WPQ5+yCZABpUpFYAZ_tQ@mail.gmail.com>
Message-ID: <CAGZAPF79XaqQo=t_Nk5Q9=TPWQmfzDyFJgEvVdPQJNiYpNybWg@mail.gmail.com>

> You will see a problem being explained that you should be *very*
> interested in.  :)  Here's a link just to give you a taste:
>
>     https://youtu.be/0yjebrZXJ9A?t=3m
>
>
> I hope that this helps point you in the right direction.  Good luck!


He has some more recent videos from 2012:

     https://youtu.be/Qc2ieXRgR0k?list=PLOtl7M3yp-DV69F32zdK7YJcNXpTunF2b

where he again goes over the familiar example in:

    https://youtu.be/o0V9eYF4UI8?t=34m52s

From monikajg at netzero.net  Thu Jul 28 00:53:01 2016
From: monikajg at netzero.net (monikajg at netzero.net)
Date: Thu, 28 Jul 2016 04:53:01 GMT
Subject: [Tutor] python programmin problem
Message-ID: <20160727.215301.641.0@webmail01.dca.untd.com>

Thank you very much. I will look into your suggestions. I have been looking for tutorials but could not find anything at my level of understanding. You said to not focus on python but I had a python teacher (a famous python book writer and a friend of  Guido) was stressing on doing things in "pythonic" way.
Thank you for the links and I will check/read each one of them.
Monika

---------- Original Message ----------
From: Danny Yoo <dyoo at hashcollision.org>
To: "monikajg at netzero.net" <monikajg at netzero.net>
Cc: Alan Gauld <alan.gauld at yahoo.co.uk>, Python Tutor Mailing List <tutor at python.org>
Subject: Re: [Tutor] python programmin problem
Date: Wed, 27 Jul 2016 21:42:25 -0700

> You will see a problem being explained that you should be *very*
> interested in.  :)  Here's a link just to give you a taste:
>
>     https://youtu.be/0yjebrZXJ9A?t=3m
>
>
> I hope that this helps point you in the right direction.  Good luck!


He has some more recent videos from 2012:

     https://youtu.be/Qc2ieXRgR0k?list=PLOtl7M3yp-DV69F32zdK7YJcNXpTunF2b

where he again goes over the familiar example in:

    https://youtu.be/o0V9eYF4UI8?t=34m52s
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


____________________________________________________________
Affordable Wireless Plans
Set up is easy. Get online in minutes.
Starting at only $9.95 per month! 
www.netzero.net?refcd=nzmem0216

From alan.gauld at yahoo.co.uk  Thu Jul 28 05:01:49 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 28 Jul 2016 10:01:49 +0100
Subject: [Tutor] python programmin problem
In-Reply-To: <20160727.215301.641.0@webmail01.dca.untd.com>
References: <20160727.215301.641.0@webmail01.dca.untd.com>
Message-ID: <nnchlu$jqi$1@ger.gmane.org>

On 28/07/16 05:53, monikajg at netzero.net wrote:
> I have been looking for tutorials but could not find anything 
> at my level of understanding.  You said to not focus on python
> but I had a python teacher ... stressing on doing things in
> "pythonic" way.

When learning to program there are two aspects to be considered.

There are the generic "software engineering" skills that
apply to any language. These are concerned with things
like data structures, algorithms, architecture and so on.

Then there are the programming languages which each have their
own ways of doing things. They all do the same basic operations
(sequences, loops, branches, modules) but they all do it
slightly differently. Then on top of the basic syntax they
also have their own idioms - the standard practices developed
by that language community. The language style if you like.

The software 3engineering bit only needs to be learned once.
Whereas the language stuff is re-learned for each language.
But you need the software engineering background before
you start worrying about the details of a particular
language and that's the bit that you seem to be weaker
on just now.

So Danny's advice to focus on algorithm development is part
of the generic skills you need to be a good programmer in
any language. Your teacher's advice is about learning the
specifics of Python. You need to do both eventually but
you should probably focus initially on the more generic
aspects. Once you know how to solve the problems then you
can worry about expressing that solution in any particular
language.

This list can help you with both aspects. Just ask when
you have a question.

-- 
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 darahpereira at yahoo.com  Fri Jul 29 00:24:02 2016
From: darahpereira at yahoo.com (Darah)
Date: Thu, 28 Jul 2016 21:24:02 -0700
Subject: [Tutor] IDLE Subprocess Startup Error
Message-ID: <FA1420A0-3EEB-47FE-A4B3-2F928D43F6B0@yahoo.com>

Hello, 

I?ve been using Python?s IDLE for a couple of weeks now and it has been working fine but a few days ago I started getting this error message "IDLE's subprocess didn't make connection.  Either IDLE can't start a subprocess or personal firewall software is blocking the connection.? 

I tried uninstalling it, restarting my computer, found a couple of people that said deleting the created .py files worked for them but it did not for me. 

I am not sure what else to do. Do you have any suggestions?

I am using OS X El Capitan 10.11.5 on mac 




Regards, 

Darah Pereira

From alan.gauld at yahoo.co.uk  Fri Jul 29 03:18:11 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 29 Jul 2016 08:18:11 +0100
Subject: [Tutor] IDLE Subprocess Startup Error
In-Reply-To: <FA1420A0-3EEB-47FE-A4B3-2F928D43F6B0@yahoo.com>
References: <FA1420A0-3EEB-47FE-A4B3-2F928D43F6B0@yahoo.com>
Message-ID: <nnevvj$m34$1@ger.gmane.org>

On 29/07/16 05:24, Darah via Tutor wrote:

> I?ve been using Python?s IDLE for a couple of weeks now and 
> it has been working fine but a few days ago I started getting
> this error message
> "IDLE's subprocess didn't make connection.
> Either IDLE can't start a subprocess or personal firewall
> software is blocking the connection.?


What version of IDLE are you using? That used to be a common
error message but since Python v2.6 I've never had it. If its an older
version than that you could try upgrading your Python version.

Other than that there is a dedicated IDLE mailing list which
is quite responsive and should be able to help if you don't
get an answer here. The gmane link is:

gmane.comp.python.idle


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 crusier at gmail.com  Fri Jul 29 03:28:25 2016
From: crusier at gmail.com (Crusier)
Date: Fri, 29 Jul 2016 15:28:25 +0800
Subject: [Tutor] Unable to download <th>, <td> using Beautifulsoup
Message-ID: <CAC7HCj9RqfNiH88d8hbaVzK9FziTmd41=BrADybc+h-y-TxESA@mail.gmail.com>

I am using Python 3 on Windows 7.

However, I am unable to download some of the data listed in the web
site as follows:

http://data.tsci.com.cn/stock/00939/STK_Broker.htm

453.IMC 98.28M 18.44M 4.32 5.33 1499.Optiver 70.91M 13.29M 3.12 5.34
7387.???? 52.72M 9.84M 2.32 5.36

When I use Google Chrome and use 'View Page Source', the data does not
show up at all. However, when I use 'Inspect', I can able to read the
data.

'<th>1453.IMC</th>'
'<td>98.28M</td>'
'<td>18.44M</td>'
'<td>4.32</td>'
'<td>5.33</td>'

'<th>1499.Optiver </th>'
'<td> 70.91M</td>'
'<td>13.29M </td>'
'<td>3.12</td>'
'<td>5.34</td>'

Please kindly explain to me if the data is hide in CSS Style sheet or
is there any way to retrieve the data listed.

Thank you

Regards, Crusier

from bs4 import BeautifulSoup
import urllib
import requests




stock_code = ('00939', '0001')

def web_scraper(stock_code):

    broker_url = 'http://data.tsci.com.cn/stock/'
    end_url = '/STK_Broker.htm'

    for code in stock_code:

        new_url  = broker_url + code + end_url
        response = requests.get(new_url)
        html = response.content
        soup = BeautifulSoup(html, "html.parser")
        Buylist = soup.find_all('div', id ="BuyingSeats")
        Selllist = soup.find_all('div', id ="SellSeats")


        print(Buylist)
        print(Selllist)



web_scraper(stock_code)

From alan.gauld at yahoo.co.uk  Fri Jul 29 11:46:19 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 29 Jul 2016 16:46:19 +0100
Subject: [Tutor] Unable to download <th>, <td> using Beautifulsoup
In-Reply-To: <CAC7HCj9RqfNiH88d8hbaVzK9FziTmd41=BrADybc+h-y-TxESA@mail.gmail.com>
References: <CAC7HCj9RqfNiH88d8hbaVzK9FziTmd41=BrADybc+h-y-TxESA@mail.gmail.com>
Message-ID: <nnftoc$at$1@ger.gmane.org>

On 29/07/16 08:28, Crusier wrote:

> When I use Google Chrome and use 'View Page Source', the data does not
> show up at all. However, when I use 'Inspect', I can able to read the
> data.
> 
> '<th>1453.IMC</th>'
> '<td>98.28M</td>'

> '<td>3.12</td>'
> '<td>5.34</td>'
> 
> Please kindly explain to me if the data is hide in CSS Style sheet or
> is there any way to retrieve the data listed.

I don;t know the answer but I would suggest that if you print
out (or send to a file)  the entire html source returned by
the server you can see what is actually happening and from
that perhaps figure out what to do with BS to extract what
you need.


> from bs4 import BeautifulSoup
> import urllib
> import requests
> 
> stock_code = ('00939', '0001')
> 
> def web_scraper(stock_code):
> 
>     broker_url = 'http://data.tsci.com.cn/stock/'
>     end_url = '/STK_Broker.htm'
> 
>     for code in stock_code:
>         new_url  = broker_url + code + end_url
>         response = requests.get(new_url)
>         html = response.content

Try sending html to a file and examining it in a
text editor...


-- 
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 Jul 29 17:23:54 2016
From: wprins at gmail.com (Walter Prins)
Date: Fri, 29 Jul 2016 22:23:54 +0100
Subject: [Tutor] Unable to download <th>, <td> using Beautifulsoup
In-Reply-To: <CAC7HCj9RqfNiH88d8hbaVzK9FziTmd41=BrADybc+h-y-TxESA@mail.gmail.com>
References: <CAC7HCj9RqfNiH88d8hbaVzK9FziTmd41=BrADybc+h-y-TxESA@mail.gmail.com>
Message-ID: <CANLXbfC+_2ixbkoCKEtN171vHeCBJFfdsCdEZXe93JiFeEAzZQ@mail.gmail.com>

Hi

On 29 July 2016 at 08:28, Crusier <crusier at gmail.com> wrote:

> I am using Python 3 on Windows 7.
>


> When I use Google Chrome and use 'View Page Source', the data does not
> show up at all. However, when I use 'Inspect', I can able to read the
> data.
>
> Please kindly explain to me if the data is hide in CSS Style sheet or
> is there any way to retrieve the data listed.
>

Using inspect is not the same as view source. The inspect tools will give
you the DOM tree as it currently is in the browser. That tree may have been
modified by any number of things (e.g. likely Javascript) since the initial
page source was loaded.  It is likely that the data you're trying to get
at, is fetched dynamically after the initial page source is fetched, which
is why you don't see it when using "view source."

As an experiment you can temporarily disable your browser's Javascript
engine and reload the webpage.  You should then find that you can't see the
data you're after at all, even with inspect, if this is what's occurring.
 (To do this for Chrome, see here:
https://productforums.google.com/forum/#!topic/chrome/BYOQskiuGU0)

So, if this is what's going on then this presents you with a bit of a
problem. Obviously the Python "requests" module is not a full browser and
does not include a Javascript runtime, so it cannot by itself yield the
same result as a real browser, if the page content is in fact the result of
dynamic population by Javascript after loading the initial HTML page
source.

In order to get around this you would therefore need to fundamentally have
a browser of some kind that you can control, and that includes a Javascript
runtime that can effectively process and construct the DOM (and render the
page image if you so desire) before you retrieve the data you're after.

It should be possible to do this, there are projects and questions on the
internet about this.  Firstly there's a project named "Selenium" that
provides a way of automating various browsers, and has Python bindings (I
used this some years ago).  So you could conceivably use
Python+Selenium+(Chrome or Firefox say) for example to fetch the page and
then get the data out.  This has the disadvantage that there's going to be
a real browser and browser window floating around.

A slightly better alternative would be to use a "headless" (displayless)
browser, such as PhantomJS.  It is basically the browser engine with lots
of ways to control and automate it.  It does not (to my knowledge) include
Python bindings directly, but Selenium includes a PhantomJS driver (I
think.)  There's lighter weight options like "jsdom" and "slimerjs", but I
have no idea whether these would suffice or not or whether they would have
Python wrappers or not.

Perhaps the best option might be Ghost.py, which sounds like it might be
exactly what you need, but I have no experience with it.

So, I'm afraid to achieve what you want will require a rather more
complicated solution than what you've currently got.  :(

Nevertheless, here's some links for you:

Ghost.py:
http://jeanphix.me/Ghost.py/
http://ghost-py.readthedocs.io/en/latest/#

PhantomJS:
http://phantomjs.org/

PhantomJS & Python:
http://stackoverflow.com/questions/13287490/is-there-a-way-to-use-phantomjs-in-python
http://toddhayton.com/2015/02/03/scraping-with-python-selenium-and-phantomjs/

SlimerJS:
http://docs.slimerjs.org/0.9/quick-start.html

I also while answering this question stumbled over the following page
listing (supposedly) almost every headless browser or framework in
existence:
https://github.com/dhamaniasad/HeadlessBrowsers

I see there's a couple of other possible options on there, but I'll leave
it up to you to investigate.

Good luck,

Walter

From badouglas at gmail.com  Fri Jul 29 18:10:04 2016
From: badouglas at gmail.com (bruce)
Date: Fri, 29 Jul 2016 18:10:04 -0400
Subject: [Tutor] Unable to download <th>, <td> using Beautifulsoup
In-Reply-To: <CAC7HCj9RqfNiH88d8hbaVzK9FziTmd41=BrADybc+h-y-TxESA@mail.gmail.com>
References: <CAC7HCj9RqfNiH88d8hbaVzK9FziTmd41=BrADybc+h-y-TxESA@mail.gmail.com>
Message-ID: <CAP16ngp65R9pJVR7-icc2U=Xy0kGoMpAXs7cOjhbUa5UsKEOtw@mail.gmail.com>

In following up/on what Walter said.

If the browser without cookies/javascript enabled doesn't generate the
content, you need to have a different approach.

The most "complete" is the use of a headless browser. However, the
use/implementation of a headless browser has its' own share of issues.
Speed, complexity, etc...

A potentially better/useful method is to view/look at the traffic
(livehttpheaders for Firefox) to get a feel for exactly what the browser
requires. At the same time, view the subordinate jscript functions.

I've found it's often enough to craft the requisite cookies/curl functions
in order to simulate the browser data.

In a few cases though, I've run across situations where a headless browser
is the only real soln.



On Fri, Jul 29, 2016 at 3:28 AM, Crusier <crusier at gmail.com> wrote:

> I am using Python 3 on Windows 7.
>
> However, I am unable to download some of the data listed in the web
> site as follows:
>
> http://data.tsci.com.cn/stock/00939/STK_Broker.htm
>
> 453.IMC 98.28M 18.44M 4.32 5.33 1499.Optiver 70.91M 13.29M 3.12 5.34
> 7387.???? 52.72M 9.84M 2.32 5.36
>
> When I use Google Chrome and use 'View Page Source', the data does not
> show up at all. However, when I use 'Inspect', I can able to read the
> data.
>
> '<th>1453.IMC</th>'
> '<td>98.28M</td>'
> '<td>18.44M</td>'
> '<td>4.32</td>'
> '<td>5.33</td>'
>
> '<th>1499.Optiver </th>'
> '<td> 70.91M</td>'
> '<td>13.29M </td>'
> '<td>3.12</td>'
> '<td>5.34</td>'
>
> Please kindly explain to me if the data is hide in CSS Style sheet or
> is there any way to retrieve the data listed.
>
> Thank you
>
> Regards, Crusier
>
> from bs4 import BeautifulSoup
> import urllib
> import requests
>
>
>
>
> stock_code = ('00939', '0001')
>
> def web_scraper(stock_code):
>
>     broker_url = 'http://data.tsci.com.cn/stock/'
>     end_url = '/STK_Broker.htm'
>
>     for code in stock_code:
>
>         new_url  = broker_url + code + end_url
>         response = requests.get(new_url)
>         html = response.content
>         soup = BeautifulSoup(html, "html.parser")
>         Buylist = soup.find_all('div', id ="BuyingSeats")
>         Selllist = soup.find_all('div', id ="SellSeats")
>
>
>         print(Buylist)
>         print(Selllist)
>
>
>
> web_scraper(stock_code)
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From alan.gauld at yahoo.co.uk  Fri Jul 29 18:59:53 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 29 Jul 2016 23:59:53 +0100
Subject: [Tutor] Unable to download <th>, <td> using Beautifulsoup
In-Reply-To: <CAP16ngp65R9pJVR7-icc2U=Xy0kGoMpAXs7cOjhbUa5UsKEOtw@mail.gmail.com>
References: <CAC7HCj9RqfNiH88d8hbaVzK9FziTmd41=BrADybc+h-y-TxESA@mail.gmail.com>
 <CAP16ngp65R9pJVR7-icc2U=Xy0kGoMpAXs7cOjhbUa5UsKEOtw@mail.gmail.com>
Message-ID: <nngn59$eiq$1@ger.gmane.org>

On 29/07/16 23:10, bruce wrote:

> The most "complete" is the use of a headless browser. However, the
> use/implementation of a headless browser has its' own share of issues.
> Speed, complexity, etc...

Walter and Bruce have jumped ahead a few steps from where I was
heading but basically it's an increasingly common scenario where
web pages are no longer primarily html but rather are
Javascript programs that fetch data dynamically.

A headless browser is the brute force way to deal with such issues
but a better (purer?) way is to access the same API that the browser
is using. Many web sites now publish RESTful APIs with web
services that you can call directly. It is worth investigating
whether your target has this. If so that will generally provide
a much nicer solution than trying to drive a headless browser.

Finally you need to consider whether you have the right to the
data without running a browser? Many sites provide information
for free but get paid by adverts. If you bypass the web screen
(adverts) you  bypass their revenue and they do not allow that.
So you need to be sure that you are legally entitled to scrape
data from the site or use an API.

Otherwise you may be on the wrong end of a law suite, or at
best be contributing to the demise of the very site you are
trying to use.

-- 
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  Fri Jul 29 20:32:40 2016
From: badouglas at gmail.com (bruce)
Date: Fri, 29 Jul 2016 20:32:40 -0400
Subject: [Tutor] Unable to download <th>, <td> using Beautifulsoup
In-Reply-To: <nngn59$eiq$1@ger.gmane.org>
References: <CAC7HCj9RqfNiH88d8hbaVzK9FziTmd41=BrADybc+h-y-TxESA@mail.gmail.com>
 <CAP16ngp65R9pJVR7-icc2U=Xy0kGoMpAXs7cOjhbUa5UsKEOtw@mail.gmail.com>
 <nngn59$eiq$1@ger.gmane.org>
Message-ID: <CAP16ngpZjuoOnCCK8To2_RABKo1dBfois25sR7vsALdWkXJ0sA@mail.gmail.com>

Hey Alan...

Wow APIs.. yeah.. would be cool!!!

I've worked on scraping data from lots of public sites, that have no issue
(as long as you're kind) that have no clue/resource regarding offerning
APIs.

However, yeah, if you''re looking to "rip" off a site that has adverts,
prob not a cool thing to do, no matter what tools are used.



On Fri, Jul 29, 2016 at 6:59 PM, Alan Gauld via Tutor <tutor at python.org>
wrote:

> On 29/07/16 23:10, bruce wrote:
>
> > The most "complete" is the use of a headless browser. However, the
> > use/implementation of a headless browser has its' own share of issues.
> > Speed, complexity, etc...
>
> Walter and Bruce have jumped ahead a few steps from where I was
> heading but basically it's an increasingly common scenario where
> web pages are no longer primarily html but rather are
> Javascript programs that fetch data dynamically.
>
> A headless browser is the brute force way to deal with such issues
> but a better (purer?) way is to access the same API that the browser
> is using. Many web sites now publish RESTful APIs with web
> services that you can call directly. It is worth investigating
> whether your target has this. If so that will generally provide
> a much nicer solution than trying to drive a headless browser.
>
> Finally you need to consider whether you have the right to the
> data without running a browser? Many sites provide information
> for free but get paid by adverts. If you bypass the web screen
> (adverts) you  bypass their revenue and they do not allow that.
> So you need to be sure that you are legally entitled to scrape
> data from the site or use an API.
>
> Otherwise you may be on the wrong end of a law suite, or at
> best be contributing to the demise of the very site you are
> trying to use.
>
> --
> 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 jkornonthecob at yahoo.com  Sat Jul 30 00:31:03 2016
From: jkornonthecob at yahoo.com (Justin Korn)
Date: Sat, 30 Jul 2016 00:31:03 -0400
Subject: [Tutor] Help on Assginments
Message-ID: <24B4556D-A3BE-4AE5-BFE6-17DD86FE242A@yahoo.com>

To whom it may concern, I need someone to help me to develop programs for the following assignments:



1. Define a new kind of Turtle, TurtleGTX, that comes with some extra features: it can jump forward a given distance, and it has an odometer that keeps track of how far the turtle has travelled since it came off the production line. (The parent class has a number of synonyms like fd, forward, back, backward, and bk: for this exercise, just focus on putting this functionality into the forward method.) Think carefully about how to count the distance if the turtle is asked to move forward by a negative amount. (We would not want to buy a second-hand turtle whose odometer reading was faked because its previous owner drove it backwards around the block too often. Try this in a car near you, and see if the car?s odometer counts up or down when you reverse.)

2. You are to develop a program (name it trivia_game.py) that will play a trivia game with two players.  The game will be played this way:
Starting with player 1, each player gets a turn at answering 5 trivia questions.  When a question is displayed, 4 possible answers are also displayed (1 of the 4 is the correct answer).  A correct answer earns the player 1 point.
After both players have answered their 5 questions the program will display the number of points earned by each player and declare the player with the most points the winner (or a tie if both players have earned the same number of points).
You must write a class (name it Question.py) to hold the data for a trivia question.  The class should have the following attributes:

A trivia question
Possible answer 1
Possible answer 2
Possible answer 3
Possible answer 4
The number of the correct answer (1, 2, 3, or 4)
The Question class should have an appropriate __init__ method, accessors and mutators.

Your program should have a list or dictionary containing 10 Question objects, one for each trivia question. You are to make up your own trivia questions. 

Submit both files (zip the two files if possible).


Our final exam is a real world problem about efficiency in a warehouse.  
3. 
XYZ Corporation sells products online.  The company has a large warehouse in which it stores its inventory of products.  Orders are picked, packed and shipped from the warehouse.

XYZ Corporation has contracted with you to write a program that will minimize the number of steps that the staff in the warehouse (called ODA's) take in picking the products ordered by customers.

The information you will need to complete this assignment are in the following files:

Specifications: CTIM285_Summer_2016_FinalExam.pdf
Warehouse Map: WarehouseImage.pdf
Data for Analysis:  warehouse_data_final_exam_Python.txt
Data for Analysis is saved in this order on each line of the file:
[orderNumber, partNumber, quantyNumber, aisleNumber, shelfNumber, binNumber]










Thanks,
Justin

From michael.selik at gmail.com  Fri Jul 29 22:58:47 2016
From: michael.selik at gmail.com (Michael Selik)
Date: Sat, 30 Jul 2016 02:58:47 +0000
Subject: [Tutor] IDLE Subprocess Startup Error
In-Reply-To: <FA1420A0-3EEB-47FE-A4B3-2F928D43F6B0@yahoo.com>
References: <FA1420A0-3EEB-47FE-A4B3-2F928D43F6B0@yahoo.com>
Message-ID: <CAGgTfkOMOnXh3A3DjHyDztxdyFrs866zHYPtf-SazoE=7kQ2EQ@mail.gmail.com>

On Fri, Jul 29, 2016, 2:11 AM Darah via Tutor <tutor at python.org> wrote:

> "IDLE's subprocess didn't make connection.  Either IDLE can't start a
> subprocess or personal firewall software is blocking the connection.?
>

In the last few days, have you installed any other software? Perhaps
something has changed your firewall settings.

>

From alan.gauld at yahoo.co.uk  Sat Jul 30 04:07:57 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 30 Jul 2016 09:07:57 +0100
Subject: [Tutor] Help on Assginments
In-Reply-To: <24B4556D-A3BE-4AE5-BFE6-17DD86FE242A@yahoo.com>
References: <24B4556D-A3BE-4AE5-BFE6-17DD86FE242A@yahoo.com>
Message-ID: <nnhn8u$epq$1@ger.gmane.org>

On 30/07/16 05:31, Justin Korn via Tutor wrote:
> ...I need someone to help me to develop programs for the following assignments:

That's not really how tutor list works.
We will answer your questions and give you hints when
you get stuck. But it is the whole list membership helping
you, not a designated "someone".

As to your projects here's what I'd recommend.

1) Tackle them one by one, it keeps the email threads
   separate and the archives easier to search.

2) Make a start, write some code. When you get stuck or
   something doesn't work as expected, ask here.

3) Always remind us of which OS and Python version you
   are using

4) If there are error messages send the whole error
   text not a summary.


> 1. Define a new kind of Turtle, ...

This one slightly confused me since the standard turtle
can already jump forward a given distance. The only new
feature appears to be the odometer concept?

> 2. You are to develop a program (name it trivia_game.py) that 
> will play a trivia game with two players.
...
> You must write a class (name it Question.py) to hold the data

This seems straightforward but a tad tedious creating the
data. It would have been nice if they provided a data file!

> Our final exam is a real world problem about efficiency in a warehouse.  

Slightly more challenging but nothing too difficult
provided you can do the math and the document provided
is sufficiently clear.


Based on the questions I assume you have a reasonably good understanding
of Python basics including the data structures, functions, classes and
objects, files, and how to import
and use modules?

-- 
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 jkornonthecob at yahoo.com  Sat Jul 30 11:28:28 2016
From: jkornonthecob at yahoo.com (Justin Korn)
Date: Sat, 30 Jul 2016 11:28:28 -0400
Subject: [Tutor] Help on Assignments
Message-ID: <663CEC8A-2333-4600-AFA8-E252CAB3DF6F@yahoo.com>

To whom it may concern, I need someone to help me to develop programs for the following assignments. I have been working on these assignments for a week and a half, and I can't make any progress. I also been dealing with a sick relative, so please help me out immediately. I use the version 3.4.1. Here are the following assignments and what I have so far:



1. Define a new kind of Turtle, TurtleGTX, that comes with some extra features: it can jump forward a given distance, and it has an odometer that keeps track of how far the turtle has travelled since it came off the production line. (The parent class has a number of synonyms like fd, forward, back, backward, and bk: for this exercise, just focus on putting this functionality into the forward method.) Think carefully about how to count the distance if the turtle is asked to move forward by a negative amount. (We would not want to buy a second-hand turtle whose odometer reading was faked because its previous owner drove it backwards around the block too often. Try this in a car near you, and see if the car?s odometer counts up or down when you reverse.)



import turtle
class turtle_Turtle():
    ts = turtle.Screen()
    ts.title("TurtleGTX")
    bob = turtle.Turtle()
    bob.shape("turtle")
    bob.color("brown")

class TurtleGTX(turtle_Turtle):
    odometer = 0
    def forward(x):
        if (x >= 0):
            i = 0
            while (i < x):
                self.fd()
                odometer += 1
                i+=1
        else:
            i = 0
            while (i > x):
                self.bk()
                odometer +=1
                i-=1
        print ("Odometer is", odemeter)


my_turtle = TurtleGTX()
my_turtle.foward()


2. You are to develop a program (name it trivia_game.py) that will play a trivia game with two players.  The game will be played this way:
Starting with player 1, each player gets a turn at answering 5 trivia questions.  When a question is displayed, 4 possible answers are also displayed (1 of the 4 is the correct answer).  A correct answer earns the player 1 point.
After both players have answered their 5 questions the program will display the number of points earned by each player and declare the player with the most points the winner (or a tie if both players have earned the same number of points).
You must write a class (name it Question.py) to hold the data for a trivia question.  The class should have the following attributes:

A trivia question
Possible answer 1
Possible answer 2
Possible answer 3
Possible answer 4
The number of the correct answer (1, 2, 3, or 4)
The Question class should have an appropriate __init__ method, accessors and mutators.

Your program should have a list or dictionary containing 10 Question objects, one for each trivia question. You are to make up your own trivia questions. 

Submit both files (zip the two files if possible).

trivia_game.py
import sys
import random
import Question.py

questions = [
    Question("How many states start with the letter M", 3, ["6", "7", "8", "9"]),
    Question("What is the area of a right triagle with a hypotenuse of 10 and an altitude of 8", 1, ["24", "40", "48", "80"]),     
    Question("Which physics quantity is not a vector", 4, ["Acceleration", "Momentum", "Torque", "Work"]),
    Question("How many inches are in a foot", 2, ["6", "12", "18", "24"]),
    Question("Who does not play in the NFL anymore", 3, ["Frank Gore", "Richard Sherman", "Peyton Manning", "Antonio Gates"]),
    Question("What is a bakers dozen equivalent to", 4, ["10", "11", "12", "13"]),
    Question("Which city has a NBA team", 1, ["Sacramento", "Baltimore", "St. Louis", "Pittsburgh"]),
    Question("Which of the following elements have eleven protons", 4, ["boron", "sulfur", "floruine", "sodium"]),
    Question("What is the minimum age to run for president of the United States", 2, ["30", "35", "40", "45"]),
    Question("Who won super bowl 44", 1, ["New Orleans Saints", "Pittsburgh Steelers", "Minnesota Vikings", "Indianapolis Colts"])
            ]
    

random.shuffle(questions)    # Randomize the order of the questions

for question in questions:
    question.ask()

Question.py

3. Our final exam is a real world problem about efficiency in a warehouse.  

XYZ Corporation sells products online.  The company has a large warehouse in which it stores its inventory of products.  Orders are picked, packed and shipped from the warehouse.

XYZ Corporation has contracted with you to write a program that will minimize the number of steps that the staff in the warehouse (called ODA's) take in picking the products ordered by customers.

The information you will need to complete this assignment are in the following files:

Specifications: CTIM285_Summer_2016_FinalExam.pdf
Warehouse Map: WarehouseImage.pdf
Data for Analysis:  warehouse_data_final_exam_Python.txt
Data for Analysis is saved in this order on each line of the file:
[orderNumber, partNumber, quantyNumber, aisleNumber, shelfNumber, binNumber]



infile = open("warehouse_data.txt", "r")
for x in infile
    for j in range(3, 6):
        if (j == 1):
            temp=a[0:3]
            a[0:3]=a[3:]
            a[3:]=temp
  
Thanks,
Justin          

From alan.gauld at yahoo.co.uk  Sat Jul 30 19:03:42 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 31 Jul 2016 00:03:42 +0100
Subject: [Tutor] Help on Assignments - Turtle
In-Reply-To: <663CEC8A-2333-4600-AFA8-E252CAB3DF6F@yahoo.com>
References: <663CEC8A-2333-4600-AFA8-E252CAB3DF6F@yahoo.com>
Message-ID: <nnjboj$o4l$1@blaine.gmane.org>

On 30/07/16 16:28, Justin Korn via Tutor wrote:
> I have been working on these assignments for a week and a half, 
> and I can't make any progress. I also been dealing with a
> sick relative, so please help me out immediately.

While I sympathise with your circumstances we are all
volunteers here so the help you receive will be at the
speed that suits the members.

I will address your two assignments in separate mails.


> import turtle
> class turtle_Turtle():
>     ts = turtle.Screen()
>     ts.title("TurtleGTX")
>     bob = turtle.Turtle()
>     bob.shape("turtle")
>     bob.color("brown")

I'm not sure what you think this is doing but I'm
pretty sure its not what you want. You are basically
defining a couple of class variables and nothing else...

> class TurtleGTX(turtle_Turtle):

I would have expected you to inherit from turtle.Turtle
rather than turtle_Turtle. The latter has no methods and
only two class variables. So your GTX class likewise has
no inherited methods, you will need to define all of
its behaviour.

>     odometer = 0

This is a class variable meaning it is shared by all
turtles. I suspect you really want it to be an instance
attribute, which means defined within an __init__()


>     def forward(x):

The first parameter of a class method is usually called
self because it will refer to the active object. In this
case your x will be the object, whereas I think you want
it to be the distance to move? But if so x is a bad choice
of name since it implies horizontal direction only

>         if (x >= 0):
>             i = 0
>             while (i < x):
>                 self.fd()
>                 odometer += 1
>                 i+=1

This is a horribly inefficient way of saying

if x>=0:
  self.fd(x)
  odometer += x

But it won't work because
a) You didn't inherit from turtle so you don't have a fd() method
b) Even if you had it requires an input value for its distance
so should be self.fd(1)


>         else:
>             i = 0
>             while (i > x):
>                 self.bk()
>                 odometer +=1
>                 i-=1

Again a very inefficient alternative to

else:
   x = -x
   self.bk(x)
   odometer += x

>         print ("Odometer is", odemeter)

Do you really want to print that every time the turtle moves?

> my_turtle = TurtleGTX()
> my_turtle.foward()

You misspelled forward and failed to give it an x value.
Please send real code and/or any error messages. This code
could never have run so you should have errors.



-- 
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 yahoo.co.uk  Sat Jul 30 19:11:40 2016
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 31 Jul 2016 00:11:40 +0100
Subject: [Tutor] Help on Assignments - trivia game
In-Reply-To: <663CEC8A-2333-4600-AFA8-E252CAB3DF6F@yahoo.com>
References: <663CEC8A-2333-4600-AFA8-E252CAB3DF6F@yahoo.com>
Message-ID: <nnjc7d$td8$1@blaine.gmane.org>

On 30/07/16 16:28, Justin Korn via Tutor wrote:

> trivia_game.py

> import sys
> import random
> import Question.py

You do not include the .py extension in an import
statement. It should read

import Question

Also by convention modules use lowercase names.

> questions = [
>     Question("How many states start with the letter M", 3, ["6", "7", "8", "9"]),

You are trying to instantiate a Question object but it is (presumably)
defined in the question.py class which you import. If so you need to
prefix it with the module name like so

Question.Question(...)

>     Question("What is the area of a right triagle with a hypotenuse of 10 and an altitude of 8", 1, ["24", "40", "48", "80"]),     
>     Question("Which physics quantity is not a vector", 4, ["Acceleration", "Momentum", "Torque", "Work"]),

List indices start from zero so your highest index should be 3.
Assuming you intend to use the '4' as an index to the correct answer?

>     Question("Who won super bowl 44", 1, ["New Orleans Saints", "Pittsburgh Steelers", "Minnesota Vikings", "Indianapolis Colts"])
>             ]
>     
> 
> random.shuffle(questions)    # Randomize the order of the questions
> 
> for question in questions:
>     question.ask()
> 
> Question.py

???
I'm expecting a class definition here with at least
__init__() and ask() methods. And it needs to store
the question, possible answers and correct answer
somewhere 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 fiberfolly at gmail.com  Sun Jul 31 19:14:59 2016
From: fiberfolly at gmail.com (D Wyatt)
Date: Sun, 31 Jul 2016 16:14:59 -0700
Subject: [Tutor] Book recommendation
Message-ID: <CANk7HcPKyb187gSM1HJ+KRmFHQ=Xc5QBDFFMj5sQfponmYZ5ZQ@mail.gmail.com>

Hello.  I've been a member of this group for a very long time and have
played with Python for years, but have never gotten past being a beginner
for various reasons.  I just discovered a very good, free book, that is
answering many of the questions I have had in the past that I never got
answers I could understand from you all.  While I appreciate the time and
effort you put in helping us out, most of you do not remember what you
didn't used to know, and are often less than helpful because of this.  This
is not meant as a criticism, but just my observation.

Anyway, this book I found, Learning Python, is well-written and easy to
understand.  Here is a url to it.    https://www.packtpub.com/tech/python.

no affiliation, etc, I just wanted to share this great resource.  I am
finding this book so easy to read I am reading it instead of my usual
non-fiction.

-- 
Deb Wyatt in WA

From gokoproject at gmail.com  Sun Jul 31 19:35:47 2016
From: gokoproject at gmail.com (John Wong)
Date: Sun, 31 Jul 2016 19:35:47 -0400
Subject: [Tutor] Book recommendation
In-Reply-To: <CANk7HcPKyb187gSM1HJ+KRmFHQ=Xc5QBDFFMj5sQfponmYZ5ZQ@mail.gmail.com>
References: <CANk7HcPKyb187gSM1HJ+KRmFHQ=Xc5QBDFFMj5sQfponmYZ5ZQ@mail.gmail.com>
Message-ID: <CACCLA57M-_ViWOP+iZdhObAUd_H4+W2G_-o+Kv-B=PNUV7ENkg@mail.gmail.com>

On Sun, Jul 31, 2016 at 7:14 PM, D Wyatt <fiberfolly at gmail.com> wrote:

> Hello.  I've been a member of this group for a very long time and have
> played with Python for years, but have never gotten past being a beginner
> for various reasons.  I just discovered a very good, free book, that is
> answering many of the questions I have had in the past that I never got
> answers I could understand from you all.  While I appreciate the time and
> effort you put in helping us out, most of you do not remember what you
> didn't used to know, and are often less than helpful because of this.  This
> is not meant as a criticism, but just my observation.
>
>
I think that's a constructive feedback. There are two problems. One is
often the question itself is not well-phrased. The other is remote
communication is a known challenge. I could spend a whole hour doing pair
programming or whiteboarding a solution with someone next to me physically,
but I can't do that over the Internet easily. The person asking the
question may not respond to my reply the next day (timezone difference).
It's a hard problem. I often ask my questions on IRC, and my experience is
also not quite as good as I would hope, although there are enough people to
chime in.

A lot of learning is practice, and then having a mentor available.


> Anyway, this book I found, Learning Python, is well-written and easy to
> understand.  Here is a url to it.    https://www.packtpub.com/tech/python.
>
>
Great. I am glad you found one that's helping you. I share the view that
any book is a good book as long as the book is giving correct information.

A few other ones:
* Think Python: How to Think Like a Computer Scientist
* Learning Python by Mark Lutz - I started my journey with this, many years
ago
* Dive Into Python - quite good for beginnger
* Google's Python Class - very gentle introduction
* Python classes online (e.g. the ones available on MIT OCW) - pretty good
if you like slow, lecture-based.
* Python documentation
* Python Essential Reference (for intermediate -> advanced)
* Learn Python the Hard Way (not so much into this, just personal
preferences)

Just my 3.1415 cents.

John