From steve at pearwood.info  Fri Jul  1 04:15:45 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 01 Jul 2011 12:15:45 +1000
Subject: [Tutor] The Card Game
In-Reply-To: <BANLkTi=n6R090rgCv6_CHzBCRxAWAG1kjw@mail.gmail.com>
References: <31961149.post@talk.nabble.com>	<iuhg0q$369$1@dough.gmane.org>
	<BANLkTi=n6R090rgCv6_CHzBCRxAWAG1kjw@mail.gmail.com>
Message-ID: <4E0D2DD1.6040508@pearwood.info>

Christopher King wrote:
> I would go with __cmp__ which covers them all. 1 for greater, 0 for equal,
> -1 for less than.


So-called "rich comparisons" using __lt__, __gt__, etc. have been 
preferred since Python 2.1. The major advantage of them is that they can 
be used for more complicated data types, e.g. with sets where > means 
superset and < means subset:


 >>> a = set([1, 2, 3, 4])
 >>> b = set([2, 3, 4, 5])
 >>>
 >>> a < b  # a is not a subset of b
False
 >>> a > b  # neither is it a superset
False
 >>> a == b  # and they're not equal either
False
 >>> a & b  # but they do overlap:
set([2, 3, 4])



In Python 2.x, __cmp__ is only used as a fall-back if the rich 
comparisons aren't defined. In Python 3.x, __cmp__ is gone: even if you 
define it, it won't be used.




From vincentbalmori at yahoo.com  Fri Jul  1 09:28:26 2011
From: vincentbalmori at yahoo.com (Vincent Balmori)
Date: Fri, 1 Jul 2011 00:28:26 -0700 (PDT)
Subject: [Tutor] Blackjack Betting
In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2E4E8A78CE@EMARC112VS01.exchad.jpmchase.net>
References: <31966195.post@talk.nabble.com>
	<0604E20B5F6F2F4784C9C8C71C5DD4DD2E4E8A78CE@EMARC112VS01.exchad.jpmchase.net>
Message-ID: <31971453.post@talk.nabble.com>


Sorry. Here is the entire Error stack if this can help.

Traceback (most recent call last):
  File
"/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
line 240, in <module>
    main()
  File
"/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
line 236, in main
    game.play()
  File
"/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
line 204, in play
    player.win()
  File
"/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
line 129, in win
    bet.stash += bet.wager



Prasad, Ramit wrote:
> 
>>I keep getting the error: ?NameError: global
>>name 'bet' is not defined.? I know I came across this error before in a
>>previous thread, but I am confused on how to solve this, since I am also
>>trying to juggle it with inherited methods at the same time.
> 
> Telling us this without the stack trace is pretty unhelpful. The Python
> exceptions include a very good stack trace (with line numbers +- 1 line)
> and a decent description. This error means that wherever this error was
> raised was a reference to the name "bet" and it had no reference to any
> "bet" at that point. The reasons could be that you forgot to assign a
> value to the name first, maybe it was a typo, in a preceding function,
> forgot the reference to self, etc, etc.
> 
> I took a *quick* look at the code and found this (I did not check for
> other problems or if this error happens in more than one place):
> 
> 
> class BJ_Player(BJ_Hand, Bet):
>     """ A Blackjack Player. """
>     def is_hitting(self):
>         response = games.ask_yes_no("\n" + self.name + ", do you want a
> hit? (Y/N): ")
>         return response == "y"
> 
>     def bust(self):
>         print(self.name, "busts.")
>         self.lose()
> 
>     def lose(self):
>         print(self.name, "loses.")
>         betting = Bet()
>         bet.stash -= bet.wager
> 
>     def win(self):
>         print(self.name, "wins.")
>         bet = Bet()
>         bet.stash += bet.wager
> 
>     def push(self):
>         print(self.name, "pushes.")
> 
> 
> There are a couple things wrong with this class. First, you never define
> an __init__ which might be technically okay but is unlikely to be what you
> want for any user defined class (especially one with multiple
> inheritance). Since there is no __init__ defined, it will call the first
> parent class BJ_Hand.__init__ but not the second parent class Bet.__init__
> (if it has one). 
> 
> Next for BJ_Player.lose(), bet is never defined and thus neither is
> bet.stash. Maybe you meant betting.stash -= betting.wager? I bet if you
> ran lint/pylint on this module it would have told you the error without
> even having to run it.
> 
> 
> Ramit
> 
> 
> Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
> 712 Main Street | Houston, TX 77002
> work phone: 713 - 216 - 5423
> 
> 
> 
> -----Original Message-----
> From: tutor-bounces+ramit.prasad=jpmchase.com at python.org
> [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of
> Vincent Balmori
> Sent: Thursday, June 30, 2011 1:49 PM
> To: tutor at python.org
> Subject: [Tutor] Blackjack Betting
> 
> 
> I have been working on another challenge that involves improving the
> Blackjack program so the players can wager an amount. If a player loses
> they
> will be removed from the game.  I keep getting the error: ?NameError:
> global
> name 'bet' is not defined.? I know I came across this error before in a
> previous thread, but I am confused on how to solve this, since I am also
> trying to juggle it with inherited methods at the same time. Here is the
> old
> and new file for the blackjack program for comparison:
> 
> http://old.nabble.com/file/p31966195/blackjack.py blackjack.py 
> http://old.nabble.com/file/p31966195/blackjackbetting.py
> blackjackbetting.py 
> -- 
> View this message in context:
> http://old.nabble.com/Blackjack-Betting-tp31966195p31966195.html
> Sent from the Python - tutor mailing list archive at Nabble.com.
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> This communication is for informational purposes only. It is not
> intended as an offer or solicitation for the purchase or sale of
> any financial instrument or as an official confirmation of any
> transaction. All market prices, data and other information are not
> warranted as to completeness or accuracy and are subject to change
> without notice. Any comments or statements made herein do not
> necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
> and affiliates.
> 
> This transmission may contain information that is privileged,
> confidential, legally privileged, and/or exempt from disclosure
> under applicable law. If you are not the intended recipient, you
> are hereby notified that any disclosure, copying, distribution, or
> use of the information contained herein (including any reliance
> thereon) is STRICTLY PROHIBITED. Although this transmission and any
> attachments are believed to be free of any virus or other defect
> that might affect any computer system into which it is received and
> opened, it is the responsibility of the recipient to ensure that it
> is virus free and no responsibility is accepted by JPMorgan Chase &
> Co., its subsidiaries and affiliates, as applicable, for any loss
> or damage arising in any way from its use. If you received this
> transmission in error, please immediately contact the sender and
> destroy the material in its entirety, whether in electronic or hard
> copy format. Thank you.
> 
> Please refer to http://www.jpmorgan.com/pages/disclosures for
> disclosures relating to European legal entities.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
View this message in context: http://old.nabble.com/Blackjack-Betting-tp31966195p31971453.html
Sent from the Python - tutor mailing list archive at Nabble.com.


From vincentbalmori at yahoo.com  Fri Jul  1 09:29:50 2011
From: vincentbalmori at yahoo.com (Vincent Balmori)
Date: Fri, 1 Jul 2011 00:29:50 -0700 (PDT)
Subject: [Tutor] Blackjack Betting
In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2E4E8A78CE@EMARC112VS01.exchad.jpmchase.net>
References: <31966195.post@talk.nabble.com>
	<0604E20B5F6F2F4784C9C8C71C5DD4DD2E4E8A78CE@EMARC112VS01.exchad.jpmchase.net>
Message-ID: <31971461.post@talk.nabble.com>


Here is the other one that occurs when I lose

Traceback (most recent call last):
  File
"/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
line 240, in <module>
    main()
  File
"/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
line 236, in main
    game.play()
  File
"/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
line 211, in play
    player.lose()
  File
"/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
line 124, in lose
    bet.stash -= bet.wager
NameError: global name 'bet' is not defined


Prasad, Ramit wrote:
> 
>>I keep getting the error: ?NameError: global
>>name 'bet' is not defined.? I know I came across this error before in a
>>previous thread, but I am confused on how to solve this, since I am also
>>trying to juggle it with inherited methods at the same time.
> 
> Telling us this without the stack trace is pretty unhelpful. The Python
> exceptions include a very good stack trace (with line numbers +- 1 line)
> and a decent description. This error means that wherever this error was
> raised was a reference to the name "bet" and it had no reference to any
> "bet" at that point. The reasons could be that you forgot to assign a
> value to the name first, maybe it was a typo, in a preceding function,
> forgot the reference to self, etc, etc.
> 
> I took a *quick* look at the code and found this (I did not check for
> other problems or if this error happens in more than one place):
> 
> 
> class BJ_Player(BJ_Hand, Bet):
>     """ A Blackjack Player. """
>     def is_hitting(self):
>         response = games.ask_yes_no("\n" + self.name + ", do you want a
> hit? (Y/N): ")
>         return response == "y"
> 
>     def bust(self):
>         print(self.name, "busts.")
>         self.lose()
> 
>     def lose(self):
>         print(self.name, "loses.")
>         betting = Bet()
>         bet.stash -= bet.wager
> 
>     def win(self):
>         print(self.name, "wins.")
>         bet = Bet()
>         bet.stash += bet.wager
> 
>     def push(self):
>         print(self.name, "pushes.")
> 
> 
> There are a couple things wrong with this class. First, you never define
> an __init__ which might be technically okay but is unlikely to be what you
> want for any user defined class (especially one with multiple
> inheritance). Since there is no __init__ defined, it will call the first
> parent class BJ_Hand.__init__ but not the second parent class Bet.__init__
> (if it has one). 
> 
> Next for BJ_Player.lose(), bet is never defined and thus neither is
> bet.stash. Maybe you meant betting.stash -= betting.wager? I bet if you
> ran lint/pylint on this module it would have told you the error without
> even having to run it.
> 
> 
> Ramit
> 
> 
> Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
> 712 Main Street | Houston, TX 77002
> work phone: 713 - 216 - 5423
> 
> 
> 
> -----Original Message-----
> From: tutor-bounces+ramit.prasad=jpmchase.com at python.org
> [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of
> Vincent Balmori
> Sent: Thursday, June 30, 2011 1:49 PM
> To: tutor at python.org
> Subject: [Tutor] Blackjack Betting
> 
> 
> I have been working on another challenge that involves improving the
> Blackjack program so the players can wager an amount. If a player loses
> they
> will be removed from the game.  I keep getting the error: ?NameError:
> global
> name 'bet' is not defined.? I know I came across this error before in a
> previous thread, but I am confused on how to solve this, since I am also
> trying to juggle it with inherited methods at the same time. Here is the
> old
> and new file for the blackjack program for comparison:
> 
> http://old.nabble.com/file/p31966195/blackjack.py blackjack.py 
> http://old.nabble.com/file/p31966195/blackjackbetting.py
> blackjackbetting.py 
> -- 
> View this message in context:
> http://old.nabble.com/Blackjack-Betting-tp31966195p31966195.html
> Sent from the Python - tutor mailing list archive at Nabble.com.
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> This communication is for informational purposes only. It is not
> intended as an offer or solicitation for the purchase or sale of
> any financial instrument or as an official confirmation of any
> transaction. All market prices, data and other information are not
> warranted as to completeness or accuracy and are subject to change
> without notice. Any comments or statements made herein do not
> necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
> and affiliates.
> 
> This transmission may contain information that is privileged,
> confidential, legally privileged, and/or exempt from disclosure
> under applicable law. If you are not the intended recipient, you
> are hereby notified that any disclosure, copying, distribution, or
> use of the information contained herein (including any reliance
> thereon) is STRICTLY PROHIBITED. Although this transmission and any
> attachments are believed to be free of any virus or other defect
> that might affect any computer system into which it is received and
> opened, it is the responsibility of the recipient to ensure that it
> is virus free and no responsibility is accepted by JPMorgan Chase &
> Co., its subsidiaries and affiliates, as applicable, for any loss
> or damage arising in any way from its use. If you received this
> transmission in error, please immediately contact the sender and
> destroy the material in its entirety, whether in electronic or hard
> copy format. Thank you.
> 
> Please refer to http://www.jpmorgan.com/pages/disclosures for
> disclosures relating to European legal entities.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
View this message in context: http://old.nabble.com/Blackjack-Betting-tp31966195p31971461.html
Sent from the Python - tutor mailing list archive at Nabble.com.


From andreengels at gmail.com  Fri Jul  1 09:51:16 2011
From: andreengels at gmail.com (Andre Engels)
Date: Fri, 1 Jul 2011 09:51:16 +0200
Subject: [Tutor] Blackjack Betting
In-Reply-To: <31971461.post@talk.nabble.com>
References: <31966195.post@talk.nabble.com>
	<0604E20B5F6F2F4784C9C8C71C5DD4DD2E4E8A78CE@EMARC112VS01.exchad.jpmchase.net>
	<31971461.post@talk.nabble.com>
Message-ID: <BANLkTin=tGos3vhaSPnr5W1C-ufgx_S9Cg@mail.gmail.com>

On Fri, Jul 1, 2011 at 9:29 AM, Vincent Balmori <vincentbalmori at yahoo.com>wrote:

>
> Here is the other one that occurs when I lose
>
> Traceback (most recent call last):
>  File
>
> "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
> line 240, in <module>
>    main()
>  File
>
> "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
> line 236, in main
>    game.play()
>  File
>
> "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
> line 211, in play
>    player.lose()
>   File
>
> "/Users/vincentbalmori/Desktop/Python/py3e_source/chapter09/blackjackbetting.py",
> line 124, in lose
>    bet.stash -= bet.wager
> NameError: global name 'bet' is not defined
>

That error message is really quite expressive, it would much more help you
to learn to read it yourself than to run to us every time something goes
wrong. The most interesting part of an error message are its last few lines,
they say what went wrong, and where it happened. The rest tells you how it
got there, which also is important to know sometimes, but many errors can
already be solved without looking at it.

In this case, the error message says:

NameError: global name 'bet' is not defined

That means, at some time at the program, it is told to do something with
'bet', but there is no variable bet. And when does that happen? That too is
told: at line 124, which says:

bet.stash -= bet.wager

Go to that line and read your code yourself - what is this 'bet' of which
the stash is to be lessened by its wager? Have you told your program that
this is the value of the variable 'bet'? Where and how?

-- 
Andr? Engels, andreengels at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110701/98d1851e/attachment-0001.html>

From ryankirk at me.com  Fri Jul  1 09:30:16 2011
From: ryankirk at me.com (Ryan Kirk)
Date: Fri, 01 Jul 2011 00:30:16 -0700
Subject: [Tutor] Limit raw_input to hundredth decimal point
Message-ID: <454D5197-386A-41BB-8A58-382E88004A36@me.com>

Is there a way to limit raw_input to the hundredth decimal point?

For example, I'd like to allow the user to enter 5.75 but not 5.756:

dollars = raw_input("Please enter a dollar amount: $")

Thanks!

From lisi.reisz at gmail.com  Fri Jul  1 11:15:08 2011
From: lisi.reisz at gmail.com (Lisi)
Date: Fri, 1 Jul 2011 10:15:08 +0100
Subject: [Tutor] problem reading script
Message-ID: <201107011015.08328.lisi.reisz@gmail.com>

I am supposed to be looking at scripts on-line, reading them and making sure 
that I understand them.  I think taht most of teh things I can't make more 
than a guess at, are modules taht I don't know, and I can mostly make them 
out.  But the unpaired double quotation mark, " , in the following has me 
stumped:

report['BzrLogTail'] = ''.join(bzr_log_tail)

The line ends accurately as it did in the script I was looking at.  In case 
you need the whole script to make out what the " means, the URL is:
http://bazaar.launchpad.net/~bzr-pqm/bzr/bzr.dev/view/head:/apport/source_bzr.py

and I have copied and pasted the function definition in which it is to be 
found after my signature.

I would be extremely grateful for an explanation/translation!

Lisi

def _add_log_tail(report):

      # may have already been added in-process

      if 'BzrLogTail' in report:

           return

  
      bzr_log_lines = open(bzr_log).readlines()

       bzr_log_lines.reverse()

  
      bzr_log_tail = []

       blanks = 0

       for line in bzr_log_lines:

           if line == '\n':

               blanks += 1

           bzr_log_tail.append(line)

  27 
          if blanks >= 2: 

  28 
              break

  29 
  30 
      bzr_log_tail.reverse()

  31 
      report['BzrLogTail'] = ''.join(bzr_log_tail)

From lisi.reisz at gmail.com  Fri Jul  1 11:21:05 2011
From: lisi.reisz at gmail.com (Lisi)
Date: Fri, 1 Jul 2011 10:21:05 +0100
Subject: [Tutor] problem reading script
In-Reply-To: <201107011015.08328.lisi.reisz@gmail.com>
References: <201107011015.08328.lisi.reisz@gmail.com>
Message-ID: <201107011021.06004.lisi.reisz@gmail.com>

On Friday 01 July 2011 10:15:08 Lisi wrote:
> I am supposed to be looking at scripts on-line, reading them and making
> sure that I understand them.  I think taht most of teh things I can't make
> more than a guess at, are modules taht I don't know, and I can mostly make
> them out.  But the unpaired double quotation mark, " , in the following has
> me stumped:
>
> report['BzrLogTail'] = ''.join(bzr_log_tail)
>
> The line ends accurately as it did in the script I was looking at.  In case
> you need the whole script to make out what the " means, the URL is:
> http://bazaar.launchpad.net/~bzr-pqm/bzr/bzr.dev/view/head:/apport/source_b
>zr.py

So sorry.  Forgot to check typos before clicking on <send>.  :-(

From martin at linux-ip.net  Fri Jul  1 11:51:20 2011
From: martin at linux-ip.net (Martin A. Brown)
Date: Fri, 1 Jul 2011 11:51:20 +0200
Subject: [Tutor] problem reading script
In-Reply-To: <201107011015.08328.lisi.reisz@gmail.com>
References: <201107011015.08328.lisi.reisz@gmail.com>
Message-ID: <alpine.LNX.2.00.1107011132390.15614@octothorpe.wonderfrog.net>


Greetings Lisi,

 : I am supposed to be looking at scripts on-line, reading them and 
 : making sure that I understand them. 

When you see an example that you don't understand, consider trying 
to do something similar in an interactive Python interpreter.  This 
is a simple way to learn in Python.

 : I think taht most of teh things I can't make more than a guess 
 : at, are modules taht I don't know, and I can mostly make them 
 : out.  But the unpaired double quotation mark, " , in the 
 : following has me stumped:

Look carefully.  It is not an unpaired double-quotation mark.  Are 
you using a monospaced font to read code?  If you are using a 
variable width font, you should change to monospaced.  Save yourself 
some future headache.  Really.  Use a monospaced font.

 : report['BzrLogTail'] = ''.join(bzr_log_tail)

Do you have a Python interpreter handy?  This is a fairly typical 
pythonic expression for concatenating elements of a list into a 
string.  Try the following in a python interpreter:

  >>> l = list()
  >>> l.append("a")
  >>> l.append("b")
  >>> l.append("c")
  >>> l
  ['a', 'b', 'c']
  >>> ''.join(l)
  'abc'

Now, you are probably wondering about that peculiar looking syntax 
for calling join() on a list.  This single quoted empty string '' is 
still a string, so it has methods that can be called on it.  Read up 
on methods available on strings [0] to get a better idea.  For other 
examples of using the string join() method, consider the following:

  >>> ':'.join(l)
  'a:b:c'

  >>> vampire = [ 'The','Deluxe','Transitive','Vampire' ]
  >>> ' '.join(vampire)
  'The Deluxe Transitive Vampire'

And, for something just a bit fancier, make a list of ints, using 
the function called range():

  >>> range(10)
  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Convert them to a list of strings:

  >>> [str(x) for x in range(10)]
  ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

Now, concatenate them and separate with some spacedash!

  >>> visual_separator = ' -- '
  >>> visual_separator.join(str(x) for x in range(10))
  '0 -- 1 -- 2 -- 3 -- 4 -- 5 -- 6 -- 7 -- 8 -- 9'

With any luck, these examples help explain what you were reading.

-Martin

 [0] http://docs.python.org/dev/library/stdtypes.html#string-methods

-- 
Martin A. Brown
http://linux-ip.net/

From izzaddin.ruhulessin at gmail.com  Fri Jul  1 12:09:46 2011
From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin)
Date: Fri, 1 Jul 2011 12:09:46 +0200
Subject: [Tutor] Limit raw_input to hundredth decimal point
In-Reply-To: <454D5197-386A-41BB-8A58-382E88004A36@me.com>
References: <454D5197-386A-41BB-8A58-382E88004A36@me.com>
Message-ID: <BANLkTimjNHiCuYOgNXfeWrfQEQ0=VYUfxw@mail.gmail.com>

You can use a regular expression or plain simple len()

2011/7/1 Ryan Kirk <ryankirk at me.com>

> Is there a way to limit raw_input to the hundredth decimal point?
>
> For example, I'd like to allow the user to enter 5.75 but not 5.756:
>
> dollars = raw_input("Please enter a dollar amount: $")
>
> Thanks!
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110701/3a041a3c/attachment.html>

From cwitts at compuscan.co.za  Fri Jul  1 12:48:58 2011
From: cwitts at compuscan.co.za (Christian Witts)
Date: Fri, 01 Jul 2011 12:48:58 +0200
Subject: [Tutor] Limit raw_input to hundredth decimal point
In-Reply-To: <454D5197-386A-41BB-8A58-382E88004A36@me.com>
References: <454D5197-386A-41BB-8A58-382E88004A36@me.com>
Message-ID: <4E0DA61A.4030101@compuscan.co.za>

On 2011/07/01 09:30 AM, Ryan Kirk wrote:
> Is there a way to limit raw_input to the hundredth decimal point?
>
> For example, I'd like to allow the user to enter 5.75 but not 5.756:
>
> dollars = raw_input("Please enter a dollar amount: $")
>
> Thanks!
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

If you're using Windows you can use the msvcrt module which has an 
implementation of getch() which gets 1 character at a time. Then you 
would just scan your input 1 character at a time and as soon as a the 
`.` is used you can limit it to 2 further key-strokes before you "ban" 
input and carry on in your process flow.
-- 

Christian Witts
Python Developer

//

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110701/60901bef/attachment.html>

From steve at pearwood.info  Fri Jul  1 15:02:31 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 01 Jul 2011 23:02:31 +1000
Subject: [Tutor] 2to3 conversion
In-Reply-To: <AANLkTinfTAzqtBfZ54V2Y0bkzVt3BVN2QsW4ukJFV0mE@mail.gmail.com>
References: <AANLkTinfTAzqtBfZ54V2Y0bkzVt3BVN2QsW4ukJFV0mE@mail.gmail.com>
Message-ID: <4E0DC567.6070107@pearwood.info>

Zubin Mithra wrote:
> Hey everyone,
> 
> I was running 2to3 on a particular file and I got the following traceback(
> http://paste.pocoo.org/show/223468/).

For short amounts of text, such as a traceback, please don't use a paste 
bin, just copy it into your post.

Some people are reading mail at a time or place where they might not 
have web access, or from somewhere that blocks access to the paste bin, 
but they can still read mail.

In your case, the error is:


Traceback (most recent call last):
   File "setup.py", line 86, in <module>
     util.run_2to3([i])
   File "/usr/lib/python3.0/distutils/util.py", line 572, in run_2to3
     r.refactor(files, write=True)
   File "/usr/lib/python3.0/lib2to3/refactor.py", line 196, in refactor
     self.refactor_file(dir_or_file, write, doctests_only)
   File "/usr/lib/python3.0/lib2to3/refactor.py", line 224, in refactor_file
     input = f.read() + "\n" # Silence certain parse errors
   File "/usr/lib/python3.0/io.py", line 1728, in read
     decoder.decode(self.buffer.read(), final=True))
   File "/usr/lib/python3.0/io.py", line 1299, in decode
     output = self.decoder.decode(input, final=final)
   File "/usr/lib/python3.0/codecs.py", line 300, in decode
     (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 232-234: 
invalid data


which looks like a bug in the 2to3 script.

This is not really a tutor question -- this list is for learning Python, 
not general Python related questions. In future, you might have better 
responses on the main python list, <python-list at python.org>.

But my guess is that the source file you are trying to convert contains 
an encoded character that doesn't exist in UTF-8. Try opening the 
original file (not the copy on the paste bin) and extracting those three 
bytes, and see what they are:


fp = open('distutils.util.py', 'r')
text = fp.read(234)
fp.close()
n = len(text.split('\n'))
s = text[232:235]
print("Bad bytes %r on line %d" % (s, n))



-- 
Steven


From steve at pearwood.info  Fri Jul  1 15:05:22 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 01 Jul 2011 23:05:22 +1000
Subject: [Tutor] 2to3 conversion
In-Reply-To: <4E0DC567.6070107@pearwood.info>
References: <AANLkTinfTAzqtBfZ54V2Y0bkzVt3BVN2QsW4ukJFV0mE@mail.gmail.com>
	<4E0DC567.6070107@pearwood.info>
Message-ID: <4E0DC612.3060605@pearwood.info>

Steven D'Aprano wrote:
> Zubin Mithra wrote:
>> Hey everyone,
>>
>> I was running 2to3 on a particular file and I got the following 
>> traceback(
>> http://paste.pocoo.org/show/223468/).
> 
> For short amounts of text, such as a traceback, please don't use a paste 
> bin, just copy it into your post.


*blinks*

Oh my, that's hilarious.

Sorry folks, nothing to see here... I accidentally clicked on an unread 
email from 2010 (!!!) and thought it had just come in.


-- 
Steven


From steve at pearwood.info  Fri Jul  1 15:13:04 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 01 Jul 2011 23:13:04 +1000
Subject: [Tutor] Limit raw_input to hundredth decimal point
In-Reply-To: <454D5197-386A-41BB-8A58-382E88004A36@me.com>
References: <454D5197-386A-41BB-8A58-382E88004A36@me.com>
Message-ID: <4E0DC7E0.40706@pearwood.info>

Ryan Kirk wrote:
> Is there a way to limit raw_input to the hundredth decimal point?

No. raw_input is a tool that does one thing: it collects input from the 
user. It doesn't understand numbers, check for decimal places, check the 
input for spelling errors, or anything else. It's a hammer, not a 
combination hammer-screwdriver-wrench-drill-saw-axe :)

One solution is to build a new tool that checks for decimal places:


def check(text):
     try:
         x = float(text)
     except ValueError:
         print "please enter a number"
         return None
     y = x*100
     if y - int(y) != 0:
         print "please enter only two decimal places"
         return None
     return x


def get_number(prompt):
     answer = None
     while answer is None:
         text = raw_input(prompt)
         answer = check(text)
     return answer


At first, this seems to work well:

 >>> get_number("Please enter a number with two decimal places: ")
Please enter a number with two decimal places: 77.25
77.25
 >>>

but there's a fundamental problem. The user is entering numbers in 
decimal (base 10), but Python does calculations in binary (base 2), and 
something that has two decimal places may not be exact in binary:

 >>> get_number("Please enter a number with two decimal places: ")
Please enter a number with two decimal places: 77.21
please enter only two decimal places

Huh? 77.21 does have two decimal places. But the closest float to 77.21 
is in fact 77.209999999999994. No computer on Earth can store 77.21 
*exactly* as a binary float, no matter how hard you try!

So, what to do...? You can:

(1) Give up on forcing the user to only enter two decimal places, and 
instead use the round() function to round to two places:

 >>> round(77.2123456, 2)
77.209999999999994

This is still not two decimal places, but it is the closest possible 
float to 7.21, so you can't do any better.

(2) Or give up on using float, and use the decimal module instead. 
(However decimals are slower and less convenient than floats.)

 >>> from decimal import Decimal
 >>> x = Decimal("77.21")
 >>> x
Decimal("77.21")


If you are working with currency, then you should use decimal, and not 
floats.



Good luck!



-- 
Steven


From emile at fenx.com  Fri Jul  1 15:17:20 2011
From: emile at fenx.com (Emile van Sebille)
Date: Fri, 01 Jul 2011 06:17:20 -0700
Subject: [Tutor] Blackjack Betting
In-Reply-To: <BANLkTin=tGos3vhaSPnr5W1C-ufgx_S9Cg@mail.gmail.com>
References: <31966195.post@talk.nabble.com>	<0604E20B5F6F2F4784C9C8C71C5DD4DD2E4E8A78CE@EMARC112VS01.exchad.jpmchase.net>	<31971461.post@talk.nabble.com>
	<BANLkTin=tGos3vhaSPnr5W1C-ufgx_S9Cg@mail.gmail.com>
Message-ID: <iukh9b$djl$1@dough.gmane.org>

On 7/1/2011 12:51 AM Andre Engels said...

> In this case, the error message says:
>
> NameError: global name 'bet' is not defined

Note use of the term global?

>
> That means, at some time at the program, it is told to do something with
> 'bet', but there is no variable bet. And when does that happen? That too
> is told: at line 124, which says:
>
> bet.stash -= bet.wager
>
> Go to that line and read your code yourself - what is this 'bet' of
> which the stash is to be lessened by its wager? Have you told your
> program that this is the value of the variable 'bet'? Where and how?

Further, because global is used, it tells you that 'bet' is not in the 
local scope, nor in the global scope.  Python's general scoping 
resolution rule is local-global-builtin.  So bet, wherever you think it 
may be defined, lives in a different namespace.

See http://docs.python.org/tutorial/classes.html

Emile


From steve at pearwood.info  Fri Jul  1 15:26:07 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 01 Jul 2011 23:26:07 +1000
Subject: [Tutor] problem reading script
In-Reply-To: <201107011015.08328.lisi.reisz@gmail.com>
References: <201107011015.08328.lisi.reisz@gmail.com>
Message-ID: <4E0DCAEF.4050809@pearwood.info>

Lisi wrote:
> I am supposed to be looking at scripts on-line, reading them and making sure 
> that I understand them.  I think taht most of teh things I can't make more 
> than a guess at, are modules taht I don't know, and I can mostly make them 
> out.  But the unpaired double quotation mark, " , in the following has me 
> stumped:
> 
> report['BzrLogTail'] = ''.join(bzr_log_tail)

There is no unpaired double quote mark. Compare:

''  # pairs single quote marks
"   # unpaired double quote mark

If they look the same to you, then you need to increase your font size, 
change to a programmers font, or possible clean your glasses :)


-- 
Steven

From lisi.reisz at gmail.com  Fri Jul  1 16:13:37 2011
From: lisi.reisz at gmail.com (Lisi)
Date: Fri, 1 Jul 2011 15:13:37 +0100
Subject: [Tutor] problem reading script
In-Reply-To: <4E0DCAEF.4050809@pearwood.info>
References: <201107011015.08328.lisi.reisz@gmail.com>
	<4E0DCAEF.4050809@pearwood.info>
Message-ID: <201107011513.37739.lisi.reisz@gmail.com>

On Friday 01 July 2011 14:26:07 Steven D'Aprano wrote:
> If they look the same to you, then you need to increase your font size,
> change to a programmers font, or possible clean your glasses :)

Thanks for the reply, Steven.  

Suggestions for "a programmers font" gratefully received.  I do have problems 
with my sight, and need to have my browser set to a font that I can read.  
But I could copy and paste to a WP and change the font for just that little 
bit.  This particular text seems to work with a serif font.

But it would be useful to know a specific programmer's font for when I am 
having difficulty seeing this particular distinction.  I am used to having to 
look at just one word in a different font to distinguish between I and l 
(which currently look identical to me), where the context doesn't help.

All I have to do now is work out/ look up what '' means!!

Lisi

From g.nius.ck at gmail.com  Fri Jul  1 16:24:06 2011
From: g.nius.ck at gmail.com (Christopher King)
Date: Fri, 1 Jul 2011 10:24:06 -0400
Subject: [Tutor] The Card Game
In-Reply-To: <4E0D2DD1.6040508@pearwood.info>
References: <31961149.post@talk.nabble.com> <iuhg0q$369$1@dough.gmane.org>
	<BANLkTi=n6R090rgCv6_CHzBCRxAWAG1kjw@mail.gmail.com>
	<4E0D2DD1.6040508@pearwood.info>
Message-ID: <BANLkTimKX90a=uo3dq2M=++=7cdbZG=WjA@mail.gmail.com>

Sorry, I haven't upgraded to 3 yet.

On Thursday, June 30, 2011, Steven D'Aprano <steve at pearwood.info> wrote:
> Christopher King wrote:
>
> I would go with __cmp__ which covers them all. 1 for greater, 0 for equal,
> -1 for less than.
>
>
>
> So-called "rich comparisons" using __lt__, __gt__, etc. have been preferred since Python 2.1. The major advantage of them is that they can be used for more complicated data types, e.g. with sets where > means superset and < means subset:
>
>
>>>> a = set([1, 2, 3, 4])
>>>> b = set([2, 3, 4, 5])
>>>>
>>>> a < b ?# a is not a subset of b
> False
>>>> a > b ?# neither is it a superset
> False
>>>> a == b ?# and they're not equal either
> False
>>>> a & b ?# but they do overlap:
> set([2, 3, 4])
>
>
>
> In Python 2.x, __cmp__ is only used as a fall-back if the rich comparisons aren't defined. In Python 3.x, __cmp__ is gone: even if you define it, it won't be used.
>
>
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From lisi.reisz at gmail.com  Fri Jul  1 16:27:33 2011
From: lisi.reisz at gmail.com (Lisi)
Date: Fri, 1 Jul 2011 15:27:33 +0100
Subject: [Tutor] 2to3 conversion
In-Reply-To: <4E0DC612.3060605@pearwood.info>
References: <AANLkTinfTAzqtBfZ54V2Y0bkzVt3BVN2QsW4ukJFV0mE@mail.gmail.com>
	<4E0DC567.6070107@pearwood.info> <4E0DC612.3060605@pearwood.info>
Message-ID: <201107011527.33423.lisi.reisz@gmail.com>

On Friday 01 July 2011 14:05:22 Steven D'Aprano wrote:
> Oh my, that's hilarious.
>
> Sorry folks, nothing to see here... I accidentally clicked on an unread
> email from 2010 (!!!) and thought it had just come in.

I'm glad that my eyes hadn't mislead me that much!!  I was trying to find the 
original.

Lisi

From steve at pearwood.info  Fri Jul  1 18:25:42 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 02 Jul 2011 02:25:42 +1000
Subject: [Tutor] The Card Game
In-Reply-To: <BANLkTimKX90a=uo3dq2M=++=7cdbZG=WjA@mail.gmail.com>
References: <31961149.post@talk.nabble.com>	<iuhg0q$369$1@dough.gmane.org>	<BANLkTi=n6R090rgCv6_CHzBCRxAWAG1kjw@mail.gmail.com>	<4E0D2DD1.6040508@pearwood.info>
	<BANLkTimKX90a=uo3dq2M=++=7cdbZG=WjA@mail.gmail.com>
Message-ID: <4E0DF506.5090005@pearwood.info>

Christopher King wrote:
> Sorry, I haven't upgraded to 3 yet.

No need to apologise for that! Python 2.7 will be around a long time yet.



-- 
Steven

From steve at pearwood.info  Fri Jul  1 18:46:19 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 02 Jul 2011 02:46:19 +1000
Subject: [Tutor] problem reading script
In-Reply-To: <201107011513.37739.lisi.reisz@gmail.com>
References: <201107011015.08328.lisi.reisz@gmail.com>	<4E0DCAEF.4050809@pearwood.info>
	<201107011513.37739.lisi.reisz@gmail.com>
Message-ID: <4E0DF9DB.8050308@pearwood.info>

Lisi wrote:
> On Friday 01 July 2011 14:26:07 Steven D'Aprano wrote:
>> If they look the same to you, then you need to increase your font size,
>> change to a programmers font, or possible clean your glasses :)
> 
> Thanks for the reply, Steven.  
> 
> Suggestions for "a programmers font" gratefully received.

Here are some links I found useful:

http://www.codinghorror.com/blog/2007/10/revisiting-programming-fonts.html
http://damieng.com/blog/2008/05/26/envy-code-r-preview-7-coding-font-released
http://www.kuro5hin.org/story/2004/12/6/11739/5249
http://www.ms-studio.com/FontSales/anonymous.html
http://www.levien.com/type/myfonts/inconsolata.html

This link astonishes me:

http://www.sitepoint.com/top-10-programming-fonts/

How can anyone claim that Arial is a good programming font? Or even a 
good font for on-screen work at all? It has to be said that Arial does 
look reasonably good printed out, but on the low resolution of computer 
monitors, it's garbage. rn and m are virtually indistinguishable in 
Arial, which essentially disqualifies it as a programmer font.


> But it would be useful to know a specific programmer's font for when I am 
> having difficulty seeing this particular distinction.  I am used to having to 
> look at just one word in a different font to distinguish between I and l 
> (which currently look identical to me), where the context doesn't help.
> 
> All I have to do now is work out/ look up what '' means!!

'' is the empty string, the same as "". In Python, single quotes and 
double quotes have the same meaning. That allows you to embed one inside 
the other without escaping:

# Don't do this:
s = "He said, \"Waiter, there is a fly in my soup!\""

# Instead do this:
s = 'He said, "Waiter, there is a fly in my soup!"'



-- 
Steven


From alan.gauld at btinternet.com  Fri Jul  1 19:03:40 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 1 Jul 2011 18:03:40 +0100
Subject: [Tutor] problem reading script
References: <201107011015.08328.lisi.reisz@gmail.com><4E0DCAEF.4050809@pearwood.info>
	<201107011513.37739.lisi.reisz@gmail.com>
Message-ID: <iukulg$4mo$1@dough.gmane.org>


"Lisi" <lisi.reisz at gmail.com> wrote

> Suggestions for "a programmers font" gratefully received.  

I generally use Courier.

Its ugly and old fashioned but it clearly shows 
the differences between i,l, | and 1 and '' and " 
and between ' and ` etc.

and spaces are big enough to "see" clearly. :-)

> But I could copy and paste to a WP 

Never read code in a word processor. Use a 
proper programmer's editor (and there are 
loads, most free, each with its supporters) 
like:  vim, emacs, scite, Eclipse, etc....

Not only will the code be clearer with syntax 
colouring etc but you will have a lot of cursor 
movement and text operations that you don't 
get in a word processor (like commenting 
out a block, or folding/hiding a block inside 
a loop, auto indenting etc, etc)

HTH,


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



From kb1pkl at aim.com  Fri Jul  1 19:56:21 2011
From: kb1pkl at aim.com (Corey Richardson)
Date: Fri, 01 Jul 2011 13:56:21 -0400
Subject: [Tutor] problem reading script
In-Reply-To: <iukulg$4mo$1@dough.gmane.org>
References: <201107011015.08328.lisi.reisz@gmail.com>
	<4E0DCAEF.4050809@pearwood.info>
	<201107011513.37739.lisi.reisz@gmail.com>
	<iukulg$4mo$1@dough.gmane.org>
Message-ID: <1309542782-sup-7200@dalek>

Excerpts from Alan Gauld's message of Fri Jul 01 13:03:40 -0400 2011:
> 
> "Lisi" <lisi.reisz at gmail.com> wrote
> 
> > Suggestions for "a programmers font" gratefully received.  
> 
> I generally use Courier.
> 
> Its ugly and old fashioned but it clearly shows 
> the differences between i,l, | and 1 and '' and " 
> and between ' and ` etc.
> 

I use and love inconsolata[0], it's a great font for programming,
and looks great as well (both on screen and off).

[0] - http://www.levien.com/type/myfonts/inconsolata.html
-- 
Corey Richardson
  "Those who deny freedom to others, deserve it not for themselves"
     -- Abraham Lincoln

From steve at alchemy.com  Fri Jul  1 20:05:02 2011
From: steve at alchemy.com (Steve Willoughby)
Date: Fri, 01 Jul 2011 11:05:02 -0700
Subject: [Tutor] problem reading script
In-Reply-To: <1309542782-sup-7200@dalek>
References: <201107011015.08328.lisi.reisz@gmail.com>	<4E0DCAEF.4050809@pearwood.info>	<201107011513.37739.lisi.reisz@gmail.com>	<iukulg$4mo$1@dough.gmane.org>
	<1309542782-sup-7200@dalek>
Message-ID: <4E0E0C4E.1020000@alchemy.com>

On 01-Jul-11 10:56, Corey Richardson wrote:
> Excerpts from Alan Gauld's message of Fri Jul 01 13:03:40 -0400 2011:
> I use and love inconsolata[0], it's a great font for programming,
> and looks great as well (both on screen and off).

I like inconsolata and Envy Code R, although just to be weird I tried 
using an old OCR font and kind of got to like that too.  A little weird 
but the glyphs are certainly distinct :)

-- 
Steve Willoughby / steve at alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C

From lisi.reisz at gmail.com  Fri Jul  1 23:22:31 2011
From: lisi.reisz at gmail.com (Lisi)
Date: Fri, 1 Jul 2011 22:22:31 +0100
Subject: [Tutor] Thank you.  Was: Re:  problem reading script
In-Reply-To: <201107011021.06004.lisi.reisz@gmail.com>
References: <201107011015.08328.lisi.reisz@gmail.com>
	<201107011021.06004.lisi.reisz@gmail.com>
Message-ID: <201107012222.31179.lisi.reisz@gmail.com>

Thank you all for such a lot of very helpful replies.  I have been looking 
through the recommended fonts and am pleasantly surprised by how clear, 
legible and well differentiated some of them are.

I have been using Bitstream Vera Sans Mono in KWrite, which gives me all the 
colours and spacing and is very easy to read, but Bitstream Vera Sans Mono, 
like Bitstream Vera Sans itself, does not distinguish well between I and l, 
nor between '' and " (which are in fact different, but the difference is 
noticeable only if you juxtapose them).

I have already installed Inconsolata because there turned out to be a Debian 
package for it, so it took less than a minute to search for it - yes, it was 
there - and install it.  And I have set KWrite to use it.

Sadly, I am tied up all day tomorrow (it is late on Friday here) so I'll look 
into the other fonts on Sunday and work through the rest of your advice.

I might even end up being able to code in Python - but if I do it will be 
because you have all hauled me over the fences.

Lisi

From vincentbalmori at yahoo.com  Sat Jul  2 00:32:10 2011
From: vincentbalmori at yahoo.com (Vincent Balmori)
Date: Fri, 1 Jul 2011 15:32:10 -0700 (PDT)
Subject: [Tutor] Blackjack Betting
In-Reply-To: <iukh9b$djl$1@dough.gmane.org>
References: <31966195.post@talk.nabble.com>
	<0604E20B5F6F2F4784C9C8C71C5DD4DD2E4E8A78CE@EMARC112VS01.exchad.jpmchase.net>
	<31971461.post@talk.nabble.com>
	<BANLkTin=tGos3vhaSPnr5W1C-ufgx_S9Cg@mail.gmail.com>
	<iukh9b$djl$1@dough.gmane.org>
Message-ID: <31977263.post@talk.nabble.com>


I was able to get the program started without errors now. What is left now is
to: 

Having the stash change after winning and losing. No matter what, the value
in stash stays the same. The conditional statement I made which prevents
players with no money from playing is dependent on this.

After each game when I choose to play again, the betting options do not come
up again before the cards are drawn.

Apply the betting option to more than one player the same way each player
can choose to hit. I think the key involves modifying the init function in
class BJ_Game, where it adds the number of players and names.

http://old.nabble.com/file/p31977263/blackjackbetting.py blackjackbetting.py 




Emile van Sebille wrote:
> 
> On 7/1/2011 12:51 AM Andre Engels said...
> 
>> In this case, the error message says:
>>
>> NameError: global name 'bet' is not defined
> 
> Note use of the term global?
> 
>>
>> That means, at some time at the program, it is told to do something with
>> 'bet', but there is no variable bet. And when does that happen? That too
>> is told: at line 124, which says:
>>
>> bet.stash -= bet.wager
>>
>> Go to that line and read your code yourself - what is this 'bet' of
>> which the stash is to be lessened by its wager? Have you told your
>> program that this is the value of the variable 'bet'? Where and how?
> 
> Further, because global is used, it tells you that 'bet' is not in the 
> local scope, nor in the global scope.  Python's general scoping 
> resolution rule is local-global-builtin.  So bet, wherever you think it 
> may be defined, lives in a different namespace.
> 
> See http://docs.python.org/tutorial/classes.html
> 
> Emile
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
View this message in context: http://old.nabble.com/Blackjack-Betting-tp31966195p31977263.html
Sent from the Python - tutor mailing list archive at Nabble.com.


From vincentbalmori at yahoo.com  Sat Jul  2 00:39:08 2011
From: vincentbalmori at yahoo.com (Vincent Balmori)
Date: Fri, 1 Jul 2011 15:39:08 -0700 (PDT)
Subject: [Tutor] Blackjack Betting
In-Reply-To: <iukh9b$djl$1@dough.gmane.org>
References: <31966195.post@talk.nabble.com>
	<0604E20B5F6F2F4784C9C8C71C5DD4DD2E4E8A78CE@EMARC112VS01.exchad.jpmchase.net>
	<31971461.post@talk.nabble.com>
	<BANLkTin=tGos3vhaSPnr5W1C-ufgx_S9Cg@mail.gmail.com>
	<iukh9b$djl$1@dough.gmane.org>
Message-ID: <31977301.post@talk.nabble.com>


Also I must be doing something wrong if I have to enter a "bet = Bet()" into
each function where it is used. I tried putting Bet into the other classes'
arguments but it did not have any effect.


Emile van Sebille wrote:
> 
> On 7/1/2011 12:51 AM Andre Engels said...
> 
>> In this case, the error message says:
>>
>> NameError: global name 'bet' is not defined
> 
> Note use of the term global?
> 
>>
>> That means, at some time at the program, it is told to do something with
>> 'bet', but there is no variable bet. And when does that happen? That too
>> is told: at line 124, which says:
>>
>> bet.stash -= bet.wager
>>
>> Go to that line and read your code yourself - what is this 'bet' of
>> which the stash is to be lessened by its wager? Have you told your
>> program that this is the value of the variable 'bet'? Where and how?
> 
> Further, because global is used, it tells you that 'bet' is not in the 
> local scope, nor in the global scope.  Python's general scoping 
> resolution rule is local-global-builtin.  So bet, wherever you think it 
> may be defined, lives in a different namespace.
> 
> See http://docs.python.org/tutorial/classes.html
> 
> Emile
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
View this message in context: http://old.nabble.com/Blackjack-Betting-tp31966195p31977301.html
Sent from the Python - tutor mailing list archive at Nabble.com.


From merrickdav at gmail.com  Sat Jul  2 04:11:57 2011
From: merrickdav at gmail.com (David Merrick)
Date: Sat, 2 Jul 2011 14:11:57 +1200
Subject: [Tutor] (no subject)
Message-ID: <CA+=McKZRHBwKEoqDSyRa2JsU=+ZTe=FY466_QKvHBeaqRaiR0w@mail.gmail.com>

# Blackjack
# From 1 to 7 players compete against a dealer

import cards, games

class BJ_Card(cards.Card):
    """ A Blackjack Card. """
    ACE_VALUE = 1

    @property
    def value(self):
        if self.is_face_up:
            v = BJ_Card.RANKS.index(self.rank) + 1
            if v > 10:
                v = 10
        else:
            v = None
        return v

class BJ_Deck(cards.Deck):
    """ A Blackjack Deck. """
    def populate(self):
        for suit in BJ_Card.SUITS:
            for rank in BJ_Card.RANKS:
                self.cards.append(BJ_Card(rank, suit))


class BJ_Hand(cards.Hand):
    """ A Blackjack Hand. """
    def __init__(self, name):
        super(BJ_Hand, self).__init__()
        self.name = name

    def __str__(self):
        rep = self.name + ":\t" + super(BJ_Hand, self).__str__()
        if self.total:
            rep += "(" + str(self.total) + ")"
        return rep

    @property
    def total(self):
        # if a card in the hand has value of None, then total is None
        for card in self.cards:
            if not card.value:
                return None

        # add up card values, treat each Ace as 1
        t = 0
        for card in self.cards:
              t += card.value

        # determine if hand contains an Ace
        contains_ace = False
        for card in self.cards:
            if card.value == BJ_Card.ACE_VALUE:
                contains_ace = True

        # if hand contains Ace and total is low enough, treat Ace as 11
        if contains_ace and t <= 11:
            # add only 10 since we've already added 1 for the Ace
            t += 10

        return t

    def is_busted(self):
        return self.total > 21

class Bet(object):
    """ A Blackjack Gamble. """
    # Values
    def __init__(bet, money = 10):
        stash  = money

    # Betting options
    def betting(bet,stash):
        try:
            if stash > 0:
                wager = int(input("\nHow much do you want to wager?: "))
                if wager > bet.stash:
                    int(input("\n You can only wager what you have. How
much?: "))
                elif wager < 0:
                    int(input("\n You can only wager what you have. How
much?: "))
        except ValueError:
                int(input("\n That's not valid! Choose a number: "))

    # Money Conditions
    def gamble(bet):
        if bet.stash <= 0:
            print("\nYou are out of money! You're out of the game!")


class BJ_Player(BJ_Hand):
    """ A Blackjack Player. """
    def is_hitting(self):
        response = games.ask_yes_no("\n" + self.name + ", do you want a hit?
(Y/N): ")
        return response == "y"

    def bust(self):
        print(self.name, "busts.")
        self.lose()

    def lose(self):
        print(self.name, "loses.")
        betting = Bet()
        stash = stash - wager
        print(stash)

    def win(self):
        print(self.name, "wins.")
        bet = Bet()
        stash += wager
        print(stash)

    def push(self):
        print(self.name, "pushes.")


class BJ_Dealer(BJ_Hand):
    """ A Blackjack Dealer. """
    def is_hitting(self):
        return self.total < 17

    def bust(self):
        print(self.name, "busts.")

    def flip_first_card(self):
        first_card = self.cards[0]
        first_card.flip()


class BJ_Game(object):
    """ A Blackjack Game. """
    def __init__(self, names):
        self.players = []
        for name in names:
            player = BJ_Player(name)
            self.players.append(player)

        self.dealer = BJ_Dealer("Dealer")

        self.deck = BJ_Deck()
        self.deck.populate()
        self.deck.shuffle()

        bet = 0
        bet = Bet()
        bet.betting(stash)

    @property
    def still_playing(self):
        sp = []
        for player in self.players:
            if not player.is_busted():
                sp.append(player)
        return sp

    def __additional_cards(self, player):
        while not player.is_busted() and player.is_hitting():
            self.deck.deal([player])
            print(player)
            if player.is_busted():
                player.bust()

    def play(self):
        # deal initial 2 cards to everyone
        self.deck.deal(self.players + [self.dealer], per_hand = 2)
        self.dealer.flip_first_card()    # hide dealer's first card
        for player in self.players:
            print(player)
        print(self.dealer)

        # deal additional cards to players
        for player in self.players:
            self.__additional_cards(player)

        self.dealer.flip_first_card()    # reveal dealer's first

        if not self.still_playing:
            # since all players have busted, just show the dealer's hand
            print(self.dealer)
        else:
            # deal additional cards to dealer
            print(self.dealer)
            self.__additional_cards(self.dealer)

            if self.dealer.is_busted():
                # everyone still playing wins
                for player in self.still_playing:
                    player.win()
            else:
                # compare each player still playing to dealer
                for player in self.still_playing:
                    if player.total > self.dealer.total:
                        player.win()
                    elif player.total < self.dealer.total:
                        player.lose()
                    else:
                        player.push()

        # remove everyone's cards
        for player in self.players:
            player.clear()
        self.dealer.clear()


def main():
    print("\t\tWelcome to Blackjack!\n")
    stash = 0
    names = []
    number = games.ask_number("How many players? (1 - 7): ", low = 1, high =
8)
    for i in range(number):
        name = input("Enter player name: ")
        names.append(name)
    print()

    game = BJ_Game(names)

    again = None
    while again != "n":
        game.play()
        again = games.ask_yes_no("\nDo you want to play again?: ")


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

*output*

Traceback (most recent call last):
  File "I:/Python/programs/blackjackBetting.py", line 224, in <module>
    main()
  File "I:/Python/programs/blackjackBetting.py", line 216, in main
    game = BJ_Game(names)
  File "I:/Python/programs/blackjackBetting.py", line 147, in __init__
    bet.betting(stash)
NameError: global name 'stash' is not defined

-- 
Dave Merrick

merrickdav at gmail.com

Ph   03 3423 121
Cell 027 3089 169
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110702/b8e28f4f/attachment-0001.html>

From ryankirk at me.com  Sat Jul  2 08:51:14 2011
From: ryankirk at me.com (Ryan Kirk)
Date: Fri, 01 Jul 2011 23:51:14 -0700
Subject: [Tutor] Limit raw_input to hundredth decimal point
In-Reply-To: <4E0DC7E0.40706@pearwood.info>
References: <454D5197-386A-41BB-8A58-382E88004A36@me.com>
	<4E0DC7E0.40706@pearwood.info>
Message-ID: <A1FFC41F-FE3F-47C0-86A7-BAD3CF2E369D@me.com>

Thanks all! This helps a lot.

On Jul 1, 2011, at 6:13 AM, Steven D'Aprano wrote:

> Ryan Kirk wrote:
>> Is there a way to limit raw_input to the hundredth decimal point?
> 
> No. raw_input is a tool that does one thing: it collects input from the user. It doesn't understand numbers, check for decimal places, check the input for spelling errors, or anything else. It's a hammer, not a combination hammer-screwdriver-wrench-drill-saw-axe :)
> 
> One solution is to build a new tool that checks for decimal places:
> 
> 
> def check(text):
>    try:
>        x = float(text)
>    except ValueError:
>        print "please enter a number"
>        return None
>    y = x*100
>    if y - int(y) != 0:
>        print "please enter only two decimal places"
>        return None
>    return x
> 
> 
> def get_number(prompt):
>    answer = None
>    while answer is None:
>        text = raw_input(prompt)
>        answer = check(text)
>    return answer
> 
> 
> At first, this seems to work well:
> 
> >>> get_number("Please enter a number with two decimal places: ")
> Please enter a number with two decimal places: 77.25
> 77.25
> >>>
> 
> but there's a fundamental problem. The user is entering numbers in decimal (base 10), but Python does calculations in binary (base 2), and something that has two decimal places may not be exact in binary:
> 
> >>> get_number("Please enter a number with two decimal places: ")
> Please enter a number with two decimal places: 77.21
> please enter only two decimal places
> 
> Huh? 77.21 does have two decimal places. But the closest float to 77.21 is in fact 77.209999999999994. No computer on Earth can store 77.21 *exactly* as a binary float, no matter how hard you try!
> 
> So, what to do...? You can:
> 
> (1) Give up on forcing the user to only enter two decimal places, and instead use the round() function to round to two places:
> 
> >>> round(77.2123456, 2)
> 77.209999999999994
> 
> This is still not two decimal places, but it is the closest possible float to 7.21, so you can't do any better.
> 
> (2) Or give up on using float, and use the decimal module instead. (However decimals are slower and less convenient than floats.)
> 
> >>> from decimal import Decimal
> >>> x = Decimal("77.21")
> >>> x
> Decimal("77.21")
> 
> 
> If you are working with currency, then you should use decimal, and not floats.
> 
> 
> 
> Good luck!
> 
> 
> 
> -- 
> Steven
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From marc.tompkins at gmail.com  Sat Jul  2 10:18:15 2011
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Sat, 2 Jul 2011 01:18:15 -0700
Subject: [Tutor] (no subject)
In-Reply-To: <CA+=McKZRHBwKEoqDSyRa2JsU=+ZTe=FY466_QKvHBeaqRaiR0w@mail.gmail.com>
References: <CA+=McKZRHBwKEoqDSyRa2JsU=+ZTe=FY466_QKvHBeaqRaiR0w@mail.gmail.com>
Message-ID: <CAKK8jXYJHb673iutKu7Ltw0He6z6hfK98K-TUYLqL5x6csHkjg@mail.gmail.com>

On Fri, Jul 1, 2011 at 7:11 PM, David Merrick <merrickdav at gmail.com> wrote:

> NameError: global name 'stash' is not defined
>
>
There are a _lot_ of missing pieces here; I think you started writing code
without a plan of how your game would actually run.  The current error is
only the first you're going to run into here...  That being said, we might
as well fix the first one.

You either have several problems here, or just one; I'm going to go for the
"just one" option: I'm going to assume that you actually want "stash" to be
an attribute of a Bet object - I think that it should be an attribute of
each player, not of their individual bets, but that's another issue.

The only time you can refer to a variable without qualifying it is from
within the same block of code.  Otherwise, the interpreter has to guess
which context (also known as "scope") the variable is supposed to belong to,
and the interpreter refuses to guess.  The error you're getting boils down
to "You referred to a variable called 'stash', but since you didn't define
it in the local scope, I assume it's a global variable - but you didn't
define it there either!  What gives?"

In Bet.__init__(), you have

>     stash = money
>
This makes "stash" a local variable in the scope of __init__(), and as soon
as __init__() terminates, so does "stash".
What you want is:

>     self.stash = money
>
This makes "stash" an attribute of Bet.

To refer to "stash" from inside the Bet object, you need to refer to it as
"self.stash"; from outside, after you've created a Bet object ("bet =
Bet()") you need to refer to it as "bet.stash".

One more thing: you define Bet.__init__() as taking two parameters, "bet"
and "money"; you make "money" optional by defaulting it to 10, but "bet" has
no default, so if your program ever got around to executing "bet = Bet()" it
would blow up because of a missing parameter.

Also, your use of variable names is confusing.  "bet = Bet()" is OK, but
ALSO having "bet" as a parameter to Bet.__init__()?  Python won't be
confused, but I bet you will be - I know I am.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110702/de147473/attachment.html>

From alan.gauld at btinternet.com  Sat Jul  2 10:33:39 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 2 Jul 2011 09:33:39 +0100
Subject: [Tutor] Blackjack 2 - was Re: (no subject)
References: <CA+=McKZRHBwKEoqDSyRa2JsU=+ZTe=FY466_QKvHBeaqRaiR0w@mail.gmail.com>
Message-ID: <iuml57$a5f$1@dough.gmane.org>

Please provide a meaningful subject!

"David Merrick" <merrickdav at gmail.com> wrote ># Blackjack

> class BJ_Game(object):
>    """ A Blackjack Game. """
>    def __init__(self, names):
>        self.players = []
>        for name in names:
>            player = BJ_Player(name)
>            self.players.append(player)
>
>        self.dealer = BJ_Dealer("Dealer")
>
>        self.deck = BJ_Deck()
>        self.deck.populate()
>        self.deck.shuffle()
>
>        bet = 0
>        bet = Bet()
>        bet.betting(stash)


> def main():
>    print("\t\tWelcome to Blackjack!\n")
>    stash = 0
>    names = []
>    number = games.ask_number("How many players? (1 - 7): ", low = 1, 
> high > .....
>
>    game = BJ_Game(names)

>  File "I:/Python/programs/blackjackBetting.py", line 224, in 
> <module>
>    main()
>  File "I:/Python/programs/blackjackBetting.py", line 216, in main
>    game = BJ_Game(names)
>  File "I:/Python/programs/blackjackBetting.py", line 147, in 
> __init__
>    bet.betting(stash)
> NameError: global name 'stash' is not defined

It says stash is not defined. That means there is no
variable named stash visible to Python inside the
init method of BJ_Game.

The only stash defined is in the main function.
variables defined inside a function (including main()
are *only* visible within that function, nowhere else.

But you have lots of missing names all over.
I suggest you review yuour code before trying
to run it, otherwise you will be seeing a lot of
these error messages.

You will fund information about naming and scope
in the "Whats in a name?" topic of my tutorial.

HTH,

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



From fomcl at yahoo.com  Sat Jul  2 11:49:45 2011
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Sat, 2 Jul 2011 02:49:45 -0700 (PDT)
Subject: [Tutor] Cython question
Message-ID: <1309600185.29355.YahooMailRC@web110707.mail.gq1.yahoo.com>

Hi,

Some time ago I finished a sav reader for Spss .sav data files (also with the 
help of some of you!):
http://code.activestate.com/recipes/577650-python-reader-for-spss-sav-files/

It works fine, but it is not fast with big files. I am thinking of implementing 
two of the functions in cython (getValueChar and getValueNum).
As far as I understood it requires the functions to be re-written in a 
Python-like langauge, 'minus the memory manager'. That little piece of code is 
converted to C and subsequently compiled to a .dll or .so file. The original 
program listens and talks to that .dll file. A couple of questions:
-is this a correct representation of things?
-will the speed improvement be worthwhile? (pros)
-are there reasons not to try this? (cons)
-is it 'sane' to mix ctypes and cython for nonintensive and intensive 
operations, respectively?

Thanks in advance!

Cheers!!
Albert-Jan


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public 
order, irrigation, roads, a fresh water system, and public health, what have the 
Romans ever done for us?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110702/4b530f71/attachment.html>

From stefan_ml at behnel.de  Sat Jul  2 13:29:31 2011
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Sat, 02 Jul 2011 13:29:31 +0200
Subject: [Tutor] Cython question
In-Reply-To: <1309600185.29355.YahooMailRC@web110707.mail.gq1.yahoo.com>
References: <1309600185.29355.YahooMailRC@web110707.mail.gq1.yahoo.com>
Message-ID: <iumves$pnu$1@dough.gmane.org>

Albert-Jan Roskam, 02.07.2011 11:49:
> Some time ago I finished a sav reader for Spss .sav data files (also with the
> help of some of you!):
> http://code.activestate.com/recipes/577650-python-reader-for-spss-sav-files/
>
> It works fine, but it is not fast with big files. I am thinking of implementing
> two of the functions in cython (getValueChar and getValueNum).
> As far as I understood it requires the functions to be re-written in a
> Python-like langauge

"rewritten" only in the sense that you may want to apply optimisations or 
provide type hints. Cython is Python, but with language extensions that 
allow the compiler to apply static optimisations to your code.


>, 'minus the memory manager'.

Erm, not sure what you mean here. Cython uses the same memory management as 
CPython.


> That little piece of code is
> converted to C and subsequently compiled to a .dll or .so file. The original
> program listens and talks to that .dll file. A couple of questions:
> -is this a correct representation of things?

More or less. Instead of "listens and talks", I'd rather say "uses". What 
you get is just another Python extension module which you can use like any 
other Python module.


> -will the speed improvement be worthwhile? (pros)

Depends. If your code is I/O bound, then likely not. If the above two 
functions are true CPU bottlenecks that do some kind of calculation or data 
transformation, it's likely going to be faster in Cython.


> -are there reasons not to try this? (cons)

If your performance problem is not CPU related, it may not be worth it.


> -is it 'sane' to mix ctypes and cython for nonintensive and intensive
> operations, respectively?

Why would you want to use ctypes if you can use Cython?

Stefan


From alan.gauld at btinternet.com  Sat Jul  2 13:40:00 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 2 Jul 2011 12:40:00 +0100
Subject: [Tutor] Cython question
References: <1309600185.29355.YahooMailRC@web110707.mail.gq1.yahoo.com>
Message-ID: <iun02l$shh$1@dough.gmane.org>

"Albert-Jan Roskam" <fomcl at yahoo.com> wrote

> As far as I understood it requires the functions to be re-written in 
> a
> Python-like langauge, 'minus the memory manager'.

Thats what I understand too, but I've only read the web docs :-)

> converted to C and subsequently compiled to a .dll or .so file.
> The original program listens and talks to that .dll file.

I believe it effectively becomes a module that you
import like any other.

> -will the speed improvement be worthwhile? (pros)

That depends on the structure of your code.

Profile it first to prove that the functions you are
optimising are in fact the places where the bulk
of the time is spent.

Then check that those functions aren't spending
their time calling C functions already. If all you have
is a loop calling a fubction that is already in C then
cython is unlikely to give huge improvement. But
if you have a lot of python code doing real
processing then yes cython (or similar) should
make a significant difference (ie up to say, 10 times
faster)

> -are there reasons not to try this? (cons)

If you optimise the wrong bits you might just waste
your time and it will make future maintenance
more difficult because you have two environments
to support.  Have you tried optimising the Python
code first?

> -is it 'sane' to mix ctypes and cython for nonintensive
> and intensive operations, respectively?

In the same app yes, in the same function I'd guess
probably not. But I'll let others with more experience
of using both comment.

But bear in mind I've only read the cython docs,
not actually used it...

HTH,

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



From wprins at gmail.com  Sat Jul  2 13:47:00 2011
From: wprins at gmail.com (Walter Prins)
Date: Sat, 2 Jul 2011 12:47:00 +0100
Subject: [Tutor] Blackjack problem
Message-ID: <CANLXbfDgzabhov_WYN7p75THHzQhEdBR8r8FJgpLMY35bq2eag@mail.gmail.com>

Hi David (and Vincent, as I think you may be interested in this as well),

On 2 July 2011 03:11, David Merrick <merrickdav at gmail.com> wrote:

> # Blackjack
> # From 1 to 7 players compete against a dealer
>

I came accross this book (
http://homepage.mac.com/s_lott/books/oodesign/build-python/html/index.html )
on the internet today, which I submit may be helpful in your journey of
learning.  It specifically covers building object oriented design type
skills (as opposed to learning Python or programming as such) and also has
as subject matter the game of Blackjack (amongst several others.)   The
author also has 2 other books, one specifically for learning the basics of
Python the language and another for learning the basics of programming in
general, which may also be helpful.

Anyway, hope that helps,

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110702/b19fd3e0/attachment.html>

From fomcl at yahoo.com  Sat Jul  2 14:47:01 2011
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Sat, 2 Jul 2011 05:47:01 -0700 (PDT)
Subject: [Tutor] Cython question
In-Reply-To: <iumves$pnu$1@dough.gmane.org>
Message-ID: <1309610821.78852.YahooMailClassic@web110701.mail.gq1.yahoo.com>

Hi Stefan, Alan, Matt,

Thanks for your replies. 

I used cProfile to find the bottlenecks, the two Python functions getValueChar and getValueNum. These two Python functions simply call two equivalent C functions in a .dll (using ctypes). The problem is that these functions are called as many times as there are VALUES in a file (e.g. 1000 records * 100 columns = 100000 function calls). So if I understand you correctly, this is not Cpu bound and, therefore, alas, Cython won't improve the excution time. Correct?

That .dll contains many more functions, for example to extract certain header information (a list of all the spss variables, etc.). Getting this kind of information is only done once per spss file. So, to answer your question, Stefan, I'd like this part of the code to remain the same, ie. with ctypes. Nothing much to win anyway, with just one function call per data file.

Cython might be useful when the program is converting spss date/times (seconds since gregorian epoch) to iso-date/times. If I understand it correctly, this is certainly cpu bound.

Btw, Matt, I indeed used psyco already, although I never precisely quantified the improvement in speed.
?
Cheers!!

Albert-Jan



~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

--- On Sat, 7/2/11, Stefan Behnel <stefan_ml at behnel.de> wrote:

From: Stefan Behnel <stefan_ml at behnel.de>
Subject: Re: [Tutor] Cython question
To: tutor at python.org
Date: Saturday, July 2, 2011, 1:29 PM

Albert-Jan Roskam, 02.07.2011 11:49:
> Some time ago I finished a sav reader for Spss .sav data files (also with the
> help of some of you!):
> http://code.activestate.com/recipes/577650-python-reader-for-spss-sav-files/
> 
> It works fine, but it is not fast with big files. I am thinking of implementing
> two of the functions in cython (getValueChar and getValueNum).
> As far as I understood it requires the functions to be re-written in a
> Python-like langauge

"rewritten" only in the sense that you may want to apply optimisations or provide type hints. Cython is Python, but with language extensions that allow the compiler to apply static optimisations to your code.


> , 'minus the memory manager'.

Erm, not sure what you mean here. Cython uses the same memory management as CPython.


> That little piece of code is
> converted to C and subsequently compiled to a .dll or .so file. The original
> program listens and talks to that .dll file. A couple of questions:
> -is this a correct representation of things?

More or less. Instead of "listens and talks", I'd rather say "uses". What you get is just another Python extension module which you can use like any other Python module.


> -will the speed improvement be worthwhile? (pros)

Depends. If your code is I/O bound, then likely not. If the above two functions are true CPU bottlenecks that do some kind of calculation or data transformation, it's likely going to be faster in Cython.


> -are there reasons not to try this? (cons)

If your performance problem is not CPU related, it may not be worth it.


> -is it 'sane' to mix ctypes and cython for nonintensive and intensive
> operations, respectively?

Why would you want to use ctypes if you can use Cython?

Stefan

_______________________________________________
Tutor maillist? -? Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110702/3cab4c38/attachment-0001.html>

From m.preetam93 at gmail.com  Sat Jul  2 15:16:06 2011
From: m.preetam93 at gmail.com (preetam shivaram)
Date: Sat, 2 Jul 2011 18:46:06 +0530
Subject: [Tutor] problem with reading dns query
Message-ID: <CAM8AQFg+pERpuCgECKLP64OxrZGOcP8sdJbivDc4Wf9Xop6xog@mail.gmail.com>

I have got a very simple idea in mind that i want to try out. Say i have a
browser, chrome for instance, and i want to search for the ip of the domain
name, say `www.google.com`. I use windows 7 and i have set the dns lookup
properties to manual and have given the address `127.0.0.1` where my server
(written in Python) is running. I started my server and i could see the dns
query like this:

    WAITING FOR CONNECTION.........

    .........recieved from :  ('127.0.0.1', 59339)

"'~\\x17\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x03www\\x06google\\x02co\\x02in\\x00\\x00\\x01\\x00\\x01'"

The `waiting for connection` and the `received from` is from my server. How
do i get a breakdown form(a human readable form) of this message??



This is my server code(quiet elementary but still):


Here is the code:

    from time import sleep
    import socket
    host=''
    port=53
    addr_list=(host,port)
    buf_siz=1024
    udp=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    udp.bind(addr_list)
    while True:
        print 'WAITING FOR CONNECTION.........'
        data,addr = udp.recvfrom(buf_siz) print '.........recieved from :
',addr
        sleep(3)
        print repr(data)

is there any better way to get the dns request fro my browser first ,extract
the domain name and then send it to a name server that i wish all in python
? if here is pl explain it without any third party modules i wouldn mind
re-inventing the wheel as long as i can learn all python concepts properly

Thanking you in advance!!!

Yours thankfully,
Preetam
(A python freak)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110702/2ae59eb3/attachment.html>

From alan.gauld at btinternet.com  Sat Jul  2 15:28:14 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 2 Jul 2011 14:28:14 +0100
Subject: [Tutor] Cython question
References: <iumves$pnu$1@dough.gmane.org>
	<1309610821.78852.YahooMailClassic@web110701.mail.gq1.yahoo.com>
Message-ID: <iun6dj$rbg$1@dough.gmane.org>

"Albert-Jan Roskam" <fomcl at yahoo.com> wrote 

> I used cProfile to find the bottlenecks, the two 
> Python functions getValueChar and getValueNum. 
> These two Python functions simply call two equivalent 
> C functions in a .dll (using ctypes). 

In that case cythin will speed up the calling loops 
but it can't do anything to speed up the DLL calls, 
you have effectively already optimised those 
functions by calling the DLL.

> The problem is that these functions are called 
> as many times as there are VALUES in a file 

It might be worth a try if you have very big data sets
because a C loop is faster than a Python loop. 
But don't expect order of magnitude improvements.

> So if I understand you correctly, this is not Cpu 
> bound and, therefore, alas, Cython won't improve 
> the excution time. Correct?

It may still be CPU bound in that the CPU is doing 
all the work, but if the CPU time is in the DLL 
functions rather than in the loop cython won't 
help much.

CPU bound refers to the type of processing - is 
it lots of logic, math, control flows etc? Or is 
it I/O bound - reading network, disk, or user input?
Or it might be memory bound - creating lots of 
in memory objects (especially if that results in 
paging to disk, when it becomes I/O bound too!)

Knowing what is causing the bottleneck will 
determine how to improve things. Use tools like
TaskManager in Windows or top in *nix to see 
where the time is going and what resources are 
being consumed. Fast code is not always the 
answer.

HTH,

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



From alan.gauld at btinternet.com  Sat Jul  2 15:38:03 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 2 Jul 2011 14:38:03 +0100
Subject: [Tutor] problem with reading dns query
References: <CAM8AQFg+pERpuCgECKLP64OxrZGOcP8sdJbivDc4Wf9Xop6xog@mail.gmail.com>
Message-ID: <iun700$ttp$1@dough.gmane.org>


"preetam shivaram" <m.preetam93 at gmail.com> wrote

> browser, chrome for instance, and i want to search for 
> the ip of the domain name, say `www.google.com`. 

I'm curious why you would want to?
Given the volatility of IP addresses in the modern 
network I'm not sure what good it would do you? 
(as opposed to doing it manually using standard 
networking tools like ping, traceroute etc)

> `127.0.0.1` where my server (written in Python) 
> is running. 

localhost is not usually a good place to test 
networking tools. Even if you used a local 
LAN IP address allocated via DHCP it would 
be slightly more realistic.

> is there any better way to get the dns request 
> fro my browser first ,extract  the domain name 
> and then send it to a name server that i wish 
> all in python

You could set your local DNS settings to your 
local server. But if you want to reroute DNS I 
suspect there are esierways. But I'm still not 
clear about what you really want to do here, 
or why?

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



From stefan_ml at behnel.de  Sat Jul  2 16:52:08 2011
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Sat, 02 Jul 2011 16:52:08 +0200
Subject: [Tutor] Cython question
In-Reply-To: <iun6dj$rbg$1@dough.gmane.org>
References: <iumves$pnu$1@dough.gmane.org>	<1309610821.78852.YahooMailClassic@web110701.mail.gq1.yahoo.com>
	<iun6dj$rbg$1@dough.gmane.org>
Message-ID: <iunbao$jjt$1@dough.gmane.org>

Alan Gauld, 02.07.2011 15:28:
> "Albert-Jan Roskam" wrote
>> I used cProfile to find the bottlenecks, the two Python functions
>> getValueChar and getValueNum. These two Python functions simply call two
>> equivalent C functions in a .dll (using ctypes).

The code is currently declared as Windows-only and I don't know any good 
C-level profiling code for that platform. Under Linux, once I'm sure I have 
a CPU bound problem below the Python level, I'd use valgrind and 
KCacheGrind to analyse the performance. That will include all C function 
calls (and even CPU instructions, if you want) in the call trace. Makes it 
a bit less obvious to see what Python is doing, but leads to much more 
detailed results at the C level.

It's also worth keeping in mind that all profiling attempts *always* 
interfere with the normal program execution. The results you get during a 
profiling run may not be what you'd get with profiling disabled. So, 
profiling is nice, but it doesn't replace proper benchmarking.


> In that case cythin will speed up the calling loops but it can't do
> anything to speed up the DLL calls, you have effectively already optimised
> those functions by calling the DLL.
>
>> The problem is that these functions are called as many times as there are
>> VALUES in a file
>
> It might be worth a try if you have very big data sets
> because a C loop is faster than a Python loop. But don't expect order of
> magnitude improvements.

Looking at the code now, it's actually worse than that. The C function call 
does not only go through ctypes, but is additionally wrapped in a method 
call. So the OP is paying the call overhead twice for each field, plus the 
method lookup and some other operations. These things can add up quite easily.

So, iff the conversion code is really a CPU bottleneck, and depending on 
how much work the C functions actually do, the current call overhead, 100 
times per record, may be a substantial part of the game. It's worth seeing 
if it can be dropped at the Python level by removing method lookup and call 
levels (i.e. by inlining the method), but if that's not enough, Cython may 
still be worth it. For one, Cython's call overhead is lower than that of 
ctypes, and if the call is only done once, and the loop is moved into 
Cython (i.e. C) entirely, the overhead will also drop substantially.

It might also be worth running the code in PyPy instead of CPython. PyPy 
will optimise a lot of the overhead away that this code contains.


>> So if I understand you correctly, this is not Cpu bound

I don't have enough information to comment on that.


> It may still be CPU bound in that the CPU is doing all the work, but if
> the CPU time is in the DLL functions rather than in the loop cython
> won't help much.
>
> CPU bound refers to the type of processing - is it lots of logic, math,
> control flows etc? Or is it I/O bound - reading network, disk, or user
> input? Or it might be memory bound - creating lots of in memory objects
> (especially if that results in paging to disk, when it becomes I/O
> bound  too!)
>
> Knowing what is causing the bottleneck will determine how to improve
> things. Use tools like TaskManager in Windows or top in *nix to see
> where the time is going and what resources are being consumed. Fast code
> is not always the answer.

That is very good advice. As a rule of thumb, a process monitor like top 
will tell you how much time is spent in I/O and CPU. If, during a test run 
(with profiling disabled, as that eats time, too!), your CPU usage stays 
close to 100%, your program is CPU bound. If, however, it stays lower, and 
the monitor reports a high I/O waiting time, it's I/O bound. In this case, 
I/O bound is what you want to achieve, because it means that your code is 
running faster than your hard drive can deliver the data.

Stefan


From coolankur2006 at gmail.com  Sat Jul  2 22:30:58 2011
From: coolankur2006 at gmail.com (ANKUR AGGARWAL)
Date: Sun, 3 Jul 2011 02:00:58 +0530
Subject: [Tutor] Algorithm for sequence matching
Message-ID: <CAKZ9t5cjLzaQr2QYUkh1cyCK-ukS9ZjY9Danc6VxUyrQ67EmKw@mail.gmail.com>

Hey
I am looking for an algo for the largest sequence search in the two list.

Example : list a accepts some say 'm' numbers. list b accept says 'n'
numbers. I want to look for the largest same sequence between the two list
and then display it. I tried out but failed to do so.
Say A=[11,23,45,21,63,56,78,32]
B=[56,78,11,23,45,21,111,234,56543]

There are two  similar sequence matching over here [11,23] and [23,45,21] i
want to display second sequence because its larger in number. Plz help
Thanks in Advance :)

Ankur Aggarwal
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110703/cb4e93cd/attachment-0001.html>

From bgailer at gmail.com  Sat Jul  2 23:09:52 2011
From: bgailer at gmail.com (bob gailer)
Date: Sat, 02 Jul 2011 17:09:52 -0400
Subject: [Tutor] Algorithm for sequence matching
In-Reply-To: <CAKZ9t5cjLzaQr2QYUkh1cyCK-ukS9ZjY9Danc6VxUyrQ67EmKw@mail.gmail.com>
References: <CAKZ9t5cjLzaQr2QYUkh1cyCK-ukS9ZjY9Danc6VxUyrQ67EmKw@mail.gmail.com>
Message-ID: <4E0F8920.3000301@gmail.com>

On 7/2/2011 4:30 PM, ANKUR AGGARWAL wrote:
> Hey
> I am looking for an algo for the largest sequence search in the two list.
>
> Example : list a accepts some say 'm' numbers. list b accept says 'n' 
> numbers. I want to look for the largest same sequence between the two 
> list and then display it. I tried out but failed to do so.
> Say A=[11,23,45,21,63,56,78,32]
> B=[56,78,11,23,45,21,111,234,56543]
>
> There are two  similar sequence matching over here [11,23] and 
> [23,45,21] i want to display second sequence because its larger in 
> number.

Makes no sense to me!

Pleae explain so a dummy like me can understand.

Also tell us what you tried and how it failed.


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


From wprins at gmail.com  Sat Jul  2 23:16:16 2011
From: wprins at gmail.com (Walter Prins)
Date: Sat, 2 Jul 2011 22:16:16 +0100
Subject: [Tutor] Algorithm for sequence matching
In-Reply-To: <CAKZ9t5cjLzaQr2QYUkh1cyCK-ukS9ZjY9Danc6VxUyrQ67EmKw@mail.gmail.com>
References: <CAKZ9t5cjLzaQr2QYUkh1cyCK-ukS9ZjY9Danc6VxUyrQ67EmKw@mail.gmail.com>
Message-ID: <CANLXbfB63TwW_NZCxEQ_C+rDOLMkT-VDwAtdOA+dzYwDR6P0Cg@mail.gmail.com>

Hi Ankur,

On 2 July 2011 21:30, ANKUR AGGARWAL <coolankur2006 at gmail.com> wrote:

> Hey
> I am looking for an algo for the largest sequence search in the two list.
>
> Example : list a accepts some say 'm' numbers. list b accept says 'n'
> numbers. I want to look for the largest same sequence between the two list
> and then display it. I tried out but failed to do so.
> Say A=[11,23,45,21,63,56,78,32]
> B=[56,78,11,23,45,21,111,234,56543]
>
> There are two  similar sequence matching over here [11,23] and [23,45,21] i
> want to display second sequence because its larger in number. Plz help
> Thanks in Advance :)
>

Umm, what about [11,23,45,21]?  That seems to be longer still so should be
the best one to display, or?

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110702/6e73461a/attachment.html>

From wprins at gmail.com  Sun Jul  3 00:18:44 2011
From: wprins at gmail.com (Walter Prins)
Date: Sat, 2 Jul 2011 23:18:44 +0100
Subject: [Tutor] Algorithm for sequence matching
In-Reply-To: <CAKZ9t5fceYHLy5kHZpnbmNe+HiUkf_MtK6_6RWm5Jy+Ja9A31g@mail.gmail.com>
References: <CAKZ9t5cjLzaQr2QYUkh1cyCK-ukS9ZjY9Danc6VxUyrQ67EmKw@mail.gmail.com>
	<CANLXbfB63TwW_NZCxEQ_C+rDOLMkT-VDwAtdOA+dzYwDR6P0Cg@mail.gmail.com>
	<CAKZ9t5fceYHLy5kHZpnbmNe+HiUkf_MtK6_6RWm5Jy+Ja9A31g@mail.gmail.com>
Message-ID: <CANLXbfAMzPxH18kvNRT0ACruoCQSO2O3d1eLgfB=14NuAqK8_g@mail.gmail.com>

Forwarding back to list.

---------- Forwarded message ----------
From: ANKUR AGGARWAL
Date: 2 July 2011 22:23
Subject: Re: [Tutor] Algorithm for sequence matching
To: Walter Prins

ya sorry I forgot to include 11 . i want the answer to be [11,23,45,21]

On Sun, Jul 3, 2011 at 2:46 AM, Walter Prins  wrote:
> Hi Ankur,
>
> Umm, what about [11,23,45,21]?  That seems to be longer still so should be
> the best one to display, or?
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110702/5cf68886/attachment.html>

From __peter__ at web.de  Sun Jul  3 00:29:46 2011
From: __peter__ at web.de (Peter Otten)
Date: Sun, 03 Jul 2011 00:29:46 +0200
Subject: [Tutor] Algorithm for sequence matching
References: <CAKZ9t5cjLzaQr2QYUkh1cyCK-ukS9ZjY9Danc6VxUyrQ67EmKw@mail.gmail.com>
Message-ID: <iuo64g$lig$1@dough.gmane.org>

ANKUR AGGARWAL wrote:

> Hey
> I am looking for an algo for the largest sequence search in the two list.
> 
> Example : list a accepts some say 'm' numbers. list b accept says 'n'
> numbers. I want to look for the largest same sequence between the two list
> and then display it. I tried out but failed to do so.
> Say A=[11,23,45,21,63,56,78,32]
> B=[56,78,11,23,45,21,111,234,56543]
> 
> There are two  similar sequence matching over here [11,23] and [23,45,21]
> i want to display second sequence because its larger in number. Plz help
> Thanks in Advance :)

The following is not particular efficient, but may be good enough if the 
sequences are not too long:

def index(items, value):
    """Generate all occurences of `value` in `items`"""
    start = 0
    while True:
        try:
            pos = items.index(value, start)
        except ValueError:
            break
        yield pos
        start = pos + 1

def matches(a, b):
    for i, x in enumerate(a):
        for k in index(b, x):
            for p, (s, t) in enumerate(zip(a[i:], b[k:])):
                if s != t:
                    break
            yield a[i:i+p]

if __name__ == "__main__":
    a = [11, 23, 45, 21, 63, 56, 78, 32]
    b = [56, 78, 11, 23, 45, 21, 111, 234, 56543]

    print(max(matches(a, b), key=len))
    print(sorted(matches(a, b)))



From wprins at gmail.com  Sun Jul  3 00:46:36 2011
From: wprins at gmail.com (Walter Prins)
Date: Sat, 2 Jul 2011 23:46:36 +0100
Subject: [Tutor] Algorithm for sequence matching
In-Reply-To: <CAKZ9t5cjLzaQr2QYUkh1cyCK-ukS9ZjY9Danc6VxUyrQ67EmKw@mail.gmail.com>
References: <CAKZ9t5cjLzaQr2QYUkh1cyCK-ukS9ZjY9Danc6VxUyrQ67EmKw@mail.gmail.com>
Message-ID: <CANLXbfDr6k462eWQv6zvyXzK_dF+tM1qr687qSkAvmyMF5HY3g@mail.gmail.com>

Hi Ankur,

On 2 July 2011 21:30, ANKUR AGGARWAL <coolankur2006 at gmail.com> wrote:

> Hey
> I am looking for an algo for the largest sequence search in the two list.
>
> Example : list a accepts some say 'm' numbers. list b accept says 'n'
> numbers. I want to look for the largest same sequence between the two list
> and then display it. I tried out but failed to do so.
> Say A=[11,23,45,21,63,56,78,32]
> B=[56,78,11,23,45,21,111,234,56543]
>
> There are two  similar sequence matching over here [11,23] and
> [11,23,45,21] i want to display second sequence because its larger in
> number. Plz help
>
>
OK, so what if A = [1,4,2,7,4,6] and B = [4,9,10,11,12,14,17,4]?  Would you
consider [4,4] a valid answer to your question?  It is a common subsequence,
albeit not of concescutive elements?

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110702/37a9c420/attachment.html>

From wprins at gmail.com  Sun Jul  3 00:59:42 2011
From: wprins at gmail.com (Walter Prins)
Date: Sat, 2 Jul 2011 23:59:42 +0100
Subject: [Tutor] Algorithm for sequence matching
In-Reply-To: <CANLXbfDr6k462eWQv6zvyXzK_dF+tM1qr687qSkAvmyMF5HY3g@mail.gmail.com>
References: <CAKZ9t5cjLzaQr2QYUkh1cyCK-ukS9ZjY9Danc6VxUyrQ67EmKw@mail.gmail.com>
	<CANLXbfDr6k462eWQv6zvyXzK_dF+tM1qr687qSkAvmyMF5HY3g@mail.gmail.com>
Message-ID: <CANLXbfB60Pixt6=kRH1qHMqRfFiktZAYmTaP9LODrX51OH2AcA@mail.gmail.com>

Just to clarify further:

On 2 July 2011 23:46, Walter Prins <wprins at gmail.com> wrote:

> On 2 July 2011 21:30, ANKUR AGGARWAL <coolankur2006 at gmail.com> wrote:
>
>> Example : list a accepts some say 'm' numbers. list b accept says 'n'
>> numbers. I want to look for the largest same sequence between the two list
>> and then display it. I tried out but failed to do so.
>> Say A=[11,23,45,21,63,56,78,32]
>> B=[56,78,11,23,45,21,111,234,56543]
>>
>> There are two  similar sequence matching over here [11,23] and
>> [11,23,45,21] i want to display second sequence because its larger in
>> number. Plz help
>>
>
> OK, so what if A = [1,4,2,7,4,6] and B = [4,9,10,11,12,14,17,4]?  Would you
> consider [4,4] a valid answer to your question?  It is a common subsequence,
> albeit not of concescutive elements?
>

There is a difference between a sub*sequence* and a sub*string*.  Strictly
speaking, a *subsquence* is a sequence that can be derived from another
sequence by deleting some of the elements from the other sequence.  The
result thus retains the ordering from the original but the elements need not
have been consecutive elements.  A *substring* on the other hand implies
consecutive elements.  I'm trying to make sure I understand your question,
and whether you're really after the longest common subsequence (LCS) or
longest common substring.  My question above thus are trying to establish
which of the two cases you're really after. Obviously the answer will be
different depending on what you really want.

Regards

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110702/33722cc4/attachment-0001.html>

From merrickdav at gmail.com  Sun Jul  3 01:47:56 2011
From: merrickdav at gmail.com (David Merrick)
Date: Sun, 3 Jul 2011 11:47:56 +1200
Subject: [Tutor] Blackjack Betting
Message-ID: <CA+=McKa5oeqPuuoJqxP1DKJigyvxjouxAz43t=8zdsSkYEy=9A@mail.gmail.com>

Each player needs to be able to bet

# Blackjack
# From 1 to 7 players compete against a dealer

import cards, games

class BJ_Card(cards.Card):
    """ A Blackjack Card. """
    ACE_VALUE = 1

    @property
    def value(self):
        if self.is_face_up:
            v = BJ_Card.RANKS.index(self.rank) + 1
            if v > 10:
                v = 10
        else:
            v = None
        return v

class BJ_Deck(cards.Deck):
    """ A Blackjack Deck. """
    def populate(self):
        for suit in BJ_Card.SUITS:
            for rank in BJ_Card.RANKS:
                self.cards.append(BJ_Card(rank, suit))


class BJ_Hand(cards.Hand):
    """ A Blackjack Hand. """
    def __init__(self, name):
        super(BJ_Hand, self).__init__()
        self.name = name

    def __str__(self):
        rep = self.name + ":\t" + super(BJ_Hand, self).__str__()
        if self.total:
            rep += "(" + str(self.total) + ")"
        return rep

    @property
    def total(self):
        # if a card in the hand has value of None, then total is None
        for card in self.cards:
            if not card.value:
                return None

        # add up card values, treat each Ace as 1
        t = 0
        for card in self.cards:
              t += card.value

        # determine if hand contains an Ace
        contains_ace = False
        for card in self.cards:
            if card.value == BJ_Card.ACE_VALUE:
                contains_ace = True

        # if hand contains Ace and total is low enough, treat Ace as 11
        if contains_ace and t <= 11:
            # add only 10 since we've already added 1 for the Ace
            t += 10

        return t

    def is_busted(self):
        return self.total > 21


class BJ_Player(BJ_Hand):
    """ A Blackjack Player. """

    def betting(stash):
        try:
            if stash > 0:
                wager = int(input("\nHow much do you want to wager?: "))
                if wager > bet.stash:
                    int(input("\n You can only wager what you have. How
much?: "))
                elif wager < 0:
                    int(input("\n You can only wager what you have. How
much?: "))
        except ValueError:
                int(input("\n That's not valid! Choose a number: "))

    def is_hitting(self):
        response = games.ask_yes_no("\n" + self.name + ", do you want a hit?
(Y/N): ")
        return response == "y"

    def bust(self):
        print(self.name, "busts.")
        self.lose()

    def lose(self):
        print(self.name, "loses.")

    def win(self):
        print(self.name, "wins.")

    def push(self):
        print(self.name, "pushes.")


class BJ_Dealer(BJ_Hand):
    """ A Blackjack Dealer. """
    def is_hitting(self):
        return self.total < 17

    def bust(self):
        print(self.name, "busts.")

    def flip_first_card(self):
        first_card = self.cards[0]
        first_card.flip()


class BJ_Game(object):
    """ A Blackjack Game. """
    def __init__(self, names):
        self.players = []
        for name in names:
            player = BJ_Player(name)
            bet = BJ_Player(name).betting(stash = 10)
            self.players.append(player)

        self.dealer = BJ_Dealer("Dealer")

        self.deck = BJ_Deck()
        self.deck.populate()
        self.deck.shuffle()

    @property
    def still_playing(self):
        sp = []
        for player in self.players:
            if not player.is_busted():
                sp.append(player)
        return sp

    def __additional_cards(self, player):
        while not player.is_busted() and player.is_hitting():
            self.deck.deal([player])
            print(player)
            if player.is_busted():
                player.bust()

    def play(self):
        # deal initial 2 cards to everyone
        self.deck.deal(self.players + [self.dealer], per_hand = 2)
        self.dealer.flip_first_card()    # hide dealer's first card
        for player in self.players:
            print(player)
        print(self.dealer)

        # deal additional cards to players
        for player in self.players:
            self.__additional_cards(player)

        self.dealer.flip_first_card()    # reveal dealer's first

        if not self.still_playing:
            # since all players have busted, just show the dealer's hand
            print(self.dealer)
        else:
            # deal additional cards to dealer
            print(self.dealer)
            self.__additional_cards(self.dealer)

            if self.dealer.is_busted():
                # everyone still playing wins
                for player in self.still_playing:
                    player.win()
            else:
                # compare each player still playing to dealer
                for player in self.still_playing:
                    if player.total > self.dealer.total:
                        player.win()
                    elif player.total < self.dealer.total:
                        player.lose()
                    else:
                        player.push()

        # remove everyone's cards
        for player in self.players:
            player.clear()
        self.dealer.clear()


def main():
    print("\t\tWelcome to Blackjack!\n")

    names = []
    number = games.ask_number("How many players? (1 - 7): ", low = 1, high =
8)
    for i in range(number):
        name = input("Enter player name: ")
        names.append(name)
    print()

    game = BJ_Game(names)

    again = None
    while again != "n":
        game.play()
        again = games.ask_yes_no("\nDo you want to play again?: ")


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


*Output*

Welcome to Blackjack!

How many players? (1 - 7): 1
Enter player name: Dave

Traceback (most recent call last):
  File "I:/Python/Python Source Code/chapter09/blackjackBetting.py", line
204, in <module>
    main()
  File "I:/Python/Python Source Code/chapter09/blackjackBetting.py", line
196, in main
    game = BJ_Game(names)
  File "I:/Python/Python Source Code/chapter09/blackjackBetting.py", line
120, in __init__
    bet = BJ_Player(name).betting(stash = 10)
TypeError: betting() got multiple values for keyword argument 'stash'
>>>

-- 
Dave Merrick

merrickdav at gmail.com

Ph   03 3423 121
Cell 027 3089 169
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110703/bf420b01/attachment.html>

From amonroe at columbus.rr.com  Sun Jul  3 02:58:22 2011
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Sat, 2 Jul 2011 20:58:22 -0400
Subject: [Tutor] problem reading script
In-Reply-To: <201107011513.37739.lisi.reisz@gmail.com>
References: <201107011015.08328.lisi.reisz@gmail.com>
	<4E0DCAEF.4050809@pearwood.info>
	<201107011513.37739.lisi.reisz@gmail.com>
Message-ID: <136518335947.20110702205822@columbus.rr.com>


> Suggestions for "a programmers font" gratefully received.

DejaVu Sans Mono


From steve at pearwood.info  Sun Jul  3 03:58:37 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 03 Jul 2011 11:58:37 +1000
Subject: [Tutor] Algorithm for sequence matching
In-Reply-To: <CAKZ9t5cjLzaQr2QYUkh1cyCK-ukS9ZjY9Danc6VxUyrQ67EmKw@mail.gmail.com>
References: <CAKZ9t5cjLzaQr2QYUkh1cyCK-ukS9ZjY9Danc6VxUyrQ67EmKw@mail.gmail.com>
Message-ID: <4E0FCCCD.1090501@pearwood.info>

ANKUR AGGARWAL wrote:
> Hey
> I am looking for an algo for the largest sequence search in the two list.
> 
> Example : list a accepts some say 'm' numbers. list b accept says 'n'
> numbers. I want to look for the largest same sequence between the two list
> and then display it. I tried out but failed to do so.

Google is your friend. Please search for "longest common subsequence" 
and "longest common substring". You can add "algorithm" and "python" if 
you like. Wikipedia, for example, gives good algorithms for both 
problems, which can be adapted to Python.

You might also like to look at the difflib module in the standard 
library, particularly the SequenceMatcher class.


-- 
Steven

From marc.tompkins at gmail.com  Sun Jul  3 06:44:25 2011
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Sat, 2 Jul 2011 21:44:25 -0700
Subject: [Tutor] Blackjack Betting
In-Reply-To: <CA+=McKa5oeqPuuoJqxP1DKJigyvxjouxAz43t=8zdsSkYEy=9A@mail.gmail.com>
References: <CA+=McKa5oeqPuuoJqxP1DKJigyvxjouxAz43t=8zdsSkYEy=9A@mail.gmail.com>
Message-ID: <CAKK8jXao0LE_k1J5K=KrpvUzT26n9vuBmxtFgm3Pn0Xh+Zi2Pg@mail.gmail.com>

On Sat, Jul 2, 2011 at 4:47 PM, David Merrick <merrickdav at gmail.com> wrote:

> Each player needs to be able to bet
>

Traceback (most recent call last):
>   File "I:/Python/Python Source Code/chapter09/blackjackBetting.py", line
> 204, in <module>
>     main()
>   File "I:/Python/Python Source Code/chapter09/blackjackBetting.py", line
> 196, in main
>     game = BJ_Game(names)
>   File "I:/Python/Python Source Code/chapter09/blackjackBetting.py", line
> 120, in __init__
>     bet = BJ_Player(name).betting(stash = 10)
> TypeError: betting() got multiple values for keyword argument 'stash'
> >>>
>
>

The "(stash = 10)" syntax is only used in the function (or method, in this
case) definition.  It means that "stash" is optional: if no value is
supplied for "stash", then it will be assigned a default value of 10.

So you have choices: all of the following will invoke "betting" with "stash"
having an initial value of 10.
    By value:

>         bet = BJ_Player(name).betting(10)
>
    By passing a variable:

>         pari = 10
>
        bet = BJ_Player(name).betting(pari)
>
    By default:

>         bet = BJ_Player(name).betting()
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110702/9b2eda34/attachment-0001.html>

From steve at pearwood.info  Sun Jul  3 07:08:16 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 03 Jul 2011 15:08:16 +1000
Subject: [Tutor] problem with reading dns query
In-Reply-To: <CAM8AQFg+pERpuCgECKLP64OxrZGOcP8sdJbivDc4Wf9Xop6xog@mail.gmail.com>
References: <CAM8AQFg+pERpuCgECKLP64OxrZGOcP8sdJbivDc4Wf9Xop6xog@mail.gmail.com>
Message-ID: <4E0FF940.4070903@pearwood.info>

preetam shivaram wrote:
> I have got a very simple idea in mind that i want to try out. Say i have a
> browser, chrome for instance, and i want to search for the ip of the domain
> name, say `www.google.com`. I use windows 7 and i have set the dns lookup
> properties to manual and have given the address `127.0.0.1` where my server
> (written in Python) is running. I started my server and i could see the dns
> query like this:


It seems to me that you want to learn how to write your own DNS caching 
server. To do that, you have to understand the DNS protocol. Start with 
the Wikipedia article:

http://en.wikipedia.org/wiki/Domain_Name_System

We probably can't help you here, this is a list for learning Python, not 
DNS. You might have more luck on the main Python list, 
<python-list at python.com> or news group <comp.lang.python> But generally, 
I would expect they'll give you the same advice I am giving: google is 
your friend.

Search for "python DNS server" and you will find information that may be 
useful to you.


More comments below:


>     WAITING FOR CONNECTION.........
> 
>     .........recieved from :  ('127.0.0.1', 59339)
> 
> "'~\\x17\\x01\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x03www\\x06google\\x02co\\x02in\\x00\\x00\\x01\\x00\\x01'"
> 
> The `waiting for connection` and the `received from` is from my server. How
> do i get a breakdown form(a human readable form) of this message??

Define "human readable form".

The data you get includes binary bytes, that is, you are getting:

tilde
hex byte 17
hex byte 01
null byte
null byte
hex byte 01

etc.

How would you like the string to be displayed, if not with escaped hex 
codes?

If you just print the string, the binary bytes will probably disappear 
because your terminal doesn't show them. You can convert to human 
readable form with escaped binary bytes using repr() like this:


 >>> print s  # non-printable characters don't print
~wwwgooglecoin
 >>> print repr(s)
'~\x17\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x06google\x02co\x02in\x00\x00\x01\x00\x01'


You could also try a hex dump, there are many recipes on the Internet. 
Here's the first one I tried:

http://code.activestate.com/recipes/142812-hex-dumper/

 >>> print(dump(s))
0000   7E 17 01 00 00 01 00 00    ~.......
0008   00 00 00 00 03 77 77 77    .....www
0010   06 67 6F 6F 67 6C 65 02    .google.
0018   63 6F 02 69 6E 00 00 01    co.in...
0020   00 01                      ..



-- 
Steven


From alan.gauld at btinternet.com  Sun Jul  3 10:00:03 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 3 Jul 2011 09:00:03 +0100
Subject: [Tutor] Blackjack Betting
References: <CA+=McKa5oeqPuuoJqxP1DKJigyvxjouxAz43t=8zdsSkYEy=9A@mail.gmail.com>
Message-ID: <iup7i9$ovs$1@dough.gmane.org>


"David Merrick" <merrickdav at gmail.com> wrote
> class BJ_Player(BJ_Hand):
>    """ A Blackjack Player. """
>
>    def betting(stash):

You forgot self.... so stash will take on the value of
the instance.


>        try:
>            if stash > 0:
>                wager = int(input("\nHow much do you want to wager?: 
> "))
>                if wager > bet.stash:
>                    int(input("\n You can only wager what you have. 
> How
> much?: "))

and you don't assign the result here to any variables


> class BJ_Game(object):
>    """ A Blackjack Game. """
>    def __init__(self, names):
>        self.players = []
>        for name in names:
>            player = BJ_Player(name)
>            bet = BJ_Player(name).betting(stash = 10)

Here you call the method and python assigns the new
instance value to stash, but you are simultaneously
assigning 10 to stash. Pyton is confused...

You need a self in your method definition.

>  File "I:/Python/Python Source Code/chapter09/blackjackBetting.py", 
> line
> 120, in __init__
>    bet = BJ_Player(name).betting(stash = 10)
> TypeError: betting() got multiple values for keyword argument 
> 'stash'
>>>>

HTH,


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



From fomcl at yahoo.com  Sun Jul  3 11:15:46 2011
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Sun, 3 Jul 2011 02:15:46 -0700 (PDT)
Subject: [Tutor] Cython question
In-Reply-To: <iunbao$jjt$1@dough.gmane.org>
Message-ID: <1309684546.31518.YahooMailClassic@web110713.mail.gq1.yahoo.com>

Hi Stefan, Alan,

Thanks for your useful advice. The first thing I will try is take the call to the spssio dll out of the Python method (ie, 'unwrap' it) and put it inside the loop. I didn't think wrapping the code inside a method/function would create so much overhead.

Cheers!!

Albert-Jan



~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

--- On Sat, 7/2/11, Stefan Behnel <stefan_ml at behnel.de> wrote:

From: Stefan Behnel <stefan_ml at behnel.de>
Subject: Re: [Tutor] Cython question
To: tutor at python.org
Date: Saturday, July 2, 2011, 4:52 PM

Alan Gauld, 02.07.2011 15:28:
> "Albert-Jan Roskam" wrote
>> I used cProfile to find the bottlenecks, the two Python functions
>> getValueChar and getValueNum. These two Python functions simply call two
>> equivalent C functions in a .dll (using ctypes).

The code is currently declared as Windows-only and I don't know any good C-level profiling code for that platform. Under Linux, once I'm sure I have a CPU bound problem below the Python level, I'd use valgrind and KCacheGrind to analyse the performance. That will include all C function calls (and even CPU instructions, if you want) in the call trace. Makes it a bit less obvious to see what Python is doing, but leads to much more detailed results at the C level.

It's also worth keeping in mind that all profiling attempts *always* interfere with the normal program execution. The results you get during a profiling run may not be what you'd get with profiling disabled. So, profiling is nice, but it doesn't replace proper benchmarking.


> In that case cythin will speed up the calling loops but it can't do
> anything to speed up the DLL calls, you have effectively already optimised
> those functions by calling the DLL.
> 
>> The problem is that these functions are called as many times as there are
>> VALUES in a file
> 
> It might be worth a try if you have very big data sets
> because a C loop is faster than a Python loop. But don't expect order of
> magnitude improvements.

Looking at the code now, it's actually worse than that. The C function call does not only go through ctypes, but is additionally wrapped in a method call. So the OP is paying the call overhead twice for each field, plus the method lookup and some other operations. These things can add up quite easily.

So, iff the conversion code is really a CPU bottleneck, and depending on how much work the C functions actually do, the current call overhead, 100 times per record, may be a substantial part of the game. It's worth seeing if it can be dropped at the Python level by removing method lookup and call levels (i.e. by inlining the method), but if that's not enough, Cython may still be worth it. For one, Cython's call overhead is lower than that of ctypes, and if the call is only done once, and the loop is moved into Cython (i.e. C) entirely, the overhead will also drop substantially.

It might also be worth running the code in PyPy instead of CPython. PyPy will optimise a lot of the overhead away that this code contains.


>> So if I understand you correctly, this is not Cpu bound

I don't have enough information to comment on that.


> It may still be CPU bound in that the CPU is doing all the work, but if
> the CPU time is in the DLL functions rather than in the loop cython
> won't help much.
> 
> CPU bound refers to the type of processing - is it lots of logic, math,
> control flows etc? Or is it I/O bound - reading network, disk, or user
> input? Or it might be memory bound - creating lots of in memory objects
> (especially if that results in paging to disk, when it becomes I/O
> bound? too!)
> 
> Knowing what is causing the bottleneck will determine how to improve
> things. Use tools like TaskManager in Windows or top in *nix to see
> where the time is going and what resources are being consumed. Fast code
> is not always the answer.

That is very good advice. As a rule of thumb, a process monitor like top will tell you how much time is spent in I/O and CPU. If, during a test run (with profiling disabled, as that eats time, too!), your CPU usage stays close to 100%, your program is CPU bound. If, however, it stays lower, and the monitor reports a high I/O waiting time, it's I/O bound. In this case, I/O bound is what you want to achieve, because it means that your code is running faster than your hard drive can deliver the data.

Stefan

_______________________________________________
Tutor maillist? -? Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110703/2d36f9e3/attachment.html>

From g.nius.ck at gmail.com  Sun Jul  3 17:48:06 2011
From: g.nius.ck at gmail.com (Christopher King)
Date: Sun, 3 Jul 2011 11:48:06 -0400
Subject: [Tutor] Algorithm for sequence matching
In-Reply-To: <CANLXbfB63TwW_NZCxEQ_C+rDOLMkT-VDwAtdOA+dzYwDR6P0Cg@mail.gmail.com>
References: <CAKZ9t5cjLzaQr2QYUkh1cyCK-ukS9ZjY9Danc6VxUyrQ67EmKw@mail.gmail.com>
	<CANLXbfB63TwW_NZCxEQ_C+rDOLMkT-VDwAtdOA+dzYwDR6P0Cg@mail.gmail.com>
Message-ID: <CAKBg9Z0+9Z8qpxs5pGeVKaknkZxTJuuKrRMjR52NGrbp-6VGtQ@mail.gmail.com>

I know a way to do that
set1 = set(list1)
set2 = set(list2)
combined = set1&set2

On Sat, Jul 2, 2011 at 5:16 PM, Walter Prins <wprins at gmail.com> wrote:

> Hi Ankur,
>
> On 2 July 2011 21:30, ANKUR AGGARWAL <coolankur2006 at gmail.com> wrote:
>
>> Hey
>> I am looking for an algo for the largest sequence search in the two list.
>>
>> Example : list a accepts some say 'm' numbers. list b accept says 'n'
>> numbers. I want to look for the largest same sequence between the two list
>> and then display it. I tried out but failed to do so.
>> Say A=[11,23,45,21,63,56,78,32]
>> B=[56,78,11,23,45,21,111,234,56543]
>>
>> There are two  similar sequence matching over here [11,23] and [23,45,21]
>> i want to display second sequence because its larger in number. Plz help
>> Thanks in Advance :)
>>
>
> Umm, what about [11,23,45,21]?  That seems to be longer still so should be
> the best one to display, or?
>
> Walter
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110703/9d3b9493/attachment.html>

From fomcl at yahoo.com  Sun Jul  3 19:32:36 2011
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Sun, 3 Jul 2011 10:32:36 -0700 (PDT)
Subject: [Tutor] Algorithm for sequence matching
In-Reply-To: <CAKBg9Z0+9Z8qpxs5pGeVKaknkZxTJuuKrRMjR52NGrbp-6VGtQ@mail.gmail.com>
Message-ID: <1309714356.49463.YahooMailClassic@web110704.mail.gq1.yahoo.com>

Hi,

Are you looking for a Longest Common Subsequence (LCS) algorithm?
http://code.activestate.com/recipes/576869-longest-common-subsequence-problem-solver/

Cheers!!

Albert-Jan



~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

--- On Sun, 7/3/11, Christopher King <g.nius.ck at gmail.com> wrote:

From: Christopher King <g.nius.ck at gmail.com>
Subject: Re: [Tutor] Algorithm for sequence matching
To: "Walter Prins" <wprins at gmail.com>
Cc: tutor at python.org
Date: Sunday, July 3, 2011, 5:48 PM

I know a way to do thatset1 = set(list1)set2 = set(list2)combined = set1&set2

On Sat, Jul 2, 2011 at 5:16 PM, Walter Prins <wprins at gmail.com> wrote:

Hi Ankur,

On 2 July 2011 21:30, ANKUR AGGARWAL <coolankur2006 at gmail.com> wrote:


HeyI am looking for an algo for the largest sequence search in the two list.
Example : list a accepts some say 'm' numbers. list b accept says 'n' numbers. I want to look for the largest same sequence between the two list and then display it. I tried out but failed to do so.?



Say A=[11,23,45,21,63,56,78,32]B=[56,78,11,23,45,21,111,234,56543]
There are two ?similar sequence matching over here [11,23] and [23,45,21] i want to display second sequence because its larger in number. Plz help



Thanks in Advance :)
Umm, what about [11,23,45,21]?? That seems to be longer still so should be the best one to display, or?

Walter 



_______________________________________________

Tutor maillist ?- ?Tutor at python.org

To unsubscribe or change subscription options:

http://mail.python.org/mailman/listinfo/tutor





-----Inline Attachment Follows-----

_______________________________________________
Tutor maillist? -? Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110703/08f1e133/attachment.html>

From merrickdav at gmail.com  Mon Jul  4 01:43:02 2011
From: merrickdav at gmail.com (David Merrick)
Date: Mon, 4 Jul 2011 11:43:02 +1200
Subject: [Tutor] Blackjackbetting
Message-ID: <CA+=McKaR-yEpRcUv6LDR+cHmqHnbEY0FYrCTFUPrDfVeHSV_ow@mail.gmail.com>

HI. I feel I'm starting to go round in circles solving this problem. I feel
I made significant progress.
Can someone help me iron out the bugs please

# Blackjack
# From 1 to 7 players compete against a dealer

import cards, games

class BJ_Card(cards.Card):
    """ A Blackjack Card. """
    ACE_VALUE = 1

    @property
    def value(self):
        if self.is_face_up:
            v = BJ_Card.RANKS.index(self.rank) + 1
            if v > 10:
                v = 10
        else:
            v = None
        return v

class BJ_Deck(cards.Deck):
    """ A Blackjack Deck. """
    def populate(self):
        for suit in BJ_Card.SUITS:
            for rank in BJ_Card.RANKS:
                self.cards.append(BJ_Card(rank, suit))


class BJ_Hand(cards.Hand):
    """ A Blackjack Hand. """
    def __init__(self, name):
        super(BJ_Hand, self).__init__()
        self.name = name

    def __str__(self):
        rep = self.name + ":\t" + super(BJ_Hand, self).__str__()
        if self.total:
            rep += "(" + str(self.total) + ")"
        return rep

    @property
    def total(self):
        # if a card in the hand has value of None, then total is None
        for card in self.cards:
            if not card.value:
                return None

        # add up card values, treat each Ace as 1
        t = 0
        for card in self.cards:
              t += card.value

        # determine if hand contains an Ace
        contains_ace = False
        for card in self.cards:
            if card.value == BJ_Card.ACE_VALUE:
                contains_ace = True

        # if hand contains Ace and total is low enough, treat Ace as 11
        if contains_ace and t <= 11:
            # add only 10 since we've already added 1 for the Ace
            t += 10

        return t

    def is_busted(self):
        return self.total > 21

class Bet(object):
    """ A Blackjack Gamble. """
    # Values
    def __init__(bet, money = 10):
        stash  = money

    # Betting options
    def betting(bet,stash):
        try:
            if stash > 0:
                wager = int(input("\nHow much do you want to wager?: "))
                if wager > stash:
                    int(input("\n You can only wager what you have. How
much?: "))
                elif wager < 0:
                    int(input("\n You can only wager what you have. How
much?: "))
        except ValueError:
                int(input("\n That's not valid! Choose a number: "))


    # Money Conditions
    def gamble(bet):
        if bet.stash <= 0:
            print("\nYou are out of money! You're out of the game!")



class BJ_Player(BJ_Hand):
    """ A Blackjack Player. """
    stash = 10
    if stash <= 0:
             print("\nYou are out of money! You're out of the game!")

    def is_hitting(self):
        response = games.ask_yes_no("\n" + self.name + ", do you want a hit?
(Y/N): ")
        return response == "y"

    def bust(self,stash,wager):
        print(self.name, "busts.")
        self.lose(self,stash,wager)

    def lose(self,stash,wager):
        print(self.name, "loses.")
        stash = stash - wager
        print("Your stash is: ",stash)
        return stash

    def win(self,stash,wager):
        print(self.name, "wins.")
        stash = stash + wager
        print("Your stash is: ",stash)
        return stash

    def push(self):
        print(self.name, "pushes.")


class BJ_Dealer(BJ_Hand):
    """ A Blackjack Dealer. """
    def is_hitting(self):
        return self.total < 17

    def bust(self):
        print(self.name, "busts.")

    def flip_first_card(self):
        first_card = self.cards[0]
        first_card.flip()


class BJ_Game(object):
    """ A Blackjack Game. """
    def __init__(self, names):
        self.players = []
        for name in names:
            stash = 100
            player = BJ_Player(name)
            playerbet = Bet(stash).betting(stash)
            self.players.append(player)

        self.dealer = BJ_Dealer("Dealer")

        self.deck = BJ_Deck()
        self.deck.populate()
        self.deck.shuffle()

    @property
    def still_playing(self):
        sp = []
        for player in self.players:
            if not player.is_busted():
                sp.append(player)
        return sp

    def __additional_cards(self, player,stash,wager):
        while not player.is_busted() and player.is_hitting():
            self.deck.deal([player])
            print(player)
            if player.is_busted():
                player.bust(self,stash,wager)

    def play(self,stash,wager):
        # deal initial 2 cards to everyone
        self.deck.deal(self.players + [self.dealer], per_hand = 2)
        self.dealer.flip_first_card()    # hide dealer's first card
        for player in self.players:
            print(player)
        print(self.dealer)

        # deal additional cards to players
        for player in self.players:
            self.__additional_cards(player,stash,wager)

        self.dealer.flip_first_card()    # reveal dealer's first

        if not self.still_playing:
            # since all players have busted, just show the dealer's hand
            print(self.dealer)
        else:
            # deal additional cards to dealer
            print(self.dealer)
            self.__additional_cards(self.dealer,stash,wager)

            if self.dealer.is_busted():
                # everyone still playing wins
                for player in self.still_playing:
                    player.win(stash,wager)
            else:
                # compare each player still playing to dealer
                for player in self.still_playing:
                    if player.total > self.dealer.total:
                        player.win(stash,wager)
                    elif player.total < self.dealer.total:
                        player.lose(stash,wager)
                    else:
                        player.push()

        # remove everyone's cards
        for player in self.players:
            player.clear()
        self.dealer.clear()


def main():
    print("\t\tWelcome to Blackjack!\n")
    stash = 0
    wager = 0
    names = []
    number = games.ask_number("How many players? (1 - 7): ", low = 1, high =
8)
    for i in range(number):
        name = input("Enter player name: ")
        names.append(name)
    print()

    game = BJ_Game(names)

    again = None
    while again != "n":
        game.play(stash,wager)
        again = games.ask_yes_no("\nDo you want to play again?: ")


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

*Output*

Welcome to Blackjack!

How many players? (1 - 7): 1
Enter player name: Dave


How much do you want to wager?: 50
Dave:    Qc    8s    (18)
Dealer:    XX    3d

Dave, do you want a hit? (Y/N): n
Dealer:    Kd    3d    (13)
Dealer:    Kd    3d    Qh    (23)
Traceback (most recent call last):
  File "I:/Python/Python Source Code/chapter09/blackjackBettingB.py", line
229, in <module>
    main()
  File "I:/Python/Python Source Code/chapter09/blackjackBettingB.py", line
225, in main
    game.play(stash,wager)
  File "I:/Python/Python Source Code/chapter09/blackjackBettingB.py", line
188, in play
    self.__additional_cards(self.dealer,stash,wager)
  File "I:/Python/Python Source Code/chapter09/blackjackBettingB.py", line
166, in __additional_cards
    player.bust(self,stash,wager)
TypeError: bust() takes exactly 1 positional argument (4 given)

-- 
Dave Merrick

merrickdav at gmail.com

Ph   03 3423 121
Cell 027 3089 169
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110704/9a0b47d9/attachment-0001.html>

From alan.gauld at btinternet.com  Mon Jul  4 02:09:07 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 4 Jul 2011 01:09:07 +0100
Subject: [Tutor] Blackjackbetting
References: <CA+=McKaR-yEpRcUv6LDR+cHmqHnbEY0FYrCTFUPrDfVeHSV_ow@mail.gmail.com>
Message-ID: <iur0ba$a1t$1@dough.gmane.org>

"David Merrick" <merrickdav at gmail.com> wrote

> I feel I'm starting to go round in circles solving this problem.
> I feel I made significant progress.

That sounds like a contradiction.
Did you make progress or are you going in circles?

Do you understand what self is?

>  File "I:/Python/Python Source Code/chapter09/blackjackBettingB.py", 
> line
> 166, in __additional_cards
>    player.bust(self,stash,wager)
> TypeError: bust() takes exactly 1 positional argument (4 given)

OK, It looks a bit confusing but here are some observations.

player.bust() takes 1 argument. You have provided 4
It looks like 3, but remember that Python fills in the 'self'
argument using the current instance to make 4 in total.

Now why are you explicitly passing self as the first argument?
It looks like you don't really understand how self is used?

But where does the 1 argument come from, BJ Player
takes 3 arguments.... but BJ Hand.bust only takes one.

Could you have managed to create a BJHand instance
where you intended a BJPlayer?

I don't know, and I'm not going to try to unravel that
mass of code for you! But it's something to check.
(print is your friend)

But remember, we said away back at the beginning:
"don't try to debug a load of code at once.
Build it up slowly, testing as you go" ?

It's a lot easier to find bugs that way. If you continue
to pursue the "built it big and then ask for help" approach
you may run out of sympathetic readers before your code
ever works...

HTH,

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



From tidal.espeon at gmail.com  Mon Jul  4 16:46:31 2011
From: tidal.espeon at gmail.com (Tidal Espeon)
Date: Mon, 4 Jul 2011 10:46:31 -0400
Subject: [Tutor] Help with making emacs work with python syntax checking?
Message-ID: <CAE3a9fKaKK8hm5XP+jEfTUDB_GkzTBmjXbntZ56Ju2P=y1uA=g@mail.gmail.com>

I need help with installing this setup on my emacs:
http://hide1713.wordpress.com/2009/01/30/setup-perfect-python-environment-in-emacs/
The problem is that I have no clue how to access any .emacs file or .emacs.d
folder. I'm running linux, and they are apparently invisible in my home
directory. Trying to create those makes linux tell me that they're already
there. I've already installed the latest ropemacs, pyflakes, etc.
I'd sincerely appreciate help, since the IDLE just doesn't cut it for me.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110704/7935dca3/attachment.html>

From lisi.reisz at gmail.com  Mon Jul  4 17:02:59 2011
From: lisi.reisz at gmail.com (Lisi)
Date: Mon, 4 Jul 2011 16:02:59 +0100
Subject: [Tutor] Help with making emacs work with python syntax checking?
In-Reply-To: <CAE3a9fKaKK8hm5XP+jEfTUDB_GkzTBmjXbntZ56Ju2P=y1uA=g@mail.gmail.com>
References: <CAE3a9fKaKK8hm5XP+jEfTUDB_GkzTBmjXbntZ56Ju2P=y1uA=g@mail.gmail.com>
Message-ID: <201107041602.59435.lisi.reisz@gmail.com>

On Monday 04 July 2011 15:46:31 Tidal Espeon wrote:
> I need help with installing this setup on my emacs:
> http://hide1713.wordpress.com/2009/01/30/setup-perfect-python-environment-i
>n-emacs/ The problem is that I have no clue how to access any .emacs file or
> .emacs.d folder. I'm running linux, and they are apparently invisible in my
> home directory. Trying to create those makes linux tell me that they're
> already there. I've already installed the latest ropemacs, pyflakes, etc.
> I'd sincerely appreciate help, since the IDLE just doesn't cut it for me.

Do you know how to access hidden files, or is that the problem?

In fact, do you know what hidden files are?

If you can give me some indication of your skill level (see above questions) 
and your distro (including version) and DE, I might be able to help you; or 
anyhow point you in the right direction.

Lisi

From __peter__ at web.de  Mon Jul  4 17:12:50 2011
From: __peter__ at web.de (Peter Otten)
Date: Mon, 04 Jul 2011 17:12:50 +0200
Subject: [Tutor] Help with making emacs work with python syntax checking?
References: <CAE3a9fKaKK8hm5XP+jEfTUDB_GkzTBmjXbntZ56Ju2P=y1uA=g@mail.gmail.com>
Message-ID: <iusl9c$ltt$1@dough.gmane.org>

Tidal Espeon wrote:

> I need help with installing this setup on my emacs:
> http://hide1713.wordpress.com/2009/01/30/setup-perfect-python-environment-
in-emacs/
> The problem is that I have no clue how to access any .emacs file or
> .emacs.d folder. I'm running linux, and they are apparently invisible in
> my home directory. Trying to create those makes linux tell me that they're
> already there. I've already installed the latest ropemacs, pyflakes, etc.
> I'd sincerely appreciate help, since the IDLE just doesn't cut it for me.

Files and directories whose name starts with a dot are hidden by default. 
You can make ls show them with the --all/-a option:

$ touch .name_that_startswith_a_dot
$ ls
$ ls -a
.  ..  .name_that_startswith_a_dot

Even though they aren't visible you can open and edit them like any other 
file, e. g. with emacs:

$ emacs -nw .name_that_startswith_a_dot



From davea at ieee.org  Mon Jul  4 17:00:32 2011
From: davea at ieee.org (Dave Angel)
Date: Mon, 04 Jul 2011 11:00:32 -0400
Subject: [Tutor] Blackjackbetting
In-Reply-To: <CA+=McKaR-yEpRcUv6LDR+cHmqHnbEY0FYrCTFUPrDfVeHSV_ow@mail.gmail.com>
References: <CA+=McKaR-yEpRcUv6LDR+cHmqHnbEY0FYrCTFUPrDfVeHSV_ow@mail.gmail.com>
Message-ID: <4E11D590.4010705@ieee.org>

On 01/-10/-28163 02:59 PM, David Merrick wrote:
> HI. I feel I'm starting to go round in circles solving this problem. I feel
> I made significant progress.
> Can someone help me iron out the bugs please
>
> # Blackjack
> # From 1 to 7 players compete against a dealer
>
> import cards, games
>
> class BJ_Card(cards.Card):
>      """ A Blackjack Card. """
>      ACE_VALUE = 1
>
>      @property
>      def value(self):
>          if self.is_face_up:
>              v = BJ_Card.RANKS.index(self.rank) + 1
>              if v>  10:
>                  v = 10
>          else:
>              v = None
>          return v
>
> class BJ_Deck(cards.Deck):
>      """ A Blackjack Deck. """
>      def populate(self):
>          for suit in BJ_Card.SUITS:
>              for rank in BJ_Card.RANKS:
>                  self.cards.append(BJ_Card(rank, suit))
>
>
> class BJ_Hand(cards.Hand):
>      """ A Blackjack Hand. """
>      def __init__(self, name):
>          super(BJ_Hand, self).__init__()
>          self.name = name
>
>      def __str__(self):
>          rep = self.name + ":\t" + super(BJ_Hand, self).__str__()
>          if self.total:
>              rep += "(" + str(self.total) + ")"
>          return rep
>
>      @property
>      def total(self):
>          # if a card in the hand has value of None, then total is None
>          for card in self.cards:
>              if not card.value:
>                  return None
>
>          # add up card values, treat each Ace as 1
>          t = 0
>          for card in self.cards:
>                t += card.value
>
>          # determine if hand contains an Ace
>          contains_ace = False
>          for card in self.cards:
>              if card.value == BJ_Card.ACE_VALUE:
>                  contains_ace = True
>
>          # if hand contains Ace and total is low enough, treat Ace as 11
>          if contains_ace and t<= 11:
>              # add only 10 since we've already added 1 for the Ace
>              t += 10
>
>          return t
>
>      def is_busted(self):
>          return self.total>  21
>
> class Bet(object):
>      """ A Blackjack Gamble. """
>      # Values
>      def __init__(bet, money = 10):
>          stash  = money
>
>      # Betting options
>      def betting(bet,stash):
>          try:
>              if stash>  0:
>                  wager = int(input("\nHow much do you want to wager?: "))
>                  if wager>  stash:
>                      int(input("\n You can only wager what you have. How
> much?: "))
>                  elif wager<  0:
>                      int(input("\n You can only wager what you have. How
> much?: "))
>          except ValueError:
>                  int(input("\n That's not valid! Choose a number: "))
>
>
>      # Money Conditions
>      def gamble(bet):
>          if bet.stash<= 0:
>              print("\nYou are out of money! You're out of the game!")
>
>
>
> class BJ_Player(BJ_Hand):
>      """ A Blackjack Player. """
>      stash = 10
>      if stash<= 0:
>               print("\nYou are out of money! You're out of the game!")
>
>      def is_hitting(self):
>          response = games.ask_yes_no("\n" + self.name + ", do you want a hit?
> (Y/N): ")
>          return response == "y"
>
>      def bust(self,stash,wager):
>          print(self.name, "busts.")
>          self.lose(self,stash,wager)
>
>      def lose(self,stash,wager):
>          print(self.name, "loses.")
>          stash = stash - wager
>          print("Your stash is: ",stash)
>          return stash
>
>      def win(self,stash,wager):
>          print(self.name, "wins.")
>          stash = stash + wager
>          print("Your stash is: ",stash)
>          return stash
>
>      def push(self):
>          print(self.name, "pushes.")
>
>
> class BJ_Dealer(BJ_Hand):
>      """ A Blackjack Dealer. """
>      def is_hitting(self):
>          return self.total<  17
>
>      def bust(self):
>          print(self.name, "busts.")
>
>      def flip_first_card(self):
>          first_card = self.cards[0]
>          first_card.flip()
>
>
> class BJ_Game(object):
>      """ A Blackjack Game. """
>      def __init__(self, names):
>          self.players = []
>          for name in names:
>              stash = 100
>              player = BJ_Player(name)
>              playerbet = Bet(stash).betting(stash)
>              self.players.append(player)
>
>          self.dealer = BJ_Dealer("Dealer")
>
>          self.deck = BJ_Deck()
>          self.deck.populate()
>          self.deck.shuffle()
>
>      @property
>      def still_playing(self):
>          sp = []
>          for player in self.players:
>              if not player.is_busted():
>                  sp.append(player)
>          return sp
>
>      def __additional_cards(self, player,stash,wager):
>          while not player.is_busted() and player.is_hitting():
>              self.deck.deal([player])
>              print(player)
>              if player.is_busted():
>                  player.bust(self,stash,wager)
>
>      def play(self,stash,wager):
>          # deal initial 2 cards to everyone
>          self.deck.deal(self.players + [self.dealer], per_hand = 2)
>          self.dealer.flip_first_card()    # hide dealer's first card
>          for player in self.players:
>              print(player)
>          print(self.dealer)
>
>          # deal additional cards to players
>          for player in self.players:
>              self.__additional_cards(player,stash,wager)
>
>          self.dealer.flip_first_card()    # reveal dealer's first
>
>          if not self.still_playing:
>              # since all players have busted, just show the dealer's hand
>              print(self.dealer)
>          else:
>              # deal additional cards to dealer
>              print(self.dealer)
>              self.__additional_cards(self.dealer,stash,wager)
>
>              if self.dealer.is_busted():
>                  # everyone still playing wins
>                  for player in self.still_playing:
>                      player.win(stash,wager)
>              else:
>                  # compare each player still playing to dealer
>                  for player in self.still_playing:
>                      if player.total>  self.dealer.total:
>                          player.win(stash,wager)
>                      elif player.total<  self.dealer.total:
>                          player.lose(stash,wager)
>                      else:
>                          player.push()
>
>          # remove everyone's cards
>          for player in self.players:
>              player.clear()
>          self.dealer.clear()
>
>
> def main():
>      print("\t\tWelcome to Blackjack!\n")
>      stash = 0
>      wager = 0
>      names = []
>      number = games.ask_number("How many players? (1 - 7): ", low = 1, high =
> 8)
>      for i in range(number):
>          name = input("Enter player name: ")
>          names.append(name)
>      print()
>
>      game = BJ_Game(names)
>
>      again = None
>      while again != "n":
>          game.play(stash,wager)
>          again = games.ask_yes_no("\nDo you want to play again?: ")
>
>
> main()
> input("\n\nPress the enter key to exit.")
>
> *Output*
>
> Welcome to Blackjack!
>
> How many players? (1 - 7): 1
> Enter player name: Dave
>
>
> How much do you want to wager?: 50
> Dave:    Qc    8s    (18)
> Dealer:    XX    3d
>
> Dave, do you want a hit? (Y/N): n
> Dealer:    Kd    3d    (13)
> Dealer:    Kd    3d    Qh    (23)
> Traceback (most recent call last):
>    File "I:/Python/Python Source Code/chapter09/blackjackBettingB.py", line
> 229, in<module>
>      main()
>    File "I:/Python/Python Source Code/chapter09/blackjackBettingB.py", line
> 225, in main
>      game.play(stash,wager)
>    File "I:/Python/Python Source Code/chapter09/blackjackBettingB.py", line
> 188, in play
>      self.__additional_cards(self.dealer,stash,wager)
>    File "I:/Python/Python Source Code/chapter09/blackjackBettingB.py", line
> 166, in __additional_cards
>      player.bust(self,stash,wager)
> TypeError: bust() takes exactly 1 positional argument (4 given)
>
It would appear from your filenaming that this program orginally came 
from some book.  Do you actually understand the version that the book 
used (which presumably worked) ?

Have you tried to analyze this program, to clean it up?  it'd be nice to 
know which parts were already there and which parts you added. Are you 
perhaps working from the book "Python Programming for the Absolute 
Beginner" by Dawson?

If I had to tackle this one blind, without its history, I'd start by 
making a diagram of the classes involved.  You have BJ_Player derived 
from BJ_Hand, which is another way of saying that a player is a kind of 
hand.  That makes no sense, so the code in those classes will make no 
sense.  It's not as clear whether a BJ_Dealer should be a kind of 
player.  Also, if you're working from the above book, Deck is already 
derived from Hand.

Inheritance usually expresses a "is a" kind of relationship.  So a 
Black-jack card is a card, a Black-jack deck is a deck.

On the other hand, instance attributes express a "has a" kind of 
relationship. A player has a hand, not is a hand.  So the hand should 
should be an attribute of the player.

Assuming that's the book you're using, why do you duplicate the populate 
method in BJ_Deck, when the base class already has the same code?

Why does a BJ_Hand need a name attribute?  Shouldn't a name be an 
attribute of a player?  I think this is a side effect of pretending that 
a player is a hand.

I can't figure out what the Bet class is all about.

The BJ_Player class starts with a class attribute stash.  But presumably 
you should have a separate stash for each player.  Where's the __init__ 
method?  That's presumably where you should associate a name and stash 
with a particular player?

In BJ_Game.play(), you call   player.win(), passing stash in.  But stash 
is a simple local, so its value is shared among all players.

And so on.  You need to figure out what each class is going to be, which 
ones have 'is a' relationships, and which ones have 'has a' 
relationships.  Then you need to decide what each class instance is 
going to store, and make sure it's done explicitly in the __init__ for 
that class.  If there's some reason the __init__() can't initialize one 
of its values, then put a comment there, listing it at least.   And 
while you're learning, you should avoid having four symbols with the 
same name, but having different scopes, lifetimes, and purposes.  For 
example, 'stash'.

Some of these suggestions are already contradicted by the book you're 
using.  For example, a Deck knows how to deal to a list of hands.  But 
you have a list of players which shouldn't be the same thing.  There are 
various ways of solving that.

DaveA








From alan.gauld at btinternet.com  Tue Jul  5 00:59:48 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 4 Jul 2011 23:59:48 +0100
Subject: [Tutor] Help with making emacs work with python syntax checking?
References: <CAE3a9fKaKK8hm5XP+jEfTUDB_GkzTBmjXbntZ56Ju2P=y1uA=g@mail.gmail.com>
Message-ID: <iutglc$oq3$1@dough.gmane.org>

"Tidal Espeon" <tidal.espeon at gmail.com> wrote 

>I need help with installing this setup on my emacs:

Why do you want this? Are you already an emacs 
user? If so then fine, go ahead. But if you do not 
already use emacs, lerarning it will be a big effort. 
emacs is a big, powerful tool and once you know 
it you can use it for almost everything. But its not 
something you can learn to use quickly.

> The problem is that I have no clue how to 
> access any .emacs file or .emacs.d

Which strongly suggests you are not n emacs regular. 
If you were you would be editing .emacs regularly!

> the IDLE just doesn't cut it for me.

There are lots of other development enmvirobnments around.
If you are a typical GUI user, which it sounds as if you are, 
then a tool liker Eclipse, (or maybe Blackadder or .Wing or SPE)
might be more appropriate. They are powerful but GUI 
oriented rather than command oriented.

Frankly if you are not already an emacs user, or unless 
you want to make emacs you standard environment 
in the future and will spend the time changing your 
computing habits to suit emacs, I'd give up and find 
a more GUI friendly tool set!

And I say that as someone who is an emacs (and vim) user!
emacs is a powerful tool and a great programmer's 
environment, but it's not for the faint hearted.

HTH,

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



From eire1130 at gmail.com  Tue Jul  5 02:15:42 2011
From: eire1130 at gmail.com (eire1130 at gmail.com)
Date: Tue, 5 Jul 2011 00:15:42 +0000
Subject: [Tutor] Help with making emacs work with python syntax checking?
In-Reply-To: <iutglc$oq3$1@dough.gmane.org>
References: <CAE3a9fKaKK8hm5XP+jEfTUDB_GkzTBmjXbntZ56Ju2P=y1uA=g@mail.gmail.com><iutglc$oq3$1@dough.gmane.org>
Message-ID: <1860727264-1309824943-cardhu_decombobulator_blackberry.rim.net-1341160846-@b1.c28.bise6.blackberry>

I second this.

I have a second harddrive with Mint on it. Ithought it might be fun to learn emacs. On windows I've been using eclipse for like 6 to 12 months or however long ago I started.

I tried emacs for about two seconds and was like, uh no thanks. Downloaded and set up eclipse and I'm still happy. Other than it took too long to set up in mint

Bonus is I can use it django as well.


Sent from my Verizon Wireless BlackBerry

-----Original Message-----
From: "Alan Gauld" <alan.gauld at btinternet.com>
Sender: tutor-bounces+eire1130=gmail.com at python.org
Date: Mon, 4 Jul 2011 23:59:48 
To: <tutor at python.org>
Subject: Re: [Tutor] Help with making emacs work with python syntax checking?

"Tidal Espeon" <tidal.espeon at gmail.com> wrote 

>I need help with installing this setup on my emacs:

Why do you want this? Are you already an emacs 
user? If so then fine, go ahead. But if you do not 
already use emacs, lerarning it will be a big effort. 
emacs is a big, powerful tool and once you know 
it you can use it for almost everything. But its not 
something you can learn to use quickly.

> The problem is that I have no clue how to 
> access any .emacs file or .emacs.d

Which strongly suggests you are not n emacs regular. 
If you were you would be editing .emacs regularly!

> the IDLE just doesn't cut it for me.

There are lots of other development enmvirobnments around.
If you are a typical GUI user, which it sounds as if you are, 
then a tool liker Eclipse, (or maybe Blackadder or .Wing or SPE)
might be more appropriate. They are powerful but GUI 
oriented rather than command oriented.

Frankly if you are not already an emacs user, or unless 
you want to make emacs you standard environment 
in the future and will spend the time changing your 
computing habits to suit emacs, I'd give up and find 
a more GUI friendly tool set!

And I say that as someone who is an emacs (and vim) user!
emacs is a powerful tool and a great programmer's 
environment, but it's not for the faint hearted.

HTH,

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


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

From samudhio at gmail.com  Tue Jul  5 02:16:06 2011
From: samudhio at gmail.com (Edgar Almonte)
Date: Mon, 4 Jul 2011 20:16:06 -0400
Subject: [Tutor] serial device emulator
Message-ID: <CAH0g_ayz4No3p0Y5-qiguqiqntKXPLxg1M5iXom5j9kHF0DDdQ@mail.gmail.com>

Hello list need some advice/help with something, i am doing a program
in python that send some command via serial to a device so far so good
, the thing is not have the program so i need make another program
that emulate the behavior of this serial device ( is quiet simple ) to
test my app
i read abou that i can use pseudo terminal in linux but not sure how
attatch the pseudo terminal /dev/pts5 example to a fake_device.py file
or something like that.

maybe this question is not so python but i will appreciate some help.


Thanks

From cfuller084 at thinkingplanet.net  Tue Jul  5 02:49:53 2011
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Mon, 4 Jul 2011 19:49:53 -0500
Subject: [Tutor] serial device emulator
In-Reply-To: <CAH0g_ayz4No3p0Y5-qiguqiqntKXPLxg1M5iXom5j9kHF0DDdQ@mail.gmail.com>
References: <CAH0g_ayz4No3p0Y5-qiguqiqntKXPLxg1M5iXom5j9kHF0DDdQ@mail.gmail.com>
Message-ID: <201107041949.58000.cfuller084@thinkingplanet.net>


You don't need to emulate a serial port (since you're writing the code; you'd 
have to emulate the port if it was standalone software), only your serial port 
library.  Write a class that has the same methods as the serial port library 
you're using (you only need the methods you're using or think you might use 
later), and fill them in with the appropriate code so it behaves like your real 
device.

Cheers

On Monday 04 July 2011, Edgar Almonte wrote:
> Hello list need some advice/help with something, i am doing a program
> in python that send some command via serial to a device so far so good
> , the thing is not have the program so i need make another program
> that emulate the behavior of this serial device ( is quiet simple ) to
> test my app
> i read abou that i can use pseudo terminal in linux but not sure how
> attatch the pseudo terminal /dev/pts5 example to a fake_device.py file
> or something like that.
> 
> maybe this question is not so python but i will appreciate some help.
> 
> 
> Thanks
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From samudhio at gmail.com  Tue Jul  5 14:03:29 2011
From: samudhio at gmail.com (Edgar Almonte)
Date: Tue, 5 Jul 2011 08:03:29 -0400
Subject: [Tutor] serial device emulator
In-Reply-To: <201107041949.58000.cfuller084@thinkingplanet.net>
References: <CAH0g_ayz4No3p0Y5-qiguqiqntKXPLxg1M5iXom5j9kHF0DDdQ@mail.gmail.com>
	<201107041949.58000.cfuller084@thinkingplanet.net>
Message-ID: <CAH0g_ayRyBvn68HMHFuO6_Ze8pY1n2m+u5F8bqg+WNAQcGT4LA@mail.gmail.com>

thanks chirs but i think  i don't follow you , can you elaborate more ?

Thanks

On Mon, Jul 4, 2011 at 8:49 PM, Chris Fuller
<cfuller084 at thinkingplanet.net> wrote:
>
> You don't need to emulate a serial port (since you're writing the code; you'd
> have to emulate the port if it was standalone software), only your serial port
> library. ?Write a class that has the same methods as the serial port library
> you're using (you only need the methods you're using or think you might use
> later), and fill them in with the appropriate code so it behaves like your real
> device.
>
> Cheers
>
> On Monday 04 July 2011, Edgar Almonte wrote:
>> Hello list need some advice/help with something, i am doing a program
>> in python that send some command via serial to a device so far so good
>> , the thing is not have the program so i need make another program
>> that emulate the behavior of this serial device ( is quiet simple ) to
>> test my app
>> i read abou that i can use pseudo terminal in linux but not sure how
>> attatch the pseudo terminal /dev/pts5 example to a fake_device.py file
>> or something like that.
>>
>> maybe this question is not so python but i will appreciate some help.
>>
>>
>> Thanks
>> _______________________________________________
>> Tutor maillist ?- ?Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From adam.jtm30 at gmail.com  Tue Jul  5 14:18:27 2011
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Tue, 05 Jul 2011 13:18:27 +0100
Subject: [Tutor] serial device emulator
In-Reply-To: <CAH0g_ayRyBvn68HMHFuO6_Ze8pY1n2m+u5F8bqg+WNAQcGT4LA@mail.gmail.com>
References: <CAH0g_ayz4No3p0Y5-qiguqiqntKXPLxg1M5iXom5j9kHF0DDdQ@mail.gmail.com>	<201107041949.58000.cfuller084@thinkingplanet.net>
	<CAH0g_ayRyBvn68HMHFuO6_Ze8pY1n2m+u5F8bqg+WNAQcGT4LA@mail.gmail.com>
Message-ID: <4E130113.8070605@gmail.com>

What Chris is getting at is that you'll use some module, eg pyserial, to 
interface with the serial port. So if you write a little module that has 
the same interface then you can pretend you have a serial port attached 
device and then switch over to an actual one without changing anything 
else in your code but the import.

## myserial.py ##
class Serial:
     def __init__(self, port=None):
         pass
     def open(self):
         pass
     def close():
         pass
     def read(size=1):
         return 'a' * size
     def write(data):
         return len(data)
#####

## foo.py ##
import myserial as serial
#import serial ## Use this in production

port = serial.Serial()
port.open()
print port.write("hello, world")
print port.read(3)
####

I hope that makes it clearer to you.
Adam.
P.S. none of that code has been tested


On 05/07/11 13:03, Edgar Almonte wrote:
> thanks chirs but i think  i don't follow you , can you elaborate more ?
>
> Thanks
>
> On Mon, Jul 4, 2011 at 8:49 PM, Chris Fuller
> <cfuller084 at thinkingplanet.net>  wrote:
>> You don't need to emulate a serial port (since you're writing the code; you'd
>> have to emulate the port if it was standalone software), only your serial port
>> library.  Write a class that has the same methods as the serial port library
>> you're using (you only need the methods you're using or think you might use
>> later), and fill them in with the appropriate code so it behaves like your real
>> device.
>>
>> Cheers
>>
>> On Monday 04 July 2011, Edgar Almonte wrote:
>>> Hello list need some advice/help with something, i am doing a program
>>> in python that send some command via serial to a device so far so good
>>> , the thing is not have the program so i need make another program
>>> that emulate the behavior of this serial device ( is quiet simple ) to
>>> test my app
>>> i read abou that i can use pseudo terminal in linux but not sure how
>>> attatch the pseudo terminal /dev/pts5 example to a fake_device.py file
>>> or something like that.
>>>
>>> maybe this question is not so python but i will appreciate some help.
>>>
>>>
>>> Thanks
>>> _______________________________________________
>>> Tutor maillist  -  Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

From samudhio at gmail.com  Tue Jul  5 14:20:36 2011
From: samudhio at gmail.com (Edgar Almonte)
Date: Tue, 5 Jul 2011 08:20:36 -0400
Subject: [Tutor] serial device emulator
In-Reply-To: <4E130113.8070605@gmail.com>
References: <CAH0g_ayz4No3p0Y5-qiguqiqntKXPLxg1M5iXom5j9kHF0DDdQ@mail.gmail.com>
	<201107041949.58000.cfuller084@thinkingplanet.net>
	<CAH0g_ayRyBvn68HMHFuO6_Ze8pY1n2m+u5F8bqg+WNAQcGT4LA@mail.gmail.com>
	<4E130113.8070605@gmail.com>
Message-ID: <CAH0g_aziXk52CoLSK7x2V_bUtu8-DCSv7PDyYbAiH_qgbAck5g@mail.gmail.com>

got it , thanks a lot

On Tue, Jul 5, 2011 at 8:18 AM, Adam Bark <adam.jtm30 at gmail.com> wrote:
> What Chris is getting at is that you'll use some module, eg pyserial, to
> interface with the serial port. So if you write a little module that has the
> same interface then you can pretend you have a serial port attached device
> and then switch over to an actual one without changing anything else in your
> code but the import.
>
> ## myserial.py ##
> class Serial:
> ? ?def __init__(self, port=None):
> ? ? ? ?pass
> ? ?def open(self):
> ? ? ? ?pass
> ? ?def close():
> ? ? ? ?pass
> ? ?def read(size=1):
> ? ? ? ?return 'a' * size
> ? ?def write(data):
> ? ? ? ?return len(data)
> #####
>
> ## foo.py ##
> import myserial as serial
> #import serial ## Use this in production
>
> port = serial.Serial()
> port.open()
> print port.write("hello, world")
> print port.read(3)
> ####
>
> I hope that makes it clearer to you.
> Adam.
> P.S. none of that code has been tested
>
>
> On 05/07/11 13:03, Edgar Almonte wrote:
>>
>> thanks chirs but i think ?i don't follow you , can you elaborate more ?
>>
>> Thanks
>>
>> On Mon, Jul 4, 2011 at 8:49 PM, Chris Fuller
>> <cfuller084 at thinkingplanet.net> ?wrote:
>>>
>>> You don't need to emulate a serial port (since you're writing the code;
>>> you'd
>>> have to emulate the port if it was standalone software), only your serial
>>> port
>>> library. ?Write a class that has the same methods as the serial port
>>> library
>>> you're using (you only need the methods you're using or think you might
>>> use
>>> later), and fill them in with the appropriate code so it behaves like
>>> your real
>>> device.
>>>
>>> Cheers
>>>
>>> On Monday 04 July 2011, Edgar Almonte wrote:
>>>>
>>>> Hello list need some advice/help with something, i am doing a program
>>>> in python that send some command via serial to a device so far so good
>>>> , the thing is not have the program so i need make another program
>>>> that emulate the behavior of this serial device ( is quiet simple ) to
>>>> test my app
>>>> i read abou that i can use pseudo terminal in linux but not sure how
>>>> attatch the pseudo terminal /dev/pts5 example to a fake_device.py file
>>>> or something like that.
>>>>
>>>> maybe this question is not so python but i will appreciate some help.
>>>>
>>>>
>>>> Thanks
>>>> _______________________________________________
>>>> Tutor maillist ?- ?Tutor at python.org
>>>> To unsubscribe or change subscription options:
>>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>> _______________________________________________
>>> Tutor maillist ?- ?Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>> _______________________________________________
>> Tutor maillist ?- ?Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From sulinet at postafiok.hu  Tue Jul  5 18:39:08 2011
From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=)
Date: Tue, 5 Jul 2011 18:39:08 +0200
Subject: [Tutor] Using a dict value in the same dict
Message-ID: <CAC2EUKK9KcY05qbvkbiP=66nrHQTH_-aBMVCQ_a+CnZ8um0Vmg@mail.gmail.com>

Hi,

I have a dictionary with the keys 'a' and 'b'. It is not in a class. (I know
that everything is in a class, but not explicitly.)
May I use the value of 'a' when defining the value of 'b'? If so, what is
the syntax?

Thx,
P?ter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110705/0099913b/attachment.html>

From enalicho at gmail.com  Tue Jul  5 18:52:13 2011
From: enalicho at gmail.com (Noah Hall)
Date: Tue, 5 Jul 2011 17:52:13 +0100
Subject: [Tutor] Using a dict value in the same dict
In-Reply-To: <CAC2EUKK9KcY05qbvkbiP=66nrHQTH_-aBMVCQ_a+CnZ8um0Vmg@mail.gmail.com>
References: <CAC2EUKK9KcY05qbvkbiP=66nrHQTH_-aBMVCQ_a+CnZ8um0Vmg@mail.gmail.com>
Message-ID: <CAOv69saGk8Wme98gGpH+_ZmFqsY+vrhHyXob0jR1J4seOg1MbQ@mail.gmail.com>

2011/7/5 V?las P?ter <sulinet at postafiok.hu>:
> Hi,
>
> I have a dictionary with the keys 'a' and 'b'. It is not in a class. (I know
> that everything is in a class, but not explicitly.)
> May I use the value of 'a' when defining the value of 'b'? If so, what is
> the syntax?

Yes. The syntax is the same as anything involving a dict -

>>> a_dict = dict()
>>> a_dict['a'] = 2
>>> a_dict['b'] = a_dict['a'] + 1
>>> a_dict
{'a': 2, 'b': 3}

From __peter__ at web.de  Tue Jul  5 19:04:24 2011
From: __peter__ at web.de (Peter Otten)
Date: Tue, 05 Jul 2011 19:04:24 +0200
Subject: [Tutor] Using a dict value in the same dict
References: <CAC2EUKK9KcY05qbvkbiP=66nrHQTH_-aBMVCQ_a+CnZ8um0Vmg@mail.gmail.com>
Message-ID: <iuvg6c$k8r$1@dough.gmane.org>

V?las P?ter wrote:

> I have a dictionary with the keys 'a' and 'b'. It is not in a class. (I
> know that everything is in a class, but not explicitly.)
> May I use the value of 'a' when defining the value of 'b'? If so, what is
> the syntax?

>>> d = {}
>>> d["a"] = 1
>>> d["b"] = d["a"] + 1
>>> d
{'a': 1, 'b': 2}

If you want the value of "b" updated whenever d["a"] changes, i. e. that the 
dict values behave like spreadsheet cells, that is not possible with a 
standard python dictionary. 
There is a recipe by Raymond Hettinger with a simple implementation of that 
behaviour at

http://code.activestate.com/recipes/355045-spreadsheet/

As it uses eval() it is OK for private use, but you shouldn't allow a 
potentially malicious user to run it.



From alan.gauld at btinternet.com  Tue Jul  5 19:42:26 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 5 Jul 2011 18:42:26 +0100
Subject: [Tutor] Using a dict value in the same dict
References: <CAC2EUKK9KcY05qbvkbiP=66nrHQTH_-aBMVCQ_a+CnZ8um0Vmg@mail.gmail.com>
Message-ID: <iuviea$4ib$1@dough.gmane.org>


"V?las P?ter" <sulinet at postafiok.hu> wrote

> I have a dictionary with the keys 'a' and 'b'. It is not in a class.
> May I use the value of 'a' when defining the value of 'b'?
> If so, what is the syntax?

single = {'a': 1,
                'b': 2
               }
double = { 'a': single['a'] *2,
                   'b' : single['b'] * 2
                 }

single['c'] = 3
double['c'] = single['c'] * 2

Does that help?
Is that what you mean?

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



From sulinet at postafiok.hu  Tue Jul  5 19:42:45 2011
From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=)
Date: Tue, 5 Jul 2011 19:42:45 +0200
Subject: [Tutor] Using a dict value in the same dict
In-Reply-To: <iuvg6c$k8r$1@dough.gmane.org>
References: <CAC2EUKK9KcY05qbvkbiP=66nrHQTH_-aBMVCQ_a+CnZ8um0Vmg@mail.gmail.com>
	<iuvg6c$k8r$1@dough.gmane.org>
Message-ID: <CAC2EUKK9ZJbHutgit5vr9UZW-KdFJ9ruH-toziWVSneF6jUssg@mail.gmail.com>

So the trick is to define the dictionary in separate sessions, not at once.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110705/36682829/attachment.html>

From wprins at gmail.com  Tue Jul  5 21:40:13 2011
From: wprins at gmail.com (Walter Prins)
Date: Tue, 5 Jul 2011 20:40:13 +0100
Subject: [Tutor] Using a dict value in the same dict
In-Reply-To: <CAC2EUKK9ZJbHutgit5vr9UZW-KdFJ9ruH-toziWVSneF6jUssg@mail.gmail.com>
References: <CAC2EUKK9KcY05qbvkbiP=66nrHQTH_-aBMVCQ_a+CnZ8um0Vmg@mail.gmail.com>
	<iuvg6c$k8r$1@dough.gmane.org>
	<CAC2EUKK9ZJbHutgit5vr9UZW-KdFJ9ruH-toziWVSneF6jUssg@mail.gmail.com>
Message-ID: <CANLXbfBJVDTYYJLDXYiU3U9Ciyuf0FhhNn3Qjt+o2h4f1SN1bw@mail.gmail.com>

Hi,

7/5 V?las P?ter <sulinet at postafiok.hu>

> So the trick is to define the dictionary in separate sessions, not at once.
>

What do you mean, "seperate sessions, not at once"?

W
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110705/e3c144c9/attachment.html>

From swiftone at swiftone.org  Tue Jul  5 22:01:47 2011
From: swiftone at swiftone.org (Brett Ritter)
Date: Tue, 5 Jul 2011 16:01:47 -0400
Subject: [Tutor] Using a dict value in the same dict
In-Reply-To: <CANLXbfBJVDTYYJLDXYiU3U9Ciyuf0FhhNn3Qjt+o2h4f1SN1bw@mail.gmail.com>
References: <CAC2EUKK9KcY05qbvkbiP=66nrHQTH_-aBMVCQ_a+CnZ8um0Vmg@mail.gmail.com>
	<iuvg6c$k8r$1@dough.gmane.org>
	<CAC2EUKK9ZJbHutgit5vr9UZW-KdFJ9ruH-toziWVSneF6jUssg@mail.gmail.com>
	<CANLXbfBJVDTYYJLDXYiU3U9Ciyuf0FhhNn3Qjt+o2h4f1SN1bw@mail.gmail.com>
Message-ID: <CAMb349yZ0dHjqkVMjL83O0=UHjvahef+aJwTPM7E5dvzgApMVw@mail.gmail.com>

On Tue, Jul 5, 2011 at 3:40 PM, Walter Prins <wprins at gmail.com> wrote:
>> So the trick is to define the dictionary in separate sessions, not at
>> once.
>
> What do you mean, "seperate sessions, not at once"?

He means you can't say:

d = {a: "1", b: d["a"]}

Which is correct.  To set one value based on another they must be set
separately.

-- 
Brett Ritter / SwiftOne
swiftone at swiftone.org

From lisi.reisz at gmail.com  Wed Jul  6 00:01:01 2011
From: lisi.reisz at gmail.com (Lisi)
Date: Tue, 5 Jul 2011 23:01:01 +0100
Subject: [Tutor] broken script
Message-ID: <201107052301.01246.lisi.reisz@gmail.com>

I am copy-typing the following pre-written program:

def break_words(stuff):
    """This function will break up words for us."""
    words=stuff.split(' ')
    return words
    
def sort_words(words):
    """Sorts the words."""
    return sorted(words)

def print_first_word(words):
    """Prints the first word after popping it off."""
    word=words.pop(0)
    print word

I am testing at the end of each section as I type it.  As far as line 9 it was 
fine - but, once I have typed up to line 14, it jibs at line 10 with the 
following error message:
    
lisi at Tux:~/Python/LearnPythonTheHardWay$ python ex26.py
  File "ex26.py", line 10
    def print_first_word(words)
                              ^
SyntaxError: invalid syntax
lisi at Tux:~/Python/LearnPythonTheHardWay$

(The caret should be under the closing bracket at the end of the line in which 
it is the penultimate character.)  I have deleted and re-copy-typed the end 
of the line repeatedly.  In despair, I deleted the end of the line and copied 
and pasted the end of line 6 into it.  I have checked and rechecked for  
incorrect white-space.  I can find nothing wrong.  I have copy-pasted it into 
a WP just to make the non-printing characters visible.  I can still see 
nothing wrong.  Why is line 6 fine and line 10 a disaster?  I can see no 
difference in the syntax, though there must clearly be one. :-(

I am at a loss as to what to do next.  (It is the next exercise that is 
supposed to have errors in for us to put right!!!)

Pointers in the right direction very gratefully received!

Thanks, 
Lisi


From martin at linux-ip.net  Wed Jul  6 00:23:41 2011
From: martin at linux-ip.net (Martin A. Brown)
Date: Wed, 6 Jul 2011 00:23:41 +0200
Subject: [Tutor] broken script
In-Reply-To: <201107052301.01246.lisi.reisz@gmail.com>
References: <201107052301.01246.lisi.reisz@gmail.com>
Message-ID: <alpine.LNX.2.00.1107060018180.19174@octothorpe.wonderfrog.net>


Hello,

 : I am copy-typing the following pre-written program:
 : 
 : def break_words(stuff):
 :     """This function will break up words for us."""
 :     words=stuff.split(' ')
 :     return words
 :     
 : def sort_words(words):
 :     """Sorts the words."""
 :     return sorted(words)
 : 
 : def print_first_word(words):
 :     """Prints the first word after popping it off."""
 :     word=words.pop(0)
 :     print word
 : 
 : I am testing at the end of each section as I type it.  As far as line 9 it was 
 : fine - but, once I have typed up to line 14, it jibs at line 10 with the 
 : following error message:
 :     
 : lisi at Tux:~/Python/LearnPythonTheHardWay$ python ex26.py
 :   File "ex26.py", line 10
 :     def print_first_word(words)
 :                               ^
 : SyntaxError: invalid syntax
 : lisi at Tux:~/Python/LearnPythonTheHardWay$

Look at the error.  Look at the error carefully.

Look at the definitions of your other functions....

Compare.  What is different?

          do you see the colon?
                        |
                        V
def silly_function(args):

Curiously, the sample that you pasted above has the required colon 
at the end of the line which starts the function definition.

 : def print_first_word(words):
 :     """Prints the first word after popping it off."""
 :     word=words.pop(0)
 :     print word

I have heard people express frustration many times about how a 
program(ming language) or "the computer" did not understand 
something because the thing was 'missing a damned semicolon'.  

Unfortunately, these syntactical rules are quite important to our 
very fast, but not terribly intuitive friends of silicon.

 : (The caret should be under the closing bracket at the end of the 
 : line in which it is the penultimate character.)  I have deleted 
 : and re-copy-typed the end of the line repeatedly.  In despair, I 
 : deleted the end of the line and copied and pasted the end of line 
 : 6 into it.  I have checked and rechecked for incorrect 
 : white-space.  I can find nothing wrong.  I have copy-pasted it 
 : into a WP just to make the non-printing characters visible.  I 
 : can still see nothing wrong.  Why is line 6 fine and line 10 a 
 : disaster?  I can see no difference in the syntax, though there 
 : must clearly be one. :-(
 : 
 : I am at a loss as to what to do next.  (It is the next exercise 
 : that is supposed to have errors in for us to put right!!!)
 : 
 : Pointers in the right direction very gratefully received!

Try again, keep with it, and recognize that these beasties are 
awfully particular in what they accept.  And, for good reason.

Best of luck, Lisi,

-Martin

-- 
Martin A. Brown
http://linux-ip.net/

From steve at pearwood.info  Wed Jul  6 00:27:38 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 06 Jul 2011 08:27:38 +1000
Subject: [Tutor] Using a dict value in the same dict
In-Reply-To: <CAC2EUKK9ZJbHutgit5vr9UZW-KdFJ9ruH-toziWVSneF6jUssg@mail.gmail.com>
References: <CAC2EUKK9KcY05qbvkbiP=66nrHQTH_-aBMVCQ_a+CnZ8um0Vmg@mail.gmail.com>	<iuvg6c$k8r$1@dough.gmane.org>
	<CAC2EUKK9ZJbHutgit5vr9UZW-KdFJ9ruH-toziWVSneF6jUssg@mail.gmail.com>
Message-ID: <4E138FDA.6090601@pearwood.info>

V?las P?ter wrote:
> So the trick is to define the dictionary in separate sessions, not at once.

No.


value = 42
my_dict = {'a': value, 'b': value, 'c': 23, 'd': value, 'e': 97}

will work fine too.



-- 
Steven


From marc.tompkins at gmail.com  Wed Jul  6 00:58:04 2011
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Tue, 5 Jul 2011 15:58:04 -0700
Subject: [Tutor] broken script
In-Reply-To: <alpine.LNX.2.00.1107060018180.19174@octothorpe.wonderfrog.net>
References: <201107052301.01246.lisi.reisz@gmail.com>
	<alpine.LNX.2.00.1107060018180.19174@octothorpe.wonderfrog.net>
Message-ID: <CAKK8jXYzguajUXEtphX2bLB=QyF9N42K_kg3q7P0iC-UvD8=sg@mail.gmail.com>

On Tue, Jul 5, 2011 at 3:23 PM, Martin A. Brown <martin at linux-ip.net> wrote:

> I have heard people express frustration many times about how a
> program(ming language) or "the computer" did not understand
> something because the thing was 'missing a damned semicolon'.
>
> Unfortunately, these syntactical rules are quite important to our
> very fast, but not terribly intuitive friends of silicon.
>
>
I really hate this dumb machine;
I wish that they would sell it.
It never does just what I want -
but only what I tell it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110705/80a7fc5f/attachment-0001.html>

From ajarncolin at gmail.com  Wed Jul  6 15:28:26 2011
From: ajarncolin at gmail.com (col speed)
Date: Wed, 6 Jul 2011 20:28:26 +0700
Subject: [Tutor] Help with making emacs work with python syntax checking?
In-Reply-To: <1860727264-1309824943-cardhu_decombobulator_blackberry.rim.net-1341160846-@b1.c28.bise6.blackberry>
References: <CAE3a9fKaKK8hm5XP+jEfTUDB_GkzTBmjXbntZ56Ju2P=y1uA=g@mail.gmail.com>
	<iutglc$oq3$1@dough.gmane.org>
	<1860727264-1309824943-cardhu_decombobulator_blackberry.rim.net-1341160846-@b1.c28.bise6.blackberry>
Message-ID: <CAKLa6jShkZQHDZwQf34r1=-0=3+HSQfMTHg5Hs8XDZ7PQ-VDqA@mail.gmail.com>

On 5 July 2011 07:15, <eire1130 at gmail.com> wrote:

> I second this.
>
> I have a second harddrive with Mint on it. Ithought it might be fun to
> learn emacs. On windows I've been using eclipse for like 6 to 12 months or
> however long ago I started.
>
> I tried emacs for about two seconds and was like, uh no thanks. Downloaded
> and set up eclipse and I'm still happy. Other than it took too long to set
> up in mint
>
> Bonus is I can use it django as well.
>
>
> Sent from my Verizon Wireless BlackBerry
>
> -----Original Message-----
> From: "Alan Gauld" <alan.gauld at btinternet.com>
> Sender: tutor-bounces+eire1130=gmail.com at python.org
> Date: Mon, 4 Jul 2011 23:59:48
> To: <tutor at python.org>
> Subject: Re: [Tutor] Help with making emacs work with python syntax
> checking?
>
> "Tidal Espeon" <tidal.espeon at gmail.com> wrote
>
> >I need help with installing this setup on my emacs:
>
> Why do you want this? Are you already an emacs
> user? If so then fine, go ahead. But if you do not
> already use emacs, lerarning it will be a big effort.
> emacs is a big, powerful tool and once you know
> it you can use it for almost everything. But its not
> something you can learn to use quickly.
>
> > The problem is that I have no clue how to
> > access any .emacs file or .emacs.d
>
> Which strongly suggests you are not n emacs regular.
> If you were you would be editing .emacs regularly!
>
> > the IDLE just doesn't cut it for me.
>
> There are lots of other development enmvirobnments around.
> If you are a typical GUI user, which it sounds as if you are,
> then a tool liker Eclipse, (or maybe Blackadder or .Wing or SPE)
> might be more appropriate. They are powerful but GUI
> oriented rather than command oriented.
>
> Frankly if you are not already an emacs user, or unless
> you want to make emacs you standard environment
> in the future and will spend the time changing your
> computing habits to suit emacs, I'd give up and find
> a more GUI friendly tool set!
>
> And I say that as someone who is an emacs (and vim) user!
> emacs is a powerful tool and a great programmer's
> environment, but it's not for the faint hearted.
>
> HTH,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

To find hidden files on Linux(well Ubuntu anyway), navigate to the directory
and press ctrl+H. Open and change at your peril!

--
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110706/66530b7b/attachment.html>

From lisi.reisz at gmail.com  Wed Jul  6 23:57:25 2011
From: lisi.reisz at gmail.com (Lisi)
Date: Wed, 6 Jul 2011 22:57:25 +0100
Subject: [Tutor] broken script - curiouser and curiouser
In-Reply-To: <alpine.LNX.2.00.1107060018180.19174@octothorpe.wonderfrog.net>
References: <201107052301.01246.lisi.reisz@gmail.com>
	<alpine.LNX.2.00.1107060018180.19174@octothorpe.wonderfrog.net>
Message-ID: <201107062257.25472.lisi.reisz@gmail.com>

Thanks very much Martin.  I did "solve" the problem after you kindly emailed - 
but the solution has puzzled me more that the original problem.

On Tuesday 05 July 2011 23:23:41 Martin wrote:
>  : lisi at Tux:~/Python/LearnPythonTheHardWay$ python ex26.py
>  :   File "ex26.py", line 10
>  :     def print_first_word(words)
>  :                               ^
>  : SyntaxError: invalid syntax
>  : lisi at Tux:~/Python/LearnPythonTheHardWay$
>
> Look at the error.  Look at the error carefully.
>
> Look at the definitions of your other functions....
>
> Compare.  What is different?

I could see nothing that was different.

>           do you see the colon?

Yes - it was one of the first things I looked for when the error came up (that 
and check that the brackets were right).  It was there in what seemed to me 
to be the right position.
>              
> def silly_function(args):
>
> Curiously, the sample that you pasted above has the required colon
> at the end of the line which starts the function definition.
>
>  : def print_first_word(words):
>  :     """Prints the first word after popping it off."""
>  :     word=words.pop(0)
>  :     print word
>
> I have heard people express frustration many times about how a
> program(ming language) or "the computer" did not understand
> something because the thing was 'missing a damned semicolon'.

 I know that the smallest difference matters when dealing with a computer but 
could - and can - find none.

> Try again, keep with it, and recognize that these beasties are
> awfully particular in what they accept.  And, for good reason.

I have no difficulty with the fact that computers are literal minded.  They 
are after all, machines.  But "try again" was obviously great advice, and you 
had given me the push I needed to try again when I had given up.  

In the end, having tried absolutely everything else I could think of, and 
given that the error arose at the closing bracket at the end of line 10, I 
tried the only thing I could remotely think of that I hadn't tried and put a 
space in between the second bracket and the colon - and the wretched thing 
ran.  So I altered line six in the same way - and that still ran.  So line 
six will run either with or without the space.  I then typed the next 2 
sections in, and they ran, like line 6, either with or without the space.

So line 10 needs a space and the other sections are happy either with or 
without.  And they all have """ at the beginning of the next line.

You could obviously see something wrong that I had continued, and continue, to 
miss, and I have still not found it.  Hitting on the "right" solution almost 
by serendipity doesn't really count as seeing something wrong!!

> Best of luck, Lisi,

Thanks again very much Martin.  You really encouraged me.  

I am obviously not going to get any further now, I am so bogged down in the 
whole thing.  So I think that I may need to pass on and come back to it 
later.

Lisi

From alan.gauld at btinternet.com  Thu Jul  7 01:48:24 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 7 Jul 2011 00:48:24 +0100
Subject: [Tutor] broken script - curiouser and curiouser
References: <201107052301.01246.lisi.reisz@gmail.com><alpine.LNX.2.00.1107060018180.19174@octothorpe.wonderfrog.net>
	<201107062257.25472.lisi.reisz@gmail.com>
Message-ID: <iv2s8i$h1p$1@dough.gmane.org>


"Lisi" <lisi.reisz at gmail.com> wrote 

>>  :   File "ex26.py", line 10
>>  :     def print_first_word(words)
>>  :                               ^
>>  : SyntaxError: invalid syntax
>>  : lisi at Tux:~/Python/LearnPythonTheHardWay$
>>
>> Look at the error.  Look at the error carefully.
>>
> I could see nothing that was different.

The error report says you had no colon in your code.
Python couldn't see it...

Are you sutre you didn't add it before posting but 
after running the code?

Or are you testing it by impotrting a module? 
In that case the interpreter may still be using 
the old version because you haven't reloaded 
the updated version?

> Yes - it was one of the first things I looked for when 
> the error came up (that and check that the brackets 
> were right).  It was there in what seemed to me 
> to be the right position.

In that case I suspect the module theory.
How are you running the code?

> In the end, having tried absolutely everything else 
> I could think of, and given that the error arose at 
> the closing bracket at the end of line 10, I 
> tried the only thing I could remotely think of that 
> I hadn't tried and put a space in between the 
> second bracket and the colon - and the wretched thing 
> ran.  

As you know that shouldn't have made any difference.
Did you try going back and removing the space again 
and see if the error came back?

> You could obviously see something wrong 

The posted error report had no colon.

HTH,

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



From lisi.reisz at gmail.com  Thu Jul  7 09:52:01 2011
From: lisi.reisz at gmail.com (Lisi)
Date: Thu, 7 Jul 2011 08:52:01 +0100
Subject: [Tutor] broken script - curiouser and curiouser
In-Reply-To: <iv2s8i$h1p$1@dough.gmane.org>
References: <201107052301.01246.lisi.reisz@gmail.com>
	<201107062257.25472.lisi.reisz@gmail.com>
	<iv2s8i$h1p$1@dough.gmane.org>
Message-ID: <201107070852.01972.lisi.reisz@gmail.com>

On Thursday 07 July 2011 00:48:24 Alan Gauld wrote:
> "Lisi" <lisi.reisz at gmail.com> wrote
>
> >>  :   File "ex26.py", line 10
> >>  :     def print_first_word(words)
> >>  :                               ^
> >>  : SyntaxError: invalid syntax
> >>  : lisi at Tux:~/Python/LearnPythonTheHardWay$
> >>
> >> Look at the error.  Look at the error carefully.
> >
> > I could see nothing that was different.
>
> The error report says you had no colon in your code.
> Python couldn't see it...

But there *was* a colon.  So why couldn't python see it?

> Are you sutre you didn't add it before posting but
> after running the code?

Positive.

> Or are you testing it by impotrting a module?
> In that case the interpreter may still be using
> the old version because you haven't reloaded
> the updated version?

 No

> > Yes - it was one of the first things I looked for when
> > the error came up (that and check that the brackets
> > were right).  It was there in what seemed to me
> > to be the right position.
>
> In that case I suspect the module theory.
> How are you running the code?

$ python ex14.py

> > In the end, having tried absolutely everything else
> > I could think of, and given that the error arose at
> > the closing bracket at the end of line 10, I
> > tried the only thing I could remotely think of that
> > I hadn't tried and put a space in between the
> > second bracket and the colon - and the wretched thing
> > ran.
>
> As you know that shouldn't have made any difference.
> Did you try going back and removing the space again
> and see if the error came back?

I now have at your suggestion, and it runs.  So I am now still  more 
mystified.  As I say I had tried retyping it (and checking carefully) umpteen 
times and also copied and pasted from a succesful function definition and 
checked the brackets and colon every time.

> > You could obviously see something wrong
>
> The posted error report had no colon.

Yes - but the script had one, which was why I included the actual script in my 
original post.  I seem to have cut too much in this email!

Thanks, Alan.

Lisi




From wprins at gmail.com  Thu Jul  7 11:21:59 2011
From: wprins at gmail.com (Walter Prins)
Date: Thu, 7 Jul 2011 10:21:59 +0100
Subject: [Tutor] broken script - curiouser and curiouser
In-Reply-To: <201107070852.01972.lisi.reisz@gmail.com>
References: <201107052301.01246.lisi.reisz@gmail.com>
	<201107062257.25472.lisi.reisz@gmail.com>
	<iv2s8i$h1p$1@dough.gmane.org>
	<201107070852.01972.lisi.reisz@gmail.com>
Message-ID: <CANLXbfAWe4x5ai0aGCdo4tA0LMMwzzL04HCHbNYJ4WQvNaAgtw@mail.gmail.com>

Hi Lisi

On 7 July 2011 08:52, Lisi <lisi.reisz at gmail.com> wrote:

> > > You could obviously see something wrong
> >
> > The posted error report had no colon.
>
> Yes - but the script had one, which was why I included the actual script in
> my
> original post.  I seem to have cut too much in this email!
>

The error message from Python is quoting what the interpreter read/saw from
the script file it was running.  If it quoted no colon, then there was no
colon in the python file read by the interpreter, at the time that it tried
to run it.  Your job is to figure out how this has happened.  Do you maybe
have several copies of the script lying around in different folders?  Were
you maybe editing the the file (and keeping it open in the editor) while
running it from a command prompt every so often and did you maybe not save
the change before running the script (so that there may have been a
discrepancy between the script on disk that was run by the interpreter and
the script in your editor window)?

Cheers

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110707/8c06bc2c/attachment-0001.html>

From lisi.reisz at gmail.com  Thu Jul  7 12:15:23 2011
From: lisi.reisz at gmail.com (Lisi)
Date: Thu, 7 Jul 2011 11:15:23 +0100
Subject: [Tutor] broken script - curiouser and curiouser
In-Reply-To: <CANLXbfAWe4x5ai0aGCdo4tA0LMMwzzL04HCHbNYJ4WQvNaAgtw@mail.gmail.com>
References: <201107052301.01246.lisi.reisz@gmail.com>
	<201107070852.01972.lisi.reisz@gmail.com>
	<CANLXbfAWe4x5ai0aGCdo4tA0LMMwzzL04HCHbNYJ4WQvNaAgtw@mail.gmail.com>
Message-ID: <201107071115.23537.lisi.reisz@gmail.com>

On Thursday 07 July 2011 10:21:59 Walter Prins wrote:
> Hi Lisi
>
> On 7 July 2011 08:52, Lisi <lisi.reisz at gmail.com> wrote:
> > > > You could obviously see something wrong
> > >
> > > The posted error report had no colon.
> >
> > Yes - but the script had one, which was why I included the actual script
> > in my
> > original post.  I seem to have cut too much in this email!
>
> The error message from Python is quoting what the interpreter read/saw from
> the script file it was running.  If it quoted no colon, then there was no
> colon in the python file read by the interpreter, at the time that it tried
> to run it.  Your job is to figure out how this has happened.  Do you maybe
> have several copies of the script lying around in different folders? 

No.  KWrite keeps an automatic backup, but I never use it.  As a result of 
your question, I have just run the automatic backup.  It runs fine.

> Were 
> you maybe editing the the file (and keeping it open in the editor) while
> running it from a command prompt every so often and did you maybe not save
> the change before running the script 

I did do that once or twice during the long saga, but immediately realised and 
saved the file before running again.  In fact, I think that it must sometimes 
have been saved multiple times because I was so afraid that I would do that.

> (so that there may have been a 
> discrepancy between the script on disk that was run by the interpreter and
> the script in your editor window)?

I can see nothing that could have caused it. :-(  Believe me, I thought of all 
the possibilities that have been mentioned so far and tried them out, with no 
joy.  The only thing that worked was inserting a space and then, at Alan's 
suggestion, removing it.  I am completely baffled.  There must have been 
something, but I cannot fathom what.  What difference does inserting a space 
and then deleting it make?????

At least this confirms that I took all the right debugging steps.  I think I 
just have to write it down as one of life's little mysteries.  If I can't 
uncover what happened with the files in front of me, clearly people who can 
see neither the screen nor the files have an impossible task!

I am very grateful for all the list's help.  I may have been left with the 
puzzle, but I have learnt a lot in the process of trying to debug the script.

Lisi

From marc.tompkins at gmail.com  Thu Jul  7 12:46:01 2011
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 7 Jul 2011 03:46:01 -0700
Subject: [Tutor] broken script - curiouser and curiouser
In-Reply-To: <201107071115.23537.lisi.reisz@gmail.com>
References: <201107052301.01246.lisi.reisz@gmail.com>
	<201107070852.01972.lisi.reisz@gmail.com>
	<CANLXbfAWe4x5ai0aGCdo4tA0LMMwzzL04HCHbNYJ4WQvNaAgtw@mail.gmail.com>
	<201107071115.23537.lisi.reisz@gmail.com>
Message-ID: <CAKK8jXZ9aTihaSRnWx3TqCoBvgrJUN325MeviVuUhzbmh628Uw@mail.gmail.com>

On Thu, Jul 7, 2011 at 3:15 AM, Lisi <lisi.reisz at gmail.com> wrote:

> There must have been
>
something, but I cannot fathom what.  What difference does inserting a space
> and then deleting it make?????
>

I wonder whether you might have had a stray non-printing character in
there?  I believe that that would explain the symptom; of course, I have no
idea how it would have got there, so this merely pushes the mystery down a
layer!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110707/39642035/attachment.html>

From lisi.reisz at gmail.com  Thu Jul  7 13:01:43 2011
From: lisi.reisz at gmail.com (Lisi)
Date: Thu, 7 Jul 2011 12:01:43 +0100
Subject: [Tutor] broken script - curiouser and curiouser
In-Reply-To: <CAKK8jXZ9aTihaSRnWx3TqCoBvgrJUN325MeviVuUhzbmh628Uw@mail.gmail.com>
References: <201107052301.01246.lisi.reisz@gmail.com>
	<201107071115.23537.lisi.reisz@gmail.com>
	<CAKK8jXZ9aTihaSRnWx3TqCoBvgrJUN325MeviVuUhzbmh628Uw@mail.gmail.com>
Message-ID: <201107071201.43452.lisi.reisz@gmail.com>

On Thursday 07 July 2011 11:46:01 Marc Tompkins wrote:
> On Thu, Jul 7, 2011 at 3:15 AM, Lisi <lisi.reisz at gmail.com> wrote:
> > There must have been
>
> something, but I cannot fathom what.  What difference does inserting a
> space
>
> > and then deleting it make?????
>
> I wonder whether you might have had a stray non-printing character in
> there?  I believe that that would explain the symptom; of course, I have no
> idea how it would have got there, so this merely pushes the mystery down a
> layer!

Low be it whispered.... <shock-horror> 
I thought of that and copy-pasted into a WP and turned on non-printed 
characters.  There were none.  Only those that were there advisedly.
</shock-horror> 

One day when I am even older and even greyer I may look at this and a light 
may dawn and say: "So *that's* what was happening."

Thanks for the input!

Lisi

From lisi.reisz at gmail.com  Thu Jul  7 16:07:18 2011
From: lisi.reisz at gmail.com (Lisi)
Date: Thu, 7 Jul 2011 15:07:18 +0100
Subject: [Tutor] broken script - curiouser and curiouser
In-Reply-To: <CANLXbfAWe4x5ai0aGCdo4tA0LMMwzzL04HCHbNYJ4WQvNaAgtw@mail.gmail.com>
References: <201107052301.01246.lisi.reisz@gmail.com>
	<201107070852.01972.lisi.reisz@gmail.com>
	<CANLXbfAWe4x5ai0aGCdo4tA0LMMwzzL04HCHbNYJ4WQvNaAgtw@mail.gmail.com>
Message-ID: <201107071507.18916.lisi.reisz@gmail.com>

On Thursday 07 July 2011 10:21:59 Walter Prins wrote:
> ?Do you maybe
> have several copies of the script lying around in different folders?

I _think_ that you may have the answer here - tho' for me it raises almost as 
many questions as I had in the first place.  The exercise I was having that 
intractable problem with was ex25.  ex26 involves downloading a file from the 
Internet and finding and correcting the errors.

In error, I downloaded ex26 before I had done ex25.  So I left it and did 
ex25.

Having finally given up on ex25, I am now doing ex26.  And guess what?!  Line 
10 has a missing colon.

So _how_ did a missing colon in ex26 cause problems in ex25????

Lisi

From lisi.reisz at gmail.com  Thu Jul  7 16:17:26 2011
From: lisi.reisz at gmail.com (Lisi)
Date: Thu, 7 Jul 2011 15:17:26 +0100
Subject: [Tutor] Python conundrum
Message-ID: <201107071517.26863.lisi.reisz@gmail.com>

Hi! :-)

From the book I am working from:

<quote> A shortcut is to do your import like this: 
from ex25 import  * </quote>

Is this a new and wonderful meaning of the word "shortcut"?  _Why_, _how_ is 
that a shortcut for:

import ex25

when it has seven *more* characters (counting the spaces)?  Or, put another 
way, twice as many words? :-/

It is obviously an alternative, but I just don't get that it is a shortcut.

Thanks,
Lisi

From z.radoslavov at gmail.com  Thu Jul  7 16:27:37 2011
From: z.radoslavov at gmail.com (=?windows-1251?B?x+Tw4OLq7iDI4uDt7uI=?=)
Date: Thu, 7 Jul 2011 17:27:37 +0300
Subject: [Tutor] Python conundrum
In-Reply-To: <201107071517.26863.lisi.reisz@gmail.com>
References: <201107071517.26863.lisi.reisz@gmail.com>
Message-ID: <CANRP-=aBWY_f7DuvOTZpxSNEYiiA6QawXj+SPMUn4hTqcM9EUA@mail.gmail.com>

if you type from ex25 import * then you don't have to put ex25. in front of
the functions.

On Thu, Jul 7, 2011 at 5:17 PM, Lisi <lisi.reisz at gmail.com> wrote:

> Hi! :-)
>
> >From the book I am working from:
>
> <quote> A shortcut is to do your import like this:
> from ex25 import  * </quote>
>
> Is this a new and wonderful meaning of the word "shortcut"?  _Why_, _how_
> is
> that a shortcut for:
>
> import ex25
>
> when it has seven *more* characters (counting the spaces)?  Or, put another
> way, twice as many words? :-/
>
> It is obviously an alternative, but I just don't get that it is a shortcut.
>
> Thanks,
> Lisi
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110707/3380c5bf/attachment.html>

From enalicho at gmail.com  Thu Jul  7 16:30:35 2011
From: enalicho at gmail.com (Noah Hall)
Date: Thu, 7 Jul 2011 15:30:35 +0100
Subject: [Tutor] Python conundrum
In-Reply-To: <201107071517.26863.lisi.reisz@gmail.com>
References: <201107071517.26863.lisi.reisz@gmail.com>
Message-ID: <CAOv69sZZutB+3PhtqEVtF-q0isRQzDMZQ-7jApuXdnnCR5JODA@mail.gmail.com>

On Thu, Jul 7, 2011 at 3:17 PM, Lisi <lisi.reisz at gmail.com> wrote:
> Hi! :-)
>
> >From the book I am working from:
>
> <quote> A shortcut is to do your import like this:
> from ex25 import ?* </quote>
>
> Is this a new and wonderful meaning of the word "shortcut"? ?_Why_, _how_ is
> that a shortcut for:
>
> import ex25
>
> when it has seven *more* characters (counting the spaces)? ?Or, put another
> way, twice as many words? :-/
>
> It is obviously an alternative, but I just don't get that it is a shortcut.
>
> Thanks,
> Lisi
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Consider this -
Say I had a program that used a few functions from the math module -


import math

print math.sqrt(4)
print math.pow(2,2)
print math.factorial(5)
print math.cos(30)

Because the way import works, I would have to write math (to say "take
from the namespace math") before each function from math.
Using from math import *, I can instead write -

from math import *

print sqrt(4)
print pow(2,2)
print factorial(5)
print cos(30)

This imports the functions directly into the __main__ namespace
Now, over the course of my program, this would save hundreds of
characters, as you wouldn't need to type "math" before to state which
namespace to use.

(Of course, if using only certain functions from a module such as
math, you should really use from math import sqrt, pow, factorial,
cos)
- notice

>>> import math
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'math']

>>> from math import *
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'acos',
'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil
', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp',
'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frex
p', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma',
'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radian
s', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

>>> from math import factorial, pow, sqrt, cos
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'cos',
'factorial', 'pow', 'sqrt']

HTH.

From Michael at shamirlens.co.uk  Thu Jul  7 16:42:12 2011
From: Michael at shamirlens.co.uk (Michael M Mason)
Date: Thu, 7 Jul 2011 14:42:12 +0000
Subject: [Tutor] broken script - curiouser and curiouser
References: <201107052301.01246.lisi.reisz@gmail.com>
	<201107070852.01972.lisi.reisz@gmail.com>
	<CANLXbfAWe4x5ai0aGCdo4tA0LMMwzzL04HCHbNYJ4WQvNaAgtw@mail.gmail.com>
	<201107071507.18916.lisi.reisz@gmail.com> 
Message-ID: <5378B081D0A21C45A6135E92E182BD7F26F26547@Mail1-Shamir.shamir.org.il>

Michael M Mason wrote on 07 July 2011 at 15:38:-
> > In error, I downloaded ex26 before I had done ex25.  So I left
> > it and did ex25.
> >
> > Having finally given up on ex25, I am now doing ex26.  And guess
> > what?!  Line 10 has a missing colon.
> >
> > So _how_ did a missing colon in ex26 cause problems in ex25????
>
> Maybe you've been editing ex25 and then executing ex26. That'd get you
> the same error in the same place over and over again.

Looks like this might be it. In your earlier post the error reported is in ex26:-

: lisi at Tux:~/Python/LearnPythonTheHardWay$ python ex26.py
:   File "ex26.py", line 10
:     def print_first_word(words)
:                               ^
: SyntaxError: invalid syntax
: lisi at Tux:~/Python/LearnPythonTheHardWay$

-- 
Michael


This mail was sent via Mail-SeCure System.

 
 
************************************************************************************
This footnote confirms that this email message has been scanned by
PineApp Mail-SeCure for the presence of malicious code, vandals & computer viruses.
************************************************************************************


From Michael at shamirlens.co.uk  Thu Jul  7 16:36:06 2011
From: Michael at shamirlens.co.uk (Michael M Mason)
Date: Thu, 7 Jul 2011 14:36:06 +0000
Subject: [Tutor] broken script - curiouser and curiouser
In-Reply-To: <201107071507.18916.lisi.reisz@gmail.com>
References: <201107052301.01246.lisi.reisz@gmail.com>
	<201107070852.01972.lisi.reisz@gmail.com>
	<CANLXbfAWe4x5ai0aGCdo4tA0LMMwzzL04HCHbNYJ4WQvNaAgtw@mail.gmail.com>
	<201107071507.18916.lisi.reisz@gmail.com>
Message-ID: <5378B081D0A21C45A6135E92E182BD7F26F26538@Mail1-Shamir.shamir.org.il>

On 07 July 2011 at 15:07 Lisi wrote:

> In error, I downloaded ex26 before I had done ex25.  So I left
> it and did ex25.
>
> Having finally given up on ex25, I am now doing ex26.  And guess
> what?!  Line 10 has a missing colon.
>
> So _how_ did a missing colon in ex26 cause problems in ex25????

Maybe you've been editing ex25 and then executing ex26. That'd get you the same error in the same place over and over again.

-- 
Michael


This mail was sent via Mail-SeCure System.

 
 
************************************************************************************
This footnote confirms that this email message has been scanned by
PineApp Mail-SeCure for the presence of malicious code, vandals & computer viruses.
************************************************************************************


From lisi.reisz at gmail.com  Thu Jul  7 17:39:34 2011
From: lisi.reisz at gmail.com (Lisi)
Date: Thu, 7 Jul 2011 16:39:34 +0100
Subject: [Tutor] broken script - curiouser and curiouser
In-Reply-To: <5378B081D0A21C45A6135E92E182BD7F26F26547@Mail1-Shamir.shamir.org.il>
References: <201107052301.01246.lisi.reisz@gmail.com>
	<201107071507.18916.lisi.reisz@gmail.com>
	<5378B081D0A21C45A6135E92E182BD7F26F26547@Mail1-Shamir.shamir.org.il>
Message-ID: <201107071639.34531.lisi.reisz@gmail.com>

On Thursday 07 July 2011 15:42:12 Michael M Mason wrote:
> > Maybe you've been editing ex25 and then executing ex26. That'd get you
> > the same error in the same place over and over again.
>
> Looks like this might be it. In your earlier post the error reported is in
> ex26:-
>
> : lisi at Tux:~/Python/LearnPythonTheHardWay$ python ex26.py
> : ? File "ex26.py", line 10
> : ? ? def print_first_word(words)
> : ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ^
> : SyntaxError: invalid syntax
> : lisi at Tux:~/Python/LearnPythonTheHardWay$

Doh! Thank you , Michael.  The book does say something along the lines of "If 
you are stuck, leave it, take a break and come back to it later".

Still, at least I can learn from my mistakes. ;-)  That is my story anyway, 
and I'm sticking to it.

Many years ago, in the days of the ark, when men were real men, and 
programming meant writing strings of 0s and 1s and then shifting pins around 
a board, I once spent over two hours trying to discover what was wrong with 
my code in just one spot.

At the end of the over 2 hours it finally dawned on me that my code was fine - 
the memory location for that particular pin was faulty.

Lisi


From marc.tompkins at gmail.com  Thu Jul  7 19:15:37 2011
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 7 Jul 2011 10:15:37 -0700
Subject: [Tutor] Python conundrum
In-Reply-To: <CAOv69sZZutB+3PhtqEVtF-q0isRQzDMZQ-7jApuXdnnCR5JODA@mail.gmail.com>
References: <201107071517.26863.lisi.reisz@gmail.com>
	<CAOv69sZZutB+3PhtqEVtF-q0isRQzDMZQ-7jApuXdnnCR5JODA@mail.gmail.com>
Message-ID: <CAKK8jXazm6=jxa9UR-3545D7XJE96c_WWvtNm5ZJY6KmzhQnww@mail.gmail.com>

On Thu, Jul 7, 2011 at 7:30 AM, Noah Hall <enalicho at gmail.com> wrote:

> On Thu, Jul 7, 2011 at 3:17 PM, Lisi <lisi.reisz at gmail.com> wrote:
> > Hi! :-)
> >
> > >From the book I am working from:
> >
> > <quote> A shortcut is to do your import like this:
> > from ex25 import  * </quote>
> >
> > Is this a new and wonderful meaning of the word "shortcut"?
>

I haven't read the book in question, so I don't know whether they cover this
in the next paragraph... but this is generally BAD PRACTICE.  If the module
you're importing contains functions that have the same names as functions in
the standard library, or in another module that you're also importing, then
_the last thing you import prevails._  If that was really what you wanted,
well and good - but it's very, very easy to make mistakes this way, and
frustratingly hard to catch them.

To take an extreme example, imagine that you're importing a module called
"bogus", and that "bogus" contains a function called "int()" function which
actually returns a random number.  (Why?  'Cause I'm making a point here,
that's why!)  In this hypothetical example, if you import "bogus" in the
usual way -

> import bogus
> int("5")
> >> 5
> bogus.int("5")
> >> 97
>
you get what you'd expect.  But if you use the nifty "shortcut" method
(SOOOO much easier!) you might get the following:

> import * from bogus
> int("5")
> >> 63
>
Huh?
>
And again, if that's what you want, more power to you.  But I prefer to
overload methods explicitly so that I know what code will run when I call a
function.

To be clear: most modules don't randomly overload standard methods... much.
One common exception is str(); many classes offer custom str() methods, and
calling a custom method when you're expecting the standard one can waste
your whole day.

In the words of the great philosopher "import this" - "Namespaces are one
honking great idea -- let's do more of those!"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110707/0fe76b0d/attachment.html>

From alan.gauld at btinternet.com  Thu Jul  7 19:18:42 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 7 Jul 2011 18:18:42 +0100
Subject: [Tutor] Python conundrum
References: <201107071517.26863.lisi.reisz@gmail.com>
Message-ID: <iv4pps$csd$1@dough.gmane.org>


"Lisi" <lisi.reisz at gmail.com> wrote

> <quote> A shortcut is to do your import like this:
> from ex25 import  * </quote>
>
> Is this a new and wonderful meaning of the word "shortcut"?

No, it just saves you typing ex25. in front of every name in the 
module.

Of course, the "import *" technique is frowned upon because
of the risk of introducing name conflicts, so its not really a
recommended "shortcut"...


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






_Why_, _how_ is
> that a shortcut for:
>
> import ex25
>
> when it has seven *more* characters (counting the spaces)?  Or, put 
> another
> way, twice as many words? :-/
>
> It is obviously an alternative, but I just don't get that it is a 
> shortcut.
>
> Thanks,
> Lisi
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 



From ramit.prasad at jpmchase.com  Thu Jul  7 19:15:22 2011
From: ramit.prasad at jpmchase.com (Prasad, Ramit)
Date: Thu, 7 Jul 2011 13:15:22 -0400
Subject: [Tutor] broken script - curiouser and curiouser
In-Reply-To: <201107071639.34531.lisi.reisz@gmail.com>
References: <201107052301.01246.lisi.reisz@gmail.com>
	<201107071507.18916.lisi.reisz@gmail.com>
	<5378B081D0A21C45A6135E92E182BD7F26F26547@Mail1-Shamir.shamir.org.il>
	<201107071639.34531.lisi.reisz@gmail.com>
Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2E4EBBAC1A@EMARC112VS01.exchad.jpmchase.net>

>Many years ago, in the days of the ark, when men were real men, and 

So men in the present day are fake men?

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423
This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase &
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.

From cfuller084 at thinkingplanet.net  Thu Jul  7 22:45:46 2011
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Thu, 7 Jul 2011 15:45:46 -0500
Subject: [Tutor] broken script - curiouser and curiouser
In-Reply-To: <201107071639.34531.lisi.reisz@gmail.com>
References: <201107052301.01246.lisi.reisz@gmail.com>
	<5378B081D0A21C45A6135E92E182BD7F26F26547@Mail1-Shamir.shamir.org.il>
	<201107071639.34531.lisi.reisz@gmail.com>
Message-ID: <201107071546.01169.cfuller084@thinkingplanet.net>


TWO HOURS??  You aren't a Real Programmer 
(http://www.catb.org/jargon/html/story-of-mel.html) until you've spent a whole 
day debugging something trivial.

Heck, I quite recently spent a day plus trying to figure out why my 
microcontroller project wasn't working right. I was using a command line tool 
to tell it what functions to execute, settings to set, etc. But it didn't 
produce any sensible output. No communication errors were reported, and the 
code looked fine. It even echoed back the updated settings correctly. I finally 
realized that each invocation of the command line tool opened and closed the 
serial port, which had the effect of resetting the microcontroller! So, 
anything saved in volatile memory was naturally lost!

Ok, maybe that was just plain old boneheadery.

Cheers

On Thursday 07 July 2011, Lisi wrote:
> On Thursday 07 July 2011 15:42:12 Michael M Mason wrote:
> > > Maybe you've been editing ex25 and then executing ex26. That'd get you
> > > the same error in the same place over and over again.
> > 
> > Looks like this might be it. In your earlier post the error reported is
> > in ex26:-
> > 
> > : lisi at Tux:~/Python/LearnPythonTheHardWay$ python ex26.py
> > :   File "ex26.py", line 10
> > :     def print_first_word(words)
> > :                               ^
> > : SyntaxError: invalid syntax
> > : lisi at Tux:~/Python/LearnPythonTheHardWay$
> 
> Doh! Thank you , Michael.  The book does say something along the lines of
> "If you are stuck, leave it, take a break and come back to it later".
> 
> Still, at least I can learn from my mistakes. ;-)  That is my story anyway,
> and I'm sticking to it.
> 
> Many years ago, in the days of the ark, when men were real men, and
> programming meant writing strings of 0s and 1s and then shifting pins
> around a board, I once spent over two hours trying to discover what was
> wrong with my code in just one spot.
> 
> At the end of the over 2 hours it finally dawned on me that my code was
> fine - the memory location for that particular pin was faulty.
> 
> Lisi
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From hrobert25 at hotmail.com  Sun Jul 10 13:12:39 2011
From: hrobert25 at hotmail.com (Robert H)
Date: Sun, 10 Jul 2011 11:12:39 +0000
Subject: [Tutor] Hello World in Python without space
Message-ID: <SNT120-W4225B173E1E955B729669FBC420@phx.gbl>


Dear all,


I have Python 3.2 installed on Windows 7. I am a complete beginner playing around with the basic functions. My problem is the following script:


name="world"
print("Hello", name,"!")


The result is:
Hello world !


However, I don't want the space before the exclamation mark. I want this:
Hello world!


I tried to solve the problem with e.g.:
print("Hello",name.strip(),"!")
but the result is the same.


Can anyone out there help me? Thank you.


Regards,
Robert
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110710/3ede54b0/attachment.html>

From izzaddin.ruhulessin at gmail.com  Sun Jul 10 13:23:11 2011
From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin)
Date: Sun, 10 Jul 2011 13:23:11 +0200
Subject: [Tutor] Hello World in Python without space
In-Reply-To: <SNT120-W4225B173E1E955B729669FBC420@phx.gbl>
References: <SNT120-W4225B173E1E955B729669FBC420@phx.gbl>
Message-ID: <CA+sZtS=vxcyCpww1r7AQ_9X=A1A=E-L7rWPMdUL0hALq60Ku-A@mail.gmail.com>

Sending args to the print command always puts spaces between them.

Try:
print("Hello {name}!".format(name=name))





2011/7/10 Robert H <hrobert25 at hotmail.com>

>  Dear all,
>
>
> I have Python 3.2 installed on Windows 7. I am a complete beginner playing
> around with the basic functions. My problem is the following script:
>
>
> name="world"
> print("Hello", name,"!")
>
>
> The result is:
> Hello world !
>
>
> However, I don't want the space before the exclamation mark. I want this:
> Hello world!
>
>
> I tried to solve the problem with e.g.:
> print("Hello",name.strip(),"!")
> but the result is the same.
>
>
> Can anyone out there help me? Thank you.
>
>
> Regards,
> Robert
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110710/240e886c/attachment.html>

From __peter__ at web.de  Sun Jul 10 14:05:25 2011
From: __peter__ at web.de (Peter Otten)
Date: Sun, 10 Jul 2011 14:05:25 +0200
Subject: [Tutor] Hello World in Python without space
References: <SNT120-W4225B173E1E955B729669FBC420@phx.gbl>
Message-ID: <ivc4h2$7ck$1@dough.gmane.org>

Robert H wrote:

> I have Python 3.2 installed on Windows 7. I am a complete beginner playing
> around with the basic functions. My problem is the following script:
> 
> 
> name="world"
> print("Hello", name,"!")
> 
> 
> The result is:
> Hello world !
> 
> 
> However, I don't want the space before the exclamation mark. I want this:
> Hello world!
> 
> 
> I tried to solve the problem with e.g.:
> print("Hello",name.strip(),"!")
> but the result is the same.


print() by default inserts a space between its arguments. You can avoid that 
by specifying a separator explicitly with the "sep" keyword. Let me show it 
in the interactive interpreter which is generally a good place to experiment 
with small snippets of code:

>>> name = "Robert"
>>> print("Hello ", name, "!", sep="") # Note the explicit " " after "Hello"
Hello Robert!

Another goodie is that you can easily get useful information about modules, 
classes, keywords, and functions, e. g.

>>> help(print)

shows

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file: a file-like object (stream); defaults to the current sys.stdout.
    sep:  string inserted between values, default a space.
    end:  string appended after the last value, default a newline.

Use help() without argument to learn more about the interactive help.



From alan.gauld at btinternet.com  Sun Jul 10 15:40:34 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 10 Jul 2011 14:40:34 +0100
Subject: [Tutor] Hello World in Python without space
References: <SNT120-W4225B173E1E955B729669FBC420@phx.gbl>
Message-ID: <ivca4v$2g9$1@dough.gmane.org>

"Robert H" <hrobert25 at hotmail.com> wrote

> name="world"
> print("Hello", name,"!")
> Hello world !
>
> However, I don't want the space before the exclamation
> mark. I want this:
> Hello world!

> Can anyone out there help me? Thank you.

I see you've already had two answers, a third is
to construct the string before printing it. There
are various ways to do that:

The simplest:

output = "Hello " + name + "!"

An alternative which is more efficient for
larger numbers of substruings is:

output = "".join(["Hello ",name,"!"])  # thats an empty string to 
start

The thirs is to use a formatstring, but thats
what Izz did in his print call.

Whichever method you use you then use

print(output)

Lots of options. As Peter said, use the >>> prompt to
experiment to find which works best for you.


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






From lisi.reisz at gmail.com  Sun Jul 10 17:31:45 2011
From: lisi.reisz at gmail.com (Lisi)
Date: Sun, 10 Jul 2011 16:31:45 +0100
Subject: [Tutor] broken script - curiouser and curiouser
In-Reply-To: <5378B081D0A21C45A6135E92E182BD7F26F26538@Mail1-Shamir.shamir.org.il>
References: <201107052301.01246.lisi.reisz@gmail.com>
	<201107071507.18916.lisi.reisz@gmail.com>
	<5378B081D0A21C45A6135E92E182BD7F26F26538@Mail1-Shamir.shamir.org.il>
Message-ID: <201107101631.45479.lisi.reisz@gmail.com>

On Thursday 07 July 2011 15:36:06 Michael M Mason wrote:
> Maybe you've been editing ex25 and then executing ex26. That'd get you the
> same error in the same place over and over again.

Doh!  They do say that there is one born every minute. 

Thanks,
Lisi

From emile at fenx.com  Mon Jul 11 15:03:26 2011
From: emile at fenx.com (Emile van Sebille)
Date: Mon, 11 Jul 2011 06:03:26 -0700
Subject: [Tutor] Hello World in Python without space
In-Reply-To: <SNT120-W4225B173E1E955B729669FBC420@phx.gbl>
References: <SNT120-W4225B173E1E955B729669FBC420@phx.gbl>
Message-ID: <ivesb6$hvi$1@dough.gmane.org>

On 7/10/2011 4:12 AM Robert H said...
> Dear all,
>
>
> I have Python 3.2 installed on Windows 7. I am a complete beginner
> playing around with the basic functions. My problem is the following script:
>
>
> name="world"
> print("Hello", name,"!")

print("Hello", name+"!")

Alan mentioned using concatenation as well and "".join() is generally 
preferred, particularly when many strings are involved.

Emile



From steven.rafael.turner at gmail.com  Mon Jul 11 15:26:50 2011
From: steven.rafael.turner at gmail.com (Rafael Turner)
Date: Mon, 11 Jul 2011 08:26:50 -0500
Subject: [Tutor] List methods inside a dictionary of list
Message-ID: <CALZDmRiMAT-+gnf3HdJK5cZEo9=i9-uKDHgB97nX2ZxuGoNgog@mail.gmail.com>

Hello,

I am playing lists and dictionaries and I came across this
counter-intuitive result.

>>> d = dict(zip(['a', 'q', 'c', 'b', 'e', 'd', 'g', 'j'],8*[[0]]))
>>>d
Out:
{'a': [0],
 'b': [0],
 'c': [0],
 'd': [0],
 'e': [0],
 'g': [0],
 'j': [0],
 'q': [0]}

>>> d['a'].__setitem__(0,4)
>>> d
Out:
{'a': [4],
 'b': [4],
 'c': [4],
 'd': [4],
 'e': [4],
 'g': [4],
 'j': [4],
 'q': [4]}

I was not expecting all the keys to be updated. Is there any
documentation I could read on how different datatypes' methods and
operators interact differently when inside a dictionary?  I would also
like to find a way of being able to use list methods in side a
dictionary so that

>>> d['a'][0] = 5

Does not return

{'a': [5],
 'b': [5],
 'c': [5],
 'd': [5],
 'e': [5],
 'g': [5],
 'j': [5],
 'q': [5]}

But rather

{'a': [5],
 'b': [0],
 'c': [0],
 'd': [0],
 'e': [0],
 'g': [0],
 'j': [0],
 'q': [0]}

Where d is made by d = dict(zip(['a', 'q', 'c', 'b', 'e', 'd', 'g',
'j'],8*[[0]]))

Thanks a bunch,
Rafael

From ctak225 at gmail.com  Mon Jul 11 15:32:43 2011
From: ctak225 at gmail.com (ctak225 at gmail.com)
Date: Mon, 11 Jul 2011 21:32:43 +0800
Subject: [Tutor] Tutor Digest, Vol 89, Issue 22
In-Reply-To: <mailman.18.1310378401.6445.tutor@python.org>
References: <mailman.18.1310378401.6445.tutor@python.org>
Message-ID: <60a29f89-d056-45fd-b84f-83b15f34ced0@email.android.com>

It just name+"!", this is string concatenation

tutor-request at python.org wrote:

>Send Tutor mailing list submissions to
>	tutor at python.org
>
>To subscribe or unsubscribe via the World Wide Web, visit
>	http://mail.python.org/mailman/listinfo/tutor
>or, via email, send a message with subject or body 'help' to
>	tutor-request at python.org
>
>You can reach the person managing the list at
>	tutor-owner at python.org
>
>When replying, please edit your Subject line so it is more specific
>than "Re: Contents of Tutor digest..."
>Today's Topics:
>
>   1. Hello World in Python without space (Robert H)
>   2. Re: Hello World in Python without space (Izz ad-Din Ruhulessin)
>   3. Re: Hello World in Python without space (Peter Otten)
>   4. Re: Hello World in Python without space (Alan Gauld)
>   5. Re: broken script - curiouser and curiouser (Lisi)
>
>Dear all,
>
>
>I have Python 3.2 installed on Windows 7. I am a complete beginner
>playing around with the basic functions. My problem is the following
>script:
>
>
>name="world"
>print("Hello", name,"!")
>
>
>The result is:
>Hello world !
>
>
>However, I don't want the space before the exclamation mark. I want
>this:
>Hello world!
>
>
>I tried to solve the problem with e.g.:
>print("Hello",name.strip(),"!")
>but the result is the same.
>
>
>Can anyone out there help me? Thank you.
>
>
>Regards,
>Robert
>		 	   		  Sending args to the print command always puts spaces between
>them.
>
>Try:
>print("Hello {name}!".format(name=name))
>
>
>
>
>
>2011/7/10 Robert H <hrobert25 at hotmail.com>
>
>>  Dear all,
>>
>>
>> I have Python 3.2 installed on Windows 7. I am a complete beginner
>playing
>> around with the basic functions. My problem is the following script:
>>
>>
>> name="world"
>> print("Hello", name,"!")
>>
>>
>> The result is:
>> Hello world !
>>
>>
>> However, I don't want the space before the exclamation mark. I want
>this:
>> Hello world!
>>
>>
>> I tried to solve the problem with e.g.:
>> print("Hello",name.strip(),"!")
>> but the result is the same.
>>
>>
>> Can anyone out there help me? Thank you.
>>
>>
>> Regards,
>> Robert
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>Robert H wrote:
>
>> I have Python 3.2 installed on Windows 7. I am a complete beginner
>playing
>> around with the basic functions. My problem is the following script:
>> 
>> 
>> name="world"
>> print("Hello", name,"!")
>> 
>> 
>> The result is:
>> Hello world !
>> 
>> 
>> However, I don't want the space before the exclamation mark. I want
>this:
>> Hello world!
>> 
>> 
>> I tried to solve the problem with e.g.:
>> print("Hello",name.strip(),"!")
>> but the result is the same.
>
>
>print() by default inserts a space between its arguments. You can avoid
>that 
>by specifying a separator explicitly with the "sep" keyword. Let me
>show it 
>in the interactive interpreter which is generally a good place to
>experiment 
>with small snippets of code:
>
>>>> name = "Robert"
>>>> print("Hello ", name, "!", sep="") # Note the explicit " " after
>"Hello"
>Hello Robert!
>
>Another goodie is that you can easily get useful information about
>modules, 
>classes, keywords, and functions, e. g.
>
>>>> help(print)
>
>shows
>
>print(...)
>    print(value, ..., sep=' ', end='\n', file=sys.stdout)
>
>    Prints the values to a stream, or to sys.stdout by default.
>    Optional keyword arguments:
> file: a file-like object (stream); defaults to the current sys.stdout.
>    sep:  string inserted between values, default a space.
>    end:  string appended after the last value, default a newline.
>
>Use help() without argument to learn more about the interactive help.
>
>
>
>"Robert H" <hrobert25 at hotmail.com> wrote
>
>> name="world"
>> print("Hello", name,"!")
>> Hello world !
>>
>> However, I don't want the space before the exclamation
>> mark. I want this:
>> Hello world!
>
>> Can anyone out there help me? Thank you.
>
>I see you've already had two answers, a third is
>to construct the string before printing it. There
>are various ways to do that:
>
>The simplest:
>
>output = "Hello " + name + "!"
>
>An alternative which is more efficient for
>larger numbers of substruings is:
>
>output = "".join(["Hello ",name,"!"])  # thats an empty string to 
>start
>
>The thirs is to use a formatstring, but thats
>what Izz did in his print call.
>
>Whichever method you use you then use
>
>print(output)
>
>Lots of options. As Peter said, use the >>> prompt to
>experiment to find which works best for you.
>
>
>-- 
>Alan Gauld
>Author of the Learn to Program web site
>http://www.alan-g.me.uk/
>
>
>
>
>
>
>On Thursday 07 July 2011 15:36:06 Michael M Mason wrote:
>> Maybe you've been editing ex25 and then executing ex26. That'd get
>you the
>> same error in the same place over and over again.
>
>Doh!  They do say that there is one born every minute. 
>
>Thanks,
>Lisi
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor

-- 
Sent from my Android phone with K-9 Mail. Please excuse my brevity.

From wprins at gmail.com  Mon Jul 11 16:06:42 2011
From: wprins at gmail.com (Walter Prins)
Date: Mon, 11 Jul 2011 15:06:42 +0100
Subject: [Tutor] List methods inside a dictionary of list
In-Reply-To: <CALZDmRiMAT-+gnf3HdJK5cZEo9=i9-uKDHgB97nX2ZxuGoNgog@mail.gmail.com>
References: <CALZDmRiMAT-+gnf3HdJK5cZEo9=i9-uKDHgB97nX2ZxuGoNgog@mail.gmail.com>
Message-ID: <CANLXbfAUYkRaPkXsrYXzv-udWsCaNUT_fAutuoErz1bmK=QyqA@mail.gmail.com>

Hi,

On 11 July 2011 14:26, Rafael Turner <steven.rafael.turner at gmail.com> wrote:

>
> >>> d = dict(zip(['a', 'q', 'c', 'b', 'e', 'd', 'g', 'j'],8*[[0]]))
> >>>d
> Out:
> {'a': [0],
>  'b': [0],
>  'c': [0],
>  'd': [0],
>  'e': [0],
>  'g': [0],
>  'j': [0],
>  'q': [0]}
>
> >>> d['a'].__setitem__(0,4)
> >>> d
> Out:
> {'a': [4],
>  'b': [4],
>  'c': [4],
>  'd': [4],
>  'e': [4],
>  'g': [4],
>  'j': [4],
>  'q': [4]}
>
> I was not expecting all the keys to be updated. Is there any
> documentation I could read on how different datatypes' methods and
> operators interact differently when inside a dictionary?  I would also
> like to find a way of being able to use list methods in side a
> dictionary so that
>

There's no funny interaction based on datatypes as you imply.  The thing
you're missing is that when you do 8*[[0]], you're actually creating a a
list of references to another **single list** (which happens to contain a
single value, 0.)  Thus, when you then update that single value 0 in that
single list, being pointed to by the several locations in the outer list,
you predictably end up seeing the change from all the references in the
outer list.

To illustrate, do the following:
>>> l=[0]
>>> l2=[l]
>>> l2
[[0]]
>>> l3=8*l2
>>> l3
[[0], [0], [0], [0], [0], [0], [0], [0]]
>>> l[0]=1
>>> l3
[[1], [1], [1], [1], [1], [1], [1], [1]]
>>>

Describing the above:

l is a *single *list object, containing a single value, 0.

l2 is another single list containing this single list l.

l3 is a third list, constructed to by contatenating the* contents* of l2 8
times. This means l3 effectively ends up containing list l (which is the
contents of l2) 8 times in successtion.  *The contents of list l2 is a
reference to list l.*  So consequently in other words each entry in l3 is
actually a back reference to the ***same original list l***.  That is the
key bit to understand, in order to understand why you're seeing what you're
seeing in your example.

Now to illustrate this, we change the original single list l's first element
to something else, namely 1.  And, as expected, when we then view the
apparent contents of l3, as before, it reflects the contents of list l 8
times, because again, every entry in l3 is actually a reference to the same
original list l, which now contains 1 instead of 0.

So, depending on what you're tring to do, you probably want to change your
data structure in your example in some way to ensure you have new seperate
sublists for each entry in your outer list.

Regards

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110711/f3ea1c53/attachment.html>

From swiftone at swiftone.org  Mon Jul 11 16:33:24 2011
From: swiftone at swiftone.org (Brett Ritter)
Date: Mon, 11 Jul 2011 10:33:24 -0400
Subject: [Tutor] List methods inside a dictionary of list
In-Reply-To: <CALZDmRiMAT-+gnf3HdJK5cZEo9=i9-uKDHgB97nX2ZxuGoNgog@mail.gmail.com>
References: <CALZDmRiMAT-+gnf3HdJK5cZEo9=i9-uKDHgB97nX2ZxuGoNgog@mail.gmail.com>
Message-ID: <CAMb349xAHTk_WZYtK4-yFx-hA8rZ8E0Rw0nYFiyXMHH96tYpbw@mail.gmail.com>

On Mon, Jul 11, 2011 at 9:26 AM, Rafael Turner
<steven.rafael.turner at gmail.com> wrote:
> I am playing lists and dictionaries and I came across this
> counter-intuitive result.
>
>>>> d = dict(zip(['a', 'q', 'c', 'b', 'e', 'd', 'g', 'j'],8*[[0]]))
...
>>>> d['a'].__setitem__(0,4)
...
>
> I was not expecting all the keys to be updated. Is there any
> documentation I could read on how different datatypes' methods and
> operators interact differently when inside a dictionary? ?I would also
> like to find a way of being able to use list methods in side a
> dictionary so that

As has been mentioned, this isn't the dictionary doing anything weird,
this is that "8*[[0]]" gives you a list of 8 references to the same
list.  You can play with just that part and see that that's the source
of your issue.

To achieve what you are trying, try this instead:

d = dict([(x,[0]) for x in ['a', 'q', 'c', 'b', 'e', 'd', 'g', 'j']])

Can you understand how this behaves differently than 8*[[0]] ?  Check
the Python docs for array multiplication if you're confused, but the
basic idea is that "[0]" isn't getting evaluated freshly for every
piece in the array for 8*[[0]], but in a list comprehension it is.
-- 
Brett Ritter / SwiftOne
swiftone at swiftone.org

From steven.rafael.turner at gmail.com  Mon Jul 11 16:45:38 2011
From: steven.rafael.turner at gmail.com (Rafael Turner)
Date: Mon, 11 Jul 2011 09:45:38 -0500
Subject: [Tutor] List methods inside a dictionary of list
In-Reply-To: <CAMb349xAHTk_WZYtK4-yFx-hA8rZ8E0Rw0nYFiyXMHH96tYpbw@mail.gmail.com>
References: <CALZDmRiMAT-+gnf3HdJK5cZEo9=i9-uKDHgB97nX2ZxuGoNgog@mail.gmail.com>
	<CAMb349xAHTk_WZYtK4-yFx-hA8rZ8E0Rw0nYFiyXMHH96tYpbw@mail.gmail.com>
Message-ID: <CALZDmRjj2xbVFRJc=Mkv1fB3HXq58N1xE8X-r4atODpbpfA3Aw@mail.gmail.com>

I did not understand the behavior of array multiplication. In fact, I
just now learned what it was called thanks to your email.

Best wishes,
Rafael

On Mon, Jul 11, 2011 at 9:33 AM, Brett Ritter <swiftone at swiftone.org> wrote:
> On Mon, Jul 11, 2011 at 9:26 AM, Rafael Turner
> <steven.rafael.turner at gmail.com> wrote:
>> I am playing lists and dictionaries and I came across this
>> counter-intuitive result.
>>
>>>>> d = dict(zip(['a', 'q', 'c', 'b', 'e', 'd', 'g', 'j'],8*[[0]]))
> ...
>>>>> d['a'].__setitem__(0,4)
> ...
>>
>> I was not expecting all the keys to be updated. Is there any
>> documentation I could read on how different datatypes' methods and
>> operators interact differently when inside a dictionary? ?I would also
>> like to find a way of being able to use list methods in side a
>> dictionary so that
>
> As has been mentioned, this isn't the dictionary doing anything weird,
> this is that "8*[[0]]" gives you a list of 8 references to the same
> list. ?You can play with just that part and see that that's the source
> of your issue.
>
> To achieve what you are trying, try this instead:
>
> d = dict([(x,[0]) for x in ['a', 'q', 'c', 'b', 'e', 'd', 'g', 'j']])
>
> Can you understand how this behaves differently than 8*[[0]] ? ?Check
> the Python docs for array multiplication if you're confused, but the
> basic idea is that "[0]" isn't getting evaluated freshly for every
> piece in the array for 8*[[0]], but in a list comprehension it is.
> --
> Brett Ritter / SwiftOne
> swiftone at swiftone.org
>

From samudhio at gmail.com  Tue Jul 12 00:16:04 2011
From: samudhio at gmail.com (Edgar Almonte)
Date: Mon, 11 Jul 2011 18:16:04 -0400
Subject: [Tutor] compare and arrange file
Message-ID: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>

hello , i have a file this a structure like this
XXXXXXXXX XXXX| 0000000000000.00| 0000000088115.39|
XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|
XXXXXXXXX XXXX| 0000000000000.00| 0000000090443.29|
XXXXXXXXX XXXX| 0000000088115.39| 0000000000000.00|
XXXXXXXXX XXXX| 0000000000000.00| 0000000088335.39|
XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|
XXXXXXXXX XXXX| 0000000088335.39| 0000000000000.00|
XXXXXXXXX XXXX| 0000000090443.29| 0000000000000.00|

now i need re-arrange the file in this way:
XXXXXXXXX XXXX| 0000000000000.00| 0000000088115.39|
XXXXXXXXX XXXX| 0000000088115.39| 0000000000000.00|
XXXXXXXXX XXXX| 0000000000000.00| 0000000090453.29|
XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|

etc....


i try this
http://pastebin.com/2mvxn5GY
but without look

maybe somebody can give some hint , i know that this is maybe not a
directly python question but if somebody can help me I will appreciate
it

Thanks

From emile at fenx.com  Tue Jul 12 00:39:47 2011
From: emile at fenx.com (Emile van Sebille)
Date: Mon, 11 Jul 2011 15:39:47 -0700
Subject: [Tutor] compare and arrange file
In-Reply-To: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>
References: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>
Message-ID: <ivfu3r$bdf$1@dough.gmane.org>

On 7/11/2011 3:16 PM Edgar Almonte said...
> hello , i have a file this a structure like this
> XXXXXXXXX XXXX| 0000000000000.00| 0000000088115.39|
> XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|
> XXXXXXXXX XXXX| 0000000000000.00| 0000000090443.29|
> XXXXXXXXX XXXX| 0000000088115.39| 0000000000000.00|
> XXXXXXXXX XXXX| 0000000000000.00| 0000000088335.39|
> XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|
> XXXXXXXXX XXXX| 0000000088335.39| 0000000000000.00|
> XXXXXXXXX XXXX| 0000000090443.29| 0000000000000.00|
>
> now i need re-arrange the file in this way:
> XXXXXXXXX XXXX| 0000000000000.00| 0000000088115.39|
> XXXXXXXXX XXXX| 0000000088115.39| 0000000000000.00|
> XXXXXXXXX XXXX| 0000000000000.00| 0000000090453.29|
> XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|
>
> etc....

It's not obvious to me for your sample what you want.  For example, the 
2nd value 0000000090453.29 from the re-arranged group doesn't appear in 
the top sample.

If I venture a guess, it seems to me that you want the debits and 
corresponding offsetting credits listed in sequence.

In pseudo-code, that might me done as:

read lines from file
for each line in lines
   set flag to D or C based on values
   set sortkey to value+flag
   append sortkey and line to decorated list
sort decorated list
for key,line in decorated list
   print line


HTH,

Emile



>
>
> i try this
> http://pastebin.com/2mvxn5GY
> but without look
>
> maybe somebody can give some hint , i know that this is maybe not a
> directly python question but if somebody can help me I will appreciate
> it
>
> Thanks
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



From d at davea.name  Tue Jul 12 01:35:34 2011
From: d at davea.name (Dave Angel)
Date: Mon, 11 Jul 2011 19:35:34 -0400
Subject: [Tutor] compare and arrange file
In-Reply-To: <ivfu3r$bdf$1@dough.gmane.org>
References: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>
	<ivfu3r$bdf$1@dough.gmane.org>
Message-ID: <4E1B88C6.7040500@davea.name>

On 07/11/2011 06:39 PM, Emile van Sebille wrote:
> On 7/11/2011 3:16 PM Edgar Almonte said...
>> hello , i have a file this a structure like this
>> XXXXXXXXX XXXX| 0000000000000.00| 0000000088115.39|
>> XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|
>> XXXXXXXXX XXXX| 0000000000000.00| 0000000090443.29|
>> XXXXXXXXX XXXX| 0000000088115.39| 0000000000000.00|
>> XXXXXXXXX XXXX| 0000000000000.00| 0000000088335.39|
>> XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|
>> XXXXXXXXX XXXX| 0000000088335.39| 0000000000000.00|
>> XXXXXXXXX XXXX| 0000000090443.29| 0000000000000.00|
>>
>> now i need re-arrange the file in this way:
>> XXXXXXXXX XXXX| 0000000000000.00| 0000000088115.39|
>> XXXXXXXXX XXXX| 0000000088115.39| 0000000000000.00|
>> XXXXXXXXX XXXX| 0000000000000.00| 0000000090453.29|
>> XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|
>>
>> etc....
>
> It's not obvious to me for your sample what you want.  For example, 
> the 2nd value 0000000090453.29 from the re-arranged group doesn't 
> appear in the top sample.
>
> If I venture a guess, it seems to me that you want the debits and 
> corresponding offsetting credits listed in sequence.
>
> In pseudo-code, that might me done as:
>
> read lines from file
> for each line in lines
>   set flag to D or C based on values
>   set sortkey to value+flag
>   append sortkey and line to decorated list
> sort decorated list
> for key,line in decorated list
>   print line
>
>
> HTH,
>
> Emile
>
>
>
>>
>>
>> i try this
>> http://pastebin.com/2mvxn5GY
>> but without look

I also can't see any pattern in the data to give a clue what kind of 
filtering you're trying to do.  A more specific spec would be useful.

I can comment on your pastebin code, however.  You should have pasted it 
in your message, since it's short.

   1.
      def splitline(line, z):
   2.
      if z == 0:
   3.
      pass
   4.
   5.
           fields = line.split('|')
   6.
           nlist = []
   7.
      for field in fields:
   8.
               nlist.append(field)
   9.
  10.
      return nlist[z]

The whole loop with nlist is a waste of energy, as you already got a 
list from split().  You could replace the function with
    def splitline(line, z):
          return  line.split('|')[z]

The if z==0 doesn't do anything either.  Perhaps you meant to do some 
error checking in case the line doesn't have at least z fields.

But the real problem in your code is the you posted for loop.  The inner 
loop takes multiple passes through the orig1 file, but the second time 
won't get anything, since the file is already positioned at the end.  
I'd simply move the open statement inside the outer loop.

There may be other problems, but that could get you going.

DaveA







-- 

DaveA

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110711/d0daf727/attachment.html>

From samudhio at gmail.com  Tue Jul 12 01:50:20 2011
From: samudhio at gmail.com (Edgar Almonte)
Date: Mon, 11 Jul 2011 19:50:20 -0400
Subject: [Tutor] compare and arrange file
In-Reply-To: <4E1B88C6.7040500@davea.name>
References: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>
	<ivfu3r$bdf$1@dough.gmane.org> <4E1B88C6.7040500@davea.name>
Message-ID: <CAH0g_ax4aoS9LUFjc7aGCmQ5oDRnjv4vzhV7HWs=znC0xBec2A@mail.gmail.com>

Thanks for the hints , what i want accomplish is sort the line by the
same value in the column 2 and 3

i mean the line with the same value in the 2 get together with the
line in the same value in column 3

emile and david thanks again let me check the hint that your give me,
i will feedback the code if everything workout or else :D

On Mon, Jul 11, 2011 at 7:35 PM, Dave Angel <d at davea.name> wrote:
> On 07/11/2011 06:39 PM, Emile van Sebille wrote:
>
> On 7/11/2011 3:16 PM Edgar Almonte said...
>
> hello , i have a file this a structure like this
> XXXXXXXXX XXXX| 0000000000000.00| 0000000088115.39|
> XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|
> XXXXXXXXX XXXX| 0000000000000.00| 0000000090443.29|
> XXXXXXXXX XXXX| 0000000088115.39| 0000000000000.00|
> XXXXXXXXX XXXX| 0000000000000.00| 0000000088335.39|
> XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|
> XXXXXXXXX XXXX| 0000000088335.39| 0000000000000.00|
> XXXXXXXXX XXXX| 0000000090443.29| 0000000000000.00|
>
> now i need re-arrange the file in this way:
> XXXXXXXXX XXXX| 0000000000000.00| 0000000088115.39|
> XXXXXXXXX XXXX| 0000000088115.39| 0000000000000.00|
> XXXXXXXXX XXXX| 0000000000000.00| 0000000090453.29|
> XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|
>
> etc....
>
> It's not obvious to me for your sample what you want.? For example, the 2nd
> value 0000000090453.29 from the re-arranged group doesn't appear in the top
> sample.
>
> If I venture a guess, it seems to me that you want the debits and
> corresponding offsetting credits listed in sequence.
>
> In pseudo-code, that might me done as:
>
> read lines from file
> for each line in lines
> ? set flag to D or C based on values
> ? set sortkey to value+flag
> ? append sortkey and line to decorated list
> sort decorated list
> for key,line in decorated list
> ? print line
>
>
> HTH,
>
> Emile
>
>
>
>
>
> i try this
> http://pastebin.com/2mvxn5GY
> but without look
>
> I also can't see any pattern in the data to give a clue what kind of
> filtering you're trying to do.? A more specific spec would be useful.
>
> I can comment on your pastebin code, however.? You should have pasted it in
> your message, since it's short.
>
> def splitline(line, z):
> ? ? if z == 0:
> ? ? ? ?pass
>
> ? ? fields = line.split('|')
> ? ? nlist = []
> ? ? for field in fields:
> ? ? ? ? nlist.append(field)
>
> ? ? return nlist[z]
>
> The whole loop with nlist is a waste of energy, as you already got a list
> from split().? You could replace the function with
> ?? def splitline(line, z):
> ???????? return? line.split('|')[z]
>
> The if z==0 doesn't do anything either.? Perhaps you meant to do some error
> checking in case the line doesn't have at least z fields.
>
> But the real problem in your code is the you posted for loop.? The inner
> loop takes multiple passes through the orig1 file, but the second time won't
> get anything, since the file is already positioned at the end.? I'd simply
> move the open statement inside the outer loop.
>
> There may be other problems, but that could get you going.
>
> DaveA
>
>
>
>
>
>
>
> --
>
> DaveA
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

From samudhio at gmail.com  Tue Jul 12 02:02:14 2011
From: samudhio at gmail.com (Edgar Almonte)
Date: Mon, 11 Jul 2011 20:02:14 -0400
Subject: [Tutor] compare and arrange file
In-Reply-To: <ivfu3r$bdf$1@dough.gmane.org>
References: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>
	<ivfu3r$bdf$1@dough.gmane.org>
Message-ID: <CAH0g_awUgNVnfTcLX7J57ropDGOp3n9OBTvt4uF0PgQnbSTkqg@mail.gmail.com>

back again,
yes that is the idea:
"> If I venture a guess, it seems to me that you want the debits and
> corresponding offsetting credits listed in sequence."


but not sure if i get you pseudo code , you mean
some how flag the line when is D or C ( credit of debit )
and then sort by what ?

On Mon, Jul 11, 2011 at 6:39 PM, Emile van Sebille <emile at fenx.com> wrote:
> On 7/11/2011 3:16 PM Edgar Almonte said...
>>
>> hello , i have a file this a structure like this
>> XXXXXXXXX XXXX| 0000000000000.00| 0000000088115.39|
>> XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|
>> XXXXXXXXX XXXX| 0000000000000.00| 0000000090443.29|
>> XXXXXXXXX XXXX| 0000000088115.39| 0000000000000.00|
>> XXXXXXXXX XXXX| 0000000000000.00| 0000000088335.39|
>> XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|
>> XXXXXXXXX XXXX| 0000000088335.39| 0000000000000.00|
>> XXXXXXXXX XXXX| 0000000090443.29| 0000000000000.00|
>>
>> now i need re-arrange the file in this way:
>> XXXXXXXXX XXXX| 0000000000000.00| 0000000088115.39|
>> XXXXXXXXX XXXX| 0000000088115.39| 0000000000000.00|
>> XXXXXXXXX XXXX| 0000000000000.00| 0000000090453.29|
>> XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|
>>
>> etc....
>
> It's not obvious to me for your sample what you want. ?For example, the 2nd
> value 0000000090453.29 from the re-arranged group doesn't appear in the top
> sample.
>
offsetting credits listed in sequence
>
> In pseudo-code, that might me done as:
>
> read lines from file
> for each line in lines
> ?set flag to D or C based on values
> ?set sortkey to value+flag
> ?append sortkey and line to decorated list
> sort decorated list
> for key,line in decorated list
> ?print line
>
>
> HTH,
>
> Emile
>
>
>
>>
>>
>> i try this
>> http://pastebin.com/2mvxn5GY
>> but without look
>>
>> maybe somebody can give some hint , i know that this is maybe not a
>> directly python question but if somebody can help me I will appreciate
>> it
>>
>> Thanks
>> _______________________________________________
>> Tutor maillist ?- ?Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From samudhio at gmail.com  Tue Jul 12 02:07:04 2011
From: samudhio at gmail.com (Edgar Almonte)
Date: Mon, 11 Jul 2011 20:07:04 -0400
Subject: [Tutor] compare and arrange file
In-Reply-To: <4E1B88C6.7040500@davea.name>
References: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>
	<ivfu3r$bdf$1@dough.gmane.org> <4E1B88C6.7040500@davea.name>
Message-ID: <CAH0g_azxjq7ekwPdZm1nqMnGajF2ZDt=Uy_3RTy2-qGRM=jsuA@mail.gmail.com>

back again david

i do the for because the line is delimited by pipeline so and i need
get the field number 2 and 3 of the line
if i understand well the split('|')[z] will just split till there ( z
value ) so if i do split('|')[2] i will get:
XXXXXXXXX XXXX, 0000000000000.00 and i just want the number value part
of the line

i try putting the read of orig1 inside the fist loop but that don't
see work because the thing is that for some reason the fist loop is
just passing one time ( the first one
if you see in my code i put a print line1 in the first loop and a
print value in the second one and i get something line

"----line1-------"
"value1"
"value1"
"value1"
"value1"
"value1"
"value1"

etc.

pd: sorry for my bad english

On Mon, Jul 11, 2011 at 7:35 PM, Dave Angel <d at davea.name> wrote:
> On 07/11/2011 06:39 PM, Emile van Sebille wrote:
>
> On 7/11/2011 3:16 PM Edgar Almonte said...
>
> hello , i have a file this a structure like this
> XXXXXXXXX XXXX| 0000000000000.00| 0000000088115.39|
> XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|
> XXXXXXXXX XXXX| 0000000000000.00| 0000000090443.29|
> XXXXXXXXX XXXX| 0000000088115.39| 0000000000000.00|
> XXXXXXXXX XXXX| 0000000000000.00| 0000000088335.39|
> XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|
> XXXXXXXXX XXXX| 0000000088335.39| 0000000000000.00|
> XXXXXXXXX XXXX| 0000000090443.29| 0000000000000.00|
>
> now i need re-arrange the file in this way:
> XXXXXXXXX XXXX| 0000000000000.00| 0000000088115.39|
> XXXXXXXXX XXXX| 0000000088115.39| 0000000000000.00|
> XXXXXXXXX XXXX| 0000000000000.00| 0000000090453.29|
> XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|
>
> etc....
>
> It's not obvious to me for your sample what you want.? For example, the 2nd
> value 0000000090453.29 from the re-arranged group doesn't appear in the top
> sample.
>
> If I venture a guess, it seems to me that you want the debits and
> corresponding offsetting credits listed in sequence.
>
> In pseudo-code, that might me done as:
>
> read lines from file
> for each line in lines
> ? set flag to D or C based on values
> ? set sortkey to value+flag
> ? append sortkey and line to decorated list
> sort decorated list
> for key,line in decorated list
> ? print line
>
>
> HTH,
>
> Emile
>
>
>
>
>
> i try this
> http://pastebin.com/2mvxn5GY
> but without look
>
> I also can't see any pattern in the data to give a clue what kind of
> filtering you're trying to do.? A more specific spec would be useful.
>
> I can comment on your pastebin code, however.? You should have pasted it in
> your message, since it's short.
>
> def splitline(line, z):
> ? ? if z == 0:
> ? ? ? ?pass
>
> ? ? fields = line.split('|')
> ? ? nlist = []
> ? ? for field in fields:
> ? ? ? ? nlist.append(field)
>
> ? ? return nlist[z]
>
> The whole loop with nlist is a waste of energy, as you already got a list
> from split().? You could replace the function with
> ?? def splitline(line, z):
> ???????? return? line.split('|')[z]
>
> The if z==0 doesn't do anything either.? Perhaps you meant to do some error
> checking in case the line doesn't have at least z fields.
>
> But the real problem in your code is the you posted for loop.? The inner
> loop takes multiple passes through the orig1 file, but the second time won't
> get anything, since the file is already positioned at the end.? I'd simply
> move the open statement inside the outer loop.
>
> There may be other problems, but that could get you going.
>
> DaveA
>
>
>
>
>
>
>
> --
>
> DaveA
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

From steve at alchemy.com  Tue Jul 12 01:55:43 2011
From: steve at alchemy.com (Steve Willoughby)
Date: Mon, 11 Jul 2011 16:55:43 -0700
Subject: [Tutor] compare and arrange file
In-Reply-To: <CAH0g_ax4aoS9LUFjc7aGCmQ5oDRnjv4vzhV7HWs=znC0xBec2A@mail.gmail.com>
References: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>
	<ivfu3r$bdf$1@dough.gmane.org> <4E1B88C6.7040500@davea.name>
	<CAH0g_ax4aoS9LUFjc7aGCmQ5oDRnjv4vzhV7HWs=znC0xBec2A@mail.gmail.com>
Message-ID: <4E1B8D7F.2090804@alchemy.com>

On 11-Jul-11 16:50, Edgar Almonte wrote:
> Thanks for the hints , what i want accomplish is sort the line by the
> same value in the column 2 and 3
>
> i mean the line with the same value in the 2 get together with the
> line in the same value in column 3

What if the same value appears more than once?  Does it matter which 
ones you match up?  If so, how do you decide?

-- 
Steve Willoughby / steve at alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C

From samudhio at gmail.com  Tue Jul 12 02:18:24 2011
From: samudhio at gmail.com (Edgar Almonte)
Date: Mon, 11 Jul 2011 20:18:24 -0400
Subject: [Tutor] compare and arrange file
In-Reply-To: <4E1B8D7F.2090804@alchemy.com>
References: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>
	<ivfu3r$bdf$1@dough.gmane.org> <4E1B88C6.7040500@davea.name>
	<CAH0g_ax4aoS9LUFjc7aGCmQ5oDRnjv4vzhV7HWs=znC0xBec2A@mail.gmail.com>
	<4E1B8D7F.2090804@alchemy.com>
Message-ID: <CAH0g_ax6L=Y5i1mwdcd4b=attAMgQOSwyD+Uene8K=46WGxrgA@mail.gmail.com>

this is just one time thing and the value don't get repeat

On Mon, Jul 11, 2011 at 7:55 PM, Steve Willoughby <steve at alchemy.com> wrote:
> On 11-Jul-11 16:50, Edgar Almonte wrote:
>>
>> Thanks for the hints , what i want accomplish is sort the line by the
>> same value in the column 2 and 3
>>
>> i mean the line with the same value in the 2 get together with the
>> line in the same value in column 3
>
> What if the same value appears more than once? ?Does it matter which ones
> you match up? ?If so, how do you decide?
>
> --
> Steve Willoughby / steve at alchemy.com
> "A ship in harbor is safe, but that is not what ships are built for."
> PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From steve at alchemy.com  Tue Jul 12 02:22:00 2011
From: steve at alchemy.com (Steve Willoughby)
Date: Mon, 11 Jul 2011 17:22:00 -0700
Subject: [Tutor] compare and arrange file
In-Reply-To: <CAH0g_ax6L=Y5i1mwdcd4b=attAMgQOSwyD+Uene8K=46WGxrgA@mail.gmail.com>
References: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>
	<ivfu3r$bdf$1@dough.gmane.org> <4E1B88C6.7040500@davea.name>
	<CAH0g_ax4aoS9LUFjc7aGCmQ5oDRnjv4vzhV7HWs=znC0xBec2A@mail.gmail.com>
	<4E1B8D7F.2090804@alchemy.com>
	<CAH0g_ax6L=Y5i1mwdcd4b=attAMgQOSwyD+Uene8K=46WGxrgA@mail.gmail.com>
Message-ID: <4E1B93A8.8010900@alchemy.com>

On 11-Jul-11 17:18, Edgar Almonte wrote:
> this is just one time thing and the value don't get repeat

Then you could make a single loop over the input lines, building two
dictionaries as you go:
   * one that maps column 2's value to the rest of that line's data
   * and one that does this for column 3's value.

Now run through the column 2 data you saved, print that data row,
then look up the value in the other dictionary and print that after it.

>
> On Mon, Jul 11, 2011 at 7:55 PM, Steve Willoughby<steve at alchemy.com>  wrote:
>> On 11-Jul-11 16:50, Edgar Almonte wrote:
>>>
>>> Thanks for the hints , what i want accomplish is sort the line by the
>>> same value in the column 2 and 3
>>>
>>> i mean the line with the same value in the 2 get together with the
>>> line in the same value in column 3
>>
>> What if the same value appears more than once?  Does it matter which ones
>> you match up?  If so, how do you decide?
>>
>> --
>> Steve Willoughby / steve at alchemy.com
>> "A ship in harbor is safe, but that is not what ships are built for."
>> PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>


-- 
Steve Willoughby / steve at alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C

From samudhio at gmail.com  Tue Jul 12 02:38:22 2011
From: samudhio at gmail.com (Edgar Almonte)
Date: Mon, 11 Jul 2011 20:38:22 -0400
Subject: [Tutor] compare and arrange file
In-Reply-To: <4E1B93A8.8010900@alchemy.com>
References: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>
	<ivfu3r$bdf$1@dough.gmane.org> <4E1B88C6.7040500@davea.name>
	<CAH0g_ax4aoS9LUFjc7aGCmQ5oDRnjv4vzhV7HWs=znC0xBec2A@mail.gmail.com>
	<4E1B8D7F.2090804@alchemy.com>
	<CAH0g_ax6L=Y5i1mwdcd4b=attAMgQOSwyD+Uene8K=46WGxrgA@mail.gmail.com>
	<4E1B93A8.8010900@alchemy.com>
Message-ID: <CAH0g_ayeg3cTDmenwjCdOWcWz5kJQ27ZEPheNs9=Bwkd-hxioQ@mail.gmail.com>

i not too smart steve , can you show me with code ?

On Mon, Jul 11, 2011 at 8:22 PM, Steve Willoughby <steve at alchemy.com> wrote:
> On 11-Jul-11 17:18, Edgar Almonte wrote:
>>
>> this is just one time thing and the value don't get repeat
>
> Then you could make a single loop over the input lines, building two
> dictionaries as you go:
> ?* one that maps column 2's value to the rest of that line's data
> ?* and one that does this for column 3's value.
>
> Now run through the column 2 data you saved, print that data row,
> then look up the value in the other dictionary and print that after it.
>
>>
>> On Mon, Jul 11, 2011 at 7:55 PM, Steve Willoughby<steve at alchemy.com>
>> ?wrote:
>>>
>>> On 11-Jul-11 16:50, Edgar Almonte wrote:
>>>>
>>>> Thanks for the hints , what i want accomplish is sort the line by the
>>>> same value in the column 2 and 3
>>>>
>>>> i mean the line with the same value in the 2 get together with the
>>>> line in the same value in column 3
>>>
>>> What if the same value appears more than once? ?Does it matter which ones
>>> you match up? ?If so, how do you decide?
>>>
>>> --
>>> Steve Willoughby / steve at alchemy.com
>>> "A ship in harbor is safe, but that is not what ships are built for."
>>> PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C
>>> _______________________________________________
>>> Tutor maillist ?- ?Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>
>
> --
> Steve Willoughby / steve at alchemy.com
> "A ship in harbor is safe, but that is not what ships are built for."
> PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C
>

From emile at fenx.com  Tue Jul 12 05:01:52 2011
From: emile at fenx.com (Emile van Sebille)
Date: Mon, 11 Jul 2011 20:01:52 -0700
Subject: [Tutor] compare and arrange file
In-Reply-To: <CAH0g_awUgNVnfTcLX7J57ropDGOp3n9OBTvt4uF0PgQnbSTkqg@mail.gmail.com>
References: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>	<ivfu3r$bdf$1@dough.gmane.org>
	<CAH0g_awUgNVnfTcLX7J57ropDGOp3n9OBTvt4uF0PgQnbSTkqg@mail.gmail.com>
Message-ID: <ivgdf8$ka7$1@dough.gmane.org>

On 7/11/2011 5:02 PM Edgar Almonte said...
> back again,
> yes that is the idea:
> ">  If I venture a guess, it seems to me that you want the debits and
>> corresponding offsetting credits listed in sequence."
>
>
> but not sure if i get you pseudo code , you mean
> some how flag the line when is D or C ( credit of debit )
> and then sort by what ?
>

When you sort a list of tuple pairs, it sort on the first item, so

set sortkey to value+flag

means the first tuple in the list of tuples to sort should end up with 
as value+flag, where the flag is set based on the non-zero value in your 
line.

For example,

     XXXs,Dval,Cval = line.split("|")

then, assuming a consistent valid file structure,

     if int(Dval): key="D"+Dval
     else: key="C"+Cval

then, append (key,line) to your decorated list for each line, and 
finally sort and print the lines from your decorated list.

Emile


>>> hello , i have a file this a structure like this
>>> XXXXXXXXX XXXX| 0000000000000.00| 0000000088115.39|
>>> XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|

<snip>

>> In pseudo-code, that might me done as:
>>
>> read lines from file
>> for each line in lines
>>   set flag to D or C based on values
>>   set sortkey to value+flag
>>   append sortkey and line to decorated list
>> sort decorated list
>> for key,line in decorated list
>>   print line


From samudhio at gmail.com  Tue Jul 12 06:56:48 2011
From: samudhio at gmail.com (Edgar Almonte)
Date: Tue, 12 Jul 2011 00:56:48 -0400
Subject: [Tutor] compare and arrange file
In-Reply-To: <ivgdf8$ka7$1@dough.gmane.org>
References: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>
	<ivfu3r$bdf$1@dough.gmane.org>
	<CAH0g_awUgNVnfTcLX7J57ropDGOp3n9OBTvt4uF0PgQnbSTkqg@mail.gmail.com>
	<ivgdf8$ka7$1@dough.gmane.org>
Message-ID: <CAH0g_axFWROiO-dvZz9XX1nrbTB_SFuvGfLFcVMWKnzFteEccA@mail.gmail.com>

thanks emile i understand exactly what you explain me but i was unable
to accomplish it ( too noob in python ) but i solved the problem with
this code
http://pastebin.com/4A6Jz4wZ

i will try do what you suggest me anyway but that will tomorrow ,
tonight i done and i feel good :D

Thanks all for the help

On Mon, Jul 11, 2011 at 11:01 PM, Emile van Sebille <emile at fenx.com> wrote:
> On 7/11/2011 5:02 PM Edgar Almonte said...
>>
>> back again,
>> yes that is the idea:
>> "> ?If I venture a guess, it seems to me that you want the debits and
>>>
>>> corresponding offsetting credits listed in sequence."
>>
>>
>> but not sure if i get you pseudo code , you mean
>> some how flag the line when is D or C ( credit of debit )
>> and then sort by what ?
>>
>
> When you sort a list of tuple pairs, it sort on the first item, so
>
> set sortkey to value+flag
>
> means the first tuple in the list of tuples to sort should end up with as
> value+flag, where the flag is set based on the non-zero value in your line.
>
> For example,
>
> ? ?XXXs,Dval,Cval = line.split("|")
>
> then, assuming a consistent valid file structure,
>
> ? ?if int(Dval): key="D"+Dval
> ? ?else: key="C"+Cval
>
> then, append (key,line) to your decorated list for each line, and finally
> sort and print the lines from your decorated list.
>
> Emile
>
>
>>>> hello , i have a file this a structure like this
>>>> XXXXXXXXX XXXX| 0000000000000.00| 0000000088115.39|
>>>> XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|
>
> <snip>
>
>>> In pseudo-code, that might me done as:
>>>
>>> read lines from file
>>> for each line in lines
>>> ?set flag to D or C based on values
>>> ?set sortkey to value+flag
>>> ?append sortkey and line to decorated list
>>> sort decorated list
>>> for key,line in decorated list
>>> ?print line
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From __peter__ at web.de  Tue Jul 12 11:44:43 2011
From: __peter__ at web.de (Peter Otten)
Date: Tue, 12 Jul 2011 11:44:43 +0200
Subject: [Tutor] compare and arrange file
References: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>
	<ivfu3r$bdf$1@dough.gmane.org>
	<CAH0g_awUgNVnfTcLX7J57ropDGOp3n9OBTvt4uF0PgQnbSTkqg@mail.gmail.com>
	<ivgdf8$ka7$1@dough.gmane.org>
	<CAH0g_axFWROiO-dvZz9XX1nrbTB_SFuvGfLFcVMWKnzFteEccA@mail.gmail.com>
Message-ID: <ivh526$bl3$1@dough.gmane.org>

Edgar Almonte wrote:

> thanks emile i understand exactly what you explain me but i was unable
> to accomplish it ( too noob in python ) but i solved the problem with
> this code
> http://pastebin.com/4A6Jz4wZ
> 
> i will try do what you suggest me anyway but that will tomorrow ,
> tonight i done and i feel good :D

When you're done compare it to the one below:









































import csv

def sortkey(row):
    if float(row[1]):
        return row[1], True
    else:
        return row[2], False

with open("infile.txt", "rb") as instream:
    rows = sorted(csv.reader(instream, delimiter="|"), key=sortkey)

with open("outfile.txt", "wb") as outstream:
    csv.writer(outstream, delimiter="|").writerows(rows)



From d at davea.name  Tue Jul 12 13:28:37 2011
From: d at davea.name (Dave Angel)
Date: Tue, 12 Jul 2011 07:28:37 -0400
Subject: [Tutor] compare and arrange file
In-Reply-To: <CAH0g_axFWROiO-dvZz9XX1nrbTB_SFuvGfLFcVMWKnzFteEccA@mail.gmail.com>
References: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>	<ivfu3r$bdf$1@dough.gmane.org>	<CAH0g_awUgNVnfTcLX7J57ropDGOp3n9OBTvt4uF0PgQnbSTkqg@mail.gmail.com>	<ivgdf8$ka7$1@dough.gmane.org>
	<CAH0g_axFWROiO-dvZz9XX1nrbTB_SFuvGfLFcVMWKnzFteEccA@mail.gmail.com>
Message-ID: <4E1C2FE5.4050907@davea.name>

On 07/12/2011 12:56 AM, Edgar Almonte wrote:
> thanks emile i understand exactly what you explain me but i was unable
> to accomplish it ( too noob in python ) but i solved the problem with
> this code
> http://pastebin.com/4A6Jz4wZ
>
(When you post on this list, your comments should follow the pieces 
you're responding to.  That's a long-standing convention.)

As I explained earlier, your nested loops won't work correctly, as you 
fail to re-open the orig1 file.  Since you still seem to think it'll 
work, I'll just hope this assignment is for fun, and not for anything 
that matters.

In particular, the first line will be compared to all the others.   But 
if the third line should have matched the seventh, it won't get written out.
-- 

DaveA


From samudhio at gmail.com  Tue Jul 12 14:21:45 2011
From: samudhio at gmail.com (Edgar Almonte)
Date: Tue, 12 Jul 2011 08:21:45 -0400
Subject: [Tutor] compare and arrange file
In-Reply-To: <ivh526$bl3$1@dough.gmane.org>
References: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>
	<ivfu3r$bdf$1@dough.gmane.org>
	<CAH0g_awUgNVnfTcLX7J57ropDGOp3n9OBTvt4uF0PgQnbSTkqg@mail.gmail.com>
	<ivgdf8$ka7$1@dough.gmane.org>
	<CAH0g_axFWROiO-dvZz9XX1nrbTB_SFuvGfLFcVMWKnzFteEccA@mail.gmail.com>
	<ivh526$bl3$1@dough.gmane.org>
Message-ID: <CAH0g_ay_SLtFsD-UXNG6NwrK2LLRWahVMSLQvDXkBs=h=ea83A@mail.gmail.com>

On Tue, Jul 12, 2011 at 5:44 AM, Peter Otten <__peter__ at web.de> wrote:
> Edgar Almonte wrote:
>
>> thanks emile i understand exactly what you explain me but i was unable
>> to accomplish it ( too noob in python ) but i solved the problem with
>> this code
>> http://pastebin.com/4A6Jz4wZ
>>
>> i will try do what you suggest me anyway but that will tomorrow ,
>> tonight i done and i feel good :D
>
> When you're done compare it to the one below:
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
> import csv
>
> def sortkey(row):
> ? ?if float(row[1]):
> ? ? ? ?return row[1], True
> ? ?else:
> ? ? ? ?return row[2], False
>
> with open("infile.txt", "rb") as instream:
> ? ?rows = sorted(csv.reader(instream, delimiter="|"), key=sortkey)
>
> with open("outfile.txt", "wb") as outstream:
> ? ?csv.writer(outstream, delimiter="|").writerows(rows)
>
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
This look aweasome i will try it later , thanks

From samudhio at gmail.com  Tue Jul 12 14:25:36 2011
From: samudhio at gmail.com (Edgar Almonte)
Date: Tue, 12 Jul 2011 08:25:36 -0400
Subject: [Tutor] compare and arrange file
In-Reply-To: <4E1C2FE5.4050907@davea.name>
References: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>
	<ivfu3r$bdf$1@dough.gmane.org>
	<CAH0g_awUgNVnfTcLX7J57ropDGOp3n9OBTvt4uF0PgQnbSTkqg@mail.gmail.com>
	<ivgdf8$ka7$1@dough.gmane.org>
	<CAH0g_axFWROiO-dvZz9XX1nrbTB_SFuvGfLFcVMWKnzFteEccA@mail.gmail.com>
	<4E1C2FE5.4050907@davea.name>
Message-ID: <CAH0g_axj9z=3VKwaNLT0HrTUduwrZSTrECFQJFEn=b=0SGfryA@mail.gmail.com>

On Tue, Jul 12, 2011 at 7:28 AM, Dave Angel <d at davea.name> wrote:
> On 07/12/2011 12:56 AM, Edgar Almonte wrote:
>>
>> thanks emile i understand exactly what you explain me but i was unable
>> to accomplish it ( too noob in python ) but i solved the problem with
>> this code
>> http://pastebin.com/4A6Jz4wZ
>>
> (When you post on this list, your comments should follow the pieces you're
> responding to. ?That's a long-standing convention.)
>
> As I explained earlier, your nested loops won't work correctly, as you fail
> to re-open the orig1 file. ?Since you still seem to think it'll work, I'll
> just hope this assignment is for fun, and not for anything that matters.
>
> In particular, the first line will be compared to all the others. ? But if
> the third line should have matched the seventh, it won't get written out.
> --
>
> DaveA
>
>


hmm i still don't get you point , i mean why you say that will fail ,
i copy/read the file 2 times and compare line by line with the second
copy of the file ( check the new code at top i do a read() for full
read it not more online reading ).

anyway i will do the case  that you explain and look the result.

From d at davea.name  Tue Jul 12 15:06:18 2011
From: d at davea.name (Dave Angel)
Date: Tue, 12 Jul 2011 09:06:18 -0400
Subject: [Tutor] compare and arrange file
In-Reply-To: <CAH0g_axj9z=3VKwaNLT0HrTUduwrZSTrECFQJFEn=b=0SGfryA@mail.gmail.com>
References: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>	<ivfu3r$bdf$1@dough.gmane.org>	<CAH0g_awUgNVnfTcLX7J57ropDGOp3n9OBTvt4uF0PgQnbSTkqg@mail.gmail.com>	<ivgdf8$ka7$1@dough.gmane.org>	<CAH0g_axFWROiO-dvZz9XX1nrbTB_SFuvGfLFcVMWKnzFteEccA@mail.gmail.com>	<4E1C2FE5.4050907@davea.name>
	<CAH0g_axj9z=3VKwaNLT0HrTUduwrZSTrECFQJFEn=b=0SGfryA@mail.gmail.com>
Message-ID: <4E1C46CA.2050504@davea.name>

On 07/12/2011 08:25 AM, Edgar Almonte wrote:
> On Tue, Jul 12, 2011 at 7:28 AM, Dave Angel<d at davea.name>  wrote:
>> On 07/12/2011 12:56 AM, Edgar Almonte wrote:
>>>
>>> thanks emile i understand exactly what you explain me but i was unable
>>> to accomplish it ( too noob in python ) but i solved the problem with
>>> this code
>>> http://pastebin.com/4A6Jz4wZ
>>>
>> (When you post on this list, your comments should follow the pieces you're
>> responding to.  That's a long-standing convention.)
>>
>> As I explained earlier, your nested loops won't work correctly, as you fail
>> to re-open the orig1 file.  Since you still seem to think it'll work, I'll
>> just hope this assignment is for fun, and not for anything that matters.
>>
>> In particular, the first line will be compared to all the others.   But if
>> the third line should have matched the seventh, it won't get written out.
>> --
>>
>> DaveA
>>
>>
>
>
> hmm i still don't get you point , i mean why you say that will fail ,
> i copy/read the file 2 times and compare line by line with the second
> copy of the file ( check the new code at top i do a read() for full
> read it not more online reading ).
>
> anyway i will do the case  that you explain and look the result.
>


You're absolutely right.  I missed the fact that you did a read() and 
split() at the top.  As long as you have enough memory to hold two 
copies of the file, that's great.

DaveA

From samudhio at gmail.com  Wed Jul 13 01:01:32 2011
From: samudhio at gmail.com (Edgar Almonte)
Date: Tue, 12 Jul 2011 19:01:32 -0400
Subject: [Tutor] compare and arrange file
In-Reply-To: <ivh526$bl3$1@dough.gmane.org>
References: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>
	<ivfu3r$bdf$1@dough.gmane.org>
	<CAH0g_awUgNVnfTcLX7J57ropDGOp3n9OBTvt4uF0PgQnbSTkqg@mail.gmail.com>
	<ivgdf8$ka7$1@dough.gmane.org>
	<CAH0g_axFWROiO-dvZz9XX1nrbTB_SFuvGfLFcVMWKnzFteEccA@mail.gmail.com>
	<ivh526$bl3$1@dough.gmane.org>
Message-ID: <CAH0g_aybrx47YV+Mb9hQ480xvb+3O3dUPXLE5JouHvGLZKqpRQ@mail.gmail.com>

On Tue, Jul 12, 2011 at 5:44 AM, Peter Otten <__peter__ at web.de> wrote:
> Edgar Almonte wrote:
>
>> thanks emile i understand exactly what you explain me but i was unable
>> to accomplish it ( too noob in python ) but i solved the problem with
>> this code
>> http://pastebin.com/4A6Jz4wZ
>>
>> i will try do what you suggest me anyway but that will tomorrow ,
>> tonight i done and i feel good :D
>
> When you're done compare it to the one below:
>

>
> import csv
>
> def sortkey(row):
> ? ?if float(row[1]):
> ? ? ? ?return row[1], True
> ? ?else:
> ? ? ? ?return row[2], False
>
> with open("infile.txt", "rb") as instream:
> ? ?rows = sorted(csv.reader(instream, delimiter="|"), key=sortkey)
>
> with open("outfile.txt", "wb") as outstream:
> ? ?csv.writer(outstream, delimiter="|").writerows(rows)
>
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

That code work flawless , aweasome , can you explain to me the code, i
have a idea but if you don't mind can you ?

From emile at fenx.com  Wed Jul 13 04:32:42 2011
From: emile at fenx.com (Emile van Sebille)
Date: Tue, 12 Jul 2011 19:32:42 -0700
Subject: [Tutor] compare and arrange file
In-Reply-To: <CAH0g_aybrx47YV+Mb9hQ480xvb+3O3dUPXLE5JouHvGLZKqpRQ@mail.gmail.com>
References: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>	<ivfu3r$bdf$1@dough.gmane.org>	<CAH0g_awUgNVnfTcLX7J57ropDGOp3n9OBTvt4uF0PgQnbSTkqg@mail.gmail.com>	<ivgdf8$ka7$1@dough.gmane.org>	<CAH0g_axFWROiO-dvZz9XX1nrbTB_SFuvGfLFcVMWKnzFteEccA@mail.gmail.com>	<ivh526$bl3$1@dough.gmane.org>
	<CAH0g_aybrx47YV+Mb9hQ480xvb+3O3dUPXLE5JouHvGLZKqpRQ@mail.gmail.com>
Message-ID: <ivj04k$9us$1@dough.gmane.org>

On 7/12/2011 4:01 PM Edgar Almonte said...
> On Tue, Jul 12, 2011 at 5:44 AM, Peter Otten<__peter__ at web.de>  wrote:
<snip>
>> import csv

imports the comma separated values (csv) file handler utilities module

>>
>> def sortkey(row):
>>     if float(row[1]):
>>         return row[1], True
>>     else:
>>         return row[2], False

... sortkey defines a function that accepts a cvs.reader data row, and 
returns either row[1] and True or row[2] and False based on which of 
row[1] and row[2] has a non-zero value

>>
>> with open("infile.txt", "rb") as instream:
>>     rows = sorted(csv.reader(instream, delimiter="|"), key=sortkey)

rows becomes the sortkey sorted result of the lines of infile.txt

>>
>> with open("outfile.txt", "wb") as outstream:
>>     csv.writer(outstream, delimiter="|").writerows(rows)

... and this writes those results to outfile.txt

you might also try the shortened:

from csv import reader,writer

def sortkey(row): return max(row[1],row[2]),row[1]>row[2]

writer(open("outfile.txt", "wb"), delimiter="|").writerows( 
sorted(reader(open("infile.txt", "rb"), delimiter="|"),key=sortkey))


Emile


From amit.pureenergy at gmail.com  Wed Jul 13 10:34:14 2011
From: amit.pureenergy at gmail.com (Amit Sethi)
Date: Wed, 13 Jul 2011 14:04:14 +0530
Subject: [Tutor] What algorithm suits here
Message-ID: <CAN+DPACUbS6spj=RFCD5jmQ2hDYbGvtW5gG4v7Yp2=aAbN8GMw@mail.gmail.com>

I have a list of dictionaries in this form.

{ message : xyz
  parent : 23
  id : 25
}
 or
{ message : abc
parent : None
id : 25
}

{ message : cde
parent : 28
id : 32
}

{ message : cde
parent : 23
id : 35
}

I want to make seperate the lists such that messages in same thread(
The parent message and its child messages } come together . What is
the best algorithm here



-- 
A-M-I-T S|S

From steve at pearwood.info  Wed Jul 13 12:06:30 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 13 Jul 2011 20:06:30 +1000
Subject: [Tutor] What algorithm suits here
In-Reply-To: <CAN+DPACUbS6spj=RFCD5jmQ2hDYbGvtW5gG4v7Yp2=aAbN8GMw@mail.gmail.com>
References: <CAN+DPACUbS6spj=RFCD5jmQ2hDYbGvtW5gG4v7Yp2=aAbN8GMw@mail.gmail.com>
Message-ID: <4E1D6E26.3040604@pearwood.info>

Amit Sethi wrote:
> I have a list of dictionaries in this form.
> 
> { message : xyz
>   parent : 23
>   id : 25
> }
>  or
> { message : abc
> parent : None
> id : 25
> }
> 
> { message : cde
> parent : 28
> id : 32
> }
> 
> { message : cde
> parent : 23
> id : 35
> }
> 
> I want to make seperate the lists such that messages in same thread(

Separate the *lists* plural? Earlier, you said you have *one* list. 
Please explain what you mean, showing an example.


> The parent message and its child messages } come together . What is
> the best algorithm here


Define "best" -- easiest to write, simplest to understand, uses least 
amount of memory, something else?




-- 
Steven


From samudhio at gmail.com  Wed Jul 13 14:18:23 2011
From: samudhio at gmail.com (Edgar Almonte)
Date: Wed, 13 Jul 2011 08:18:23 -0400
Subject: [Tutor] compare and arrange file
In-Reply-To: <ivj04k$9us$1@dough.gmane.org>
References: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>
	<ivfu3r$bdf$1@dough.gmane.org>
	<CAH0g_awUgNVnfTcLX7J57ropDGOp3n9OBTvt4uF0PgQnbSTkqg@mail.gmail.com>
	<ivgdf8$ka7$1@dough.gmane.org>
	<CAH0g_axFWROiO-dvZz9XX1nrbTB_SFuvGfLFcVMWKnzFteEccA@mail.gmail.com>
	<ivh526$bl3$1@dough.gmane.org>
	<CAH0g_aybrx47YV+Mb9hQ480xvb+3O3dUPXLE5JouHvGLZKqpRQ@mail.gmail.com>
	<ivj04k$9us$1@dough.gmane.org>
Message-ID: <CAH0g_azYS67Y=5=rY17OGh1E-XEUS0TA_8DuE3sLoNJ=im6tsQ@mail.gmail.com>

On Tue, Jul 12, 2011 at 10:32 PM, Emile van Sebille <emile at fenx.com> wrote:
> On 7/12/2011 4:01 PM Edgar Almonte said...
>>
>> On Tue, Jul 12, 2011 at 5:44 AM, Peter Otten<__peter__ at web.de> ?wrote:
>
> <snip>
>>>
>>> import csv
>
> imports the comma separated values (csv) file handler utilities module
>
>>>
>>> def sortkey(row):
>>> ? ?if float(row[1]):
>>> ? ? ? ?return row[1], True
>>> ? ?else:
>>> ? ? ? ?return row[2], False
>
> ... sortkey defines a function that accepts a cvs.reader data row, and
> returns either row[1] and True or row[2] and False based on which of row[1]
> and row[2] has a non-zero value
>
>>>
>>> with open("infile.txt", "rb") as instream:
>>> ? ?rows = sorted(csv.reader(instream, delimiter="|"), key=sortkey)
>
> rows becomes the sortkey sorted result of the lines of infile.txt
>
>>>
>>> with open("outfile.txt", "wb") as outstream:
>>> ? ?csv.writer(outstream, delimiter="|").writerows(rows)
>
> ... and this writes those results to outfile.txt
>
> you might also try the shortened:
>
> from csv import reader,writer
>
> def sortkey(row): return max(row[1],row[2]),row[1]>row[2]
>
> writer(open("outfile.txt", "wb"), delimiter="|").writerows(
> sorted(reader(open("infile.txt", "rb"), delimiter="|"),key=sortkey))
>
>
> Emile
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

fist time i saw the statement "with" , is part of the module csv ? ,
that make a loop through the file ? is not the sortkey function
waiting for a paramenter ( the row ) ? i don't see how is get pass ,
the "key" is a parameter of sorted function ? , reader is a function
of csv module ? if "with..." is a loop  that go through the file is
the second with inside of that loop ? ( i dont see how the write of
the output file catch the line readed

Thanks again for the helping of my understand

From armvrt at gmail.com  Wed Jul 13 16:41:22 2011
From: armvrt at gmail.com (Shwinn Ricci)
Date: Wed, 13 Jul 2011 10:41:22 -0400
Subject: [Tutor] GUI selection help
Message-ID: <CAM-hM0Xgd38wjvDwbwJN3JiSOQU6nqX2jJd_CXWytLiadRSYZA@mail.gmail.com>

Hey all,

I am browsing through the large list of apps for creating GUIs from python
on http://wiki.python.org/moin/GuiProgramming but unfortunately don't know
which one is the best for my project, which involves mapping a point on a
2-Dimensional surface to a 3-Dimensional structure by having users move
their mouse over the 2-D surface to light up a respective point on the 3-D
surface. The GUI should also allow me to implement rotated camera angles for
the 3-D structure. Does the GUI I select matter at all? Any pointers would
be appreciated.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110713/3f6d3c66/attachment.html>

From __peter__ at web.de  Wed Jul 13 17:02:10 2011
From: __peter__ at web.de (Peter Otten)
Date: Wed, 13 Jul 2011 17:02:10 +0200
Subject: [Tutor] compare and arrange file
References: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>
	<ivfu3r$bdf$1@dough.gmane.org>
	<CAH0g_awUgNVnfTcLX7J57ropDGOp3n9OBTvt4uF0PgQnbSTkqg@mail.gmail.com>
	<ivgdf8$ka7$1@dough.gmane.org>
	<CAH0g_axFWROiO-dvZz9XX1nrbTB_SFuvGfLFcVMWKnzFteEccA@mail.gmail.com>
	<ivh526$bl3$1@dough.gmane.org>
	<CAH0g_aybrx47YV+Mb9hQ480xvb+3O3dUPXLE5JouHvGLZKqpRQ@mail.gmail.com>
	<ivj04k$9us$1@dough.gmane.org>
	<CAH0g_azYS67Y=5=rY17OGh1E-XEUS0TA_8DuE3sLoNJ=im6tsQ@mail.gmail.com>
Message-ID: <ivkc18$rhe$1@dough.gmane.org>

Edgar Almonte wrote:

> fist time i saw the statement "with" , is part of the module csv ? ,
> that make a loop through the file ? is not the sortkey function
> waiting for a paramenter ( the row ) ? i don't see how is get pass ,
> the "key" is a parameter of sorted function ? , reader is a function
> of csv module ? if "with..." is a loop  that go through the file is
> the second with inside of that loop ? ( i dont see how the write of
> the output file catch the line readed

with open(filename) as fileobj:
   do_something_with(fileobj)

is a shortcut for

fileobj = open(filename)
do_something_with(fileobj)
fileobj.close()

But it is not only shorter; it also guarantees that the file will be closed 
even if an error occurs while it is being processed.

In my code the file object is wrapped into a csv.reader.

for row in csv.reader(fileobj, delimiter="|"):
    # do something with row

walks through the file one row at a time where the row is a list of the 
columns. To be able to sort these rows you have to read them all into 
memory. You typically do that with

rows_iter = csv.reader(fileobj, delimiter="|")
rows = list(rows_iter)

and can then sort the rows with

rows.sort()

Because this two-step process is so common there is a builtin sorted() that 
converts an iterable (the rows here) into a sorted list. Now consider the 
following infile:

$ cat infile.txt
aXXXXXXXX XXXX| 0000000000000.00| 0000000011111.11|
bXXXXXXXX XXXX| 0000000000000.00| 0000000011111.11|
XXXXXXXXX XXXX| 0000000000000.00| 0000000088115.39|
XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|
XXXXXXXXX XXXX| 0000000000000.00| 0000000090443.29|
cXXXXXXXX XXXX| 0000000011111.11| 0000000000000.00|
XXXXXXXXX XXXX| 0000000088115.39| 0000000000000.00|
XXXXXXXXX XXXX| 0000000000000.00| 0000000088335.39|
XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|
XXXXXXXXX XXXX| 0000000088335.39| 0000000000000.00|
XXXXXXXXX XXXX| 0000000090443.29| 0000000000000.00|
dXXXXXXXX XXXX| 0000000011111.11| 0000000000000.00|

If we read it and sort it we get the following:

>>> import csv
>>> with open("infile.txt") as fileobj:
...     rows = sorted(csv.reader(fileobj, delimiter="|"))
...
>>> from pprint import pprint
>>> pprint(rows)
[['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000088115.39', ''],
 ['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000088335.39', ''],
 ['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000090443.29', ''],
 ['XXXXXXXXX XXXX', ' 0000000088115.39', ' 0000000000000.00', ''],
 ['XXXXXXXXX XXXX', ' 0000000088335.39', ' 0000000000000.00', ''],
 ['XXXXXXXXX XXXX', ' 0000000090443.29', ' 0000000000000.00', ''],
 ['XXXXXXXXX XXXX', ' 0000000090453.29', ' 0000000000000.00', ''],
 ['XXXXXXXXX XXXX', ' 0000000090453.29', ' 0000000000000.00', ''],
 ['aXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000011111.11', ''],
 ['bXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000011111.11', ''],
 ['cXXXXXXXX XXXX', ' 0000000011111.11', ' 0000000000000.00', ''],
 ['dXXXXXXXX XXXX', ' 0000000011111.11', ' 0000000000000.00', '']]

Can you infer the sort order of the list of lists above? The rows are sorted 
by the first item in the list, then rows whose first item compares equal are 
sorted by the second and so on. This sort order is not something built into 
the sort() method, but rather the objects that are compared. sort() uses the 
usual operators like < and == internally. Now what would you do if you 
wanted to sort your data by the third column, say? Here the key parameter 
comes into play. You can use it to provide a function that takes an item in 
the list to be sorted and returns something that is used instead of the 
items to compare them to each other:

>> def extract_third_column(row):
...     return row[2]
...
>>> rows.sort(key=extract_third_column)
>>> pprint(rows)
[['XXXXXXXXX XXXX', ' 0000000088115.39', ' 0000000000000.00', ''],
 ['XXXXXXXXX XXXX', ' 0000000088335.39', ' 0000000000000.00', ''],
 ['XXXXXXXXX XXXX', ' 0000000090443.29', ' 0000000000000.00', ''],
 ['XXXXXXXXX XXXX', ' 0000000090453.29', ' 0000000000000.00', ''],
 ['XXXXXXXXX XXXX', ' 0000000090453.29', ' 0000000000000.00', ''],
 ['cXXXXXXXX XXXX', ' 0000000011111.11', ' 0000000000000.00', ''],
 ['dXXXXXXXX XXXX', ' 0000000011111.11', ' 0000000000000.00', ''],
 ['aXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000011111.11', ''],
 ['bXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000011111.11', ''],
 ['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000088115.39', ''],
 ['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000088335.39', ''],
 ['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000090443.29', '']]

The key function you actually need is a bit more sophisticated. You want 
rows with equal nonzero values to end close together, no matter whether the 
interesting value is in the second or third column. Let's try:

>>> def extract_nonzero_column(row):
...     if row[1] == ' 0000000000000.00':
...             return row[2]
...     else:
...             return row[1]
...

Here's a preview of the keys:

>>> for row in rows:
...     print extract_nonzero_column(row)
...
 0000000088115.39
 0000000088335.39
 0000000090443.29
 0000000090453.29
 0000000090453.29
 0000000011111.11
 0000000011111.11
 0000000011111.11
 0000000011111.11
 0000000088115.39
 0000000088335.39
 0000000090443.29

Looks good, let's apply:

>>> pprint(sorted(rows, key=extract_nonzero_column))
[['cXXXXXXXX XXXX', ' 0000000011111.11', ' 0000000000000.00', ''],
 ['dXXXXXXXX XXXX', ' 0000000011111.11', ' 0000000000000.00', ''],
 ['aXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000011111.11', ''],
 ['bXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000011111.11', ''],
 ['XXXXXXXXX XXXX', ' 0000000088115.39', ' 0000000000000.00', ''],
 ['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000088115.39', ''],
 ['XXXXXXXXX XXXX', ' 0000000088335.39', ' 0000000000000.00', ''],
 ['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000088335.39', ''],
 ['XXXXXXXXX XXXX', ' 0000000090443.29', ' 0000000000000.00', ''],
 ['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000090443.29', ''],
 ['XXXXXXXXX XXXX', ' 0000000090453.29', ' 0000000000000.00', ''],
 ['XXXXXXXXX XXXX', ' 0000000090453.29', ' 0000000000000.00', '']]

Almost there, but we want the rows with nonzero values in the third column 
before those with nonzero values in the second. Emile's and my solution was 
to add a flag to the sort key, True if the nonzero value is in the first, 
False else because False < True in python:

>>> sorted([True, False, False, True, False])
[False, False, False, True, True]

Just as with the rows the flag is the second item in the result tuple, and 
is only used to sort the items if their first value compares equal.

>>> def sortkey(row):
...     if row[1] == ' 0000000000000.00':
...             return row[2], False
...     else:
...             return row[1], True
...
>>> rows.sort(key=sortkey)
>>> pprint(rows)
[['aXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000011111.11', ''],
 ['bXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000011111.11', ''],
 ['cXXXXXXXX XXXX', ' 0000000011111.11', ' 0000000000000.00', ''],
 ['dXXXXXXXX XXXX', ' 0000000011111.11', ' 0000000000000.00', ''],
 ['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000088115.39', ''],
 ['XXXXXXXXX XXXX', ' 0000000088115.39', ' 0000000000000.00', ''],
 ['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000088335.39', ''],
 ['XXXXXXXXX XXXX', ' 0000000088335.39', ' 0000000000000.00', ''],
 ['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000090443.29', ''],
 ['XXXXXXXXX XXXX', ' 0000000090443.29', ' 0000000000000.00', ''],
 ['XXXXXXXXX XXXX', ' 0000000090453.29', ' 0000000000000.00', ''],
 ['XXXXXXXXX XXXX', ' 0000000090453.29', ' 0000000000000.00', '']]

Now you just have to write the result back to a file.

Two problems remain: unpaired values are not detected and duplicate values 
destroy the right-left-right-left alteration, too.

Bonus: Python's list.sort() method is "stable", it doesn't affect the 
relative order of items in the list that compare equal. This allows to 
replace one sort with a complex key with two sorts with simpler keys:

>>> rows.sort(key=lambda row: row[1])
>>> rows.sort(key=lambda row: max(row[1:]))



From waynejwerner at gmail.com  Wed Jul 13 17:36:09 2011
From: waynejwerner at gmail.com (Wayne Werner)
Date: Wed, 13 Jul 2011 10:36:09 -0500
Subject: [Tutor] GUI selection help
In-Reply-To: <CAM-hM0Xgd38wjvDwbwJN3JiSOQU6nqX2jJd_CXWytLiadRSYZA@mail.gmail.com>
References: <CAM-hM0Xgd38wjvDwbwJN3JiSOQU6nqX2jJd_CXWytLiadRSYZA@mail.gmail.com>
Message-ID: <CAPM86NfF-+X6Jz4R5LqmUsY4Gmudwoh6TNkrmR4GLjfRm7jNVA@mail.gmail.com>

On Wed, Jul 13, 2011 at 9:41 AM, Shwinn Ricci <armvrt at gmail.com> wrote:

> Hey all,
>
> I am browsing through the large list of apps for creating GUIs from python
> on http://wiki.python.org/moin/GuiProgramming but unfortunately don't know
> which one is the best for my project, which involves mapping a point on a
> 2-Dimensional surface to a 3-Dimensional structure by having users move
> their mouse over the 2-D surface to light up a respective point on the 3-D
> surface. The GUI should also allow me to implement rotated camera angles for
> the 3-D structure. Does the GUI I select matter at all? Any pointers would
> be appreciated.
>

Do you have any experience with 3d programming? If you've already familiar
with OpenGL, you can use the pyglet framework that gives you OpenGL
bindings.

Of course, if you already have a way to do the 3d part, then your GUI
framework really doesn't matter - Tkinter is probably the easiest one to
use, wxPython give you native-looking widgets (if you're using Windows, your
apps will look like other Windows apps), PyGTK+ is great if you plan to use
the Gnome window manager under Linux, and PyQT is good for KDE and contains
everything but the kitchen sink. Also you'll be using your left pinky /all/
the time because everything you use has "q" in it.

If all you need to do is display an image and track where the mouse
click/drags are happening, I'd probably use Tkinter.

-HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110713/e4e1b915/attachment-0001.html>

From susana.delgado_s at utzmg.edu.mx  Wed Jul 13 19:23:00 2011
From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez)
Date: Wed, 13 Jul 2011 12:23:00 -0500
Subject: [Tutor] Get file last user
Message-ID: <CAFEP6HtFJVCGwYx0i4JDmFAkjd_RfdBthzBLTFpJArFKy9RMpA@mail.gmail.com>

Hello list!!!

I want to get the last user who accessed to a file, I already have the way
to know who owns the file, but I really need to get this information.
To get file user I'm using: os.environ.get("USERNAME") and to get the
machine host: socket.gethostname()
Is there a way to find out who used the file for the last time?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110713/22cf2374/attachment.html>

From steve at pearwood.info  Wed Jul 13 19:28:24 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 14 Jul 2011 03:28:24 +1000
Subject: [Tutor] Get file last user
In-Reply-To: <CAFEP6HtFJVCGwYx0i4JDmFAkjd_RfdBthzBLTFpJArFKy9RMpA@mail.gmail.com>
References: <CAFEP6HtFJVCGwYx0i4JDmFAkjd_RfdBthzBLTFpJArFKy9RMpA@mail.gmail.com>
Message-ID: <4E1DD5B8.3040807@pearwood.info>

Susana Iraiis Delgado Rodriguez wrote:
> Hello list!!!
> 
> I want to get the last user who accessed to a file, I already have the way
> to know who owns the file, but I really need to get this information.
> To get file user I'm using: os.environ.get("USERNAME") and to get the
> machine host: socket.gethostname()
> Is there a way to find out who used the file for the last time?


I don't believe so. As far as I know, that information simply isn't 
recorded anywhere.


-- 
Steven


From MPirritano at ochca.com  Wed Jul 13 20:17:41 2011
From: MPirritano at ochca.com (Pirritano, Matthew)
Date: Wed, 13 Jul 2011 11:17:41 -0700
Subject: [Tutor] copy and paste excel worksheet using win32
In-Reply-To: <4E1DD5B8.3040807@pearwood.info>
References: <CAFEP6HtFJVCGwYx0i4JDmFAkjd_RfdBthzBLTFpJArFKy9RMpA@mail.gmail.com>
	<4E1DD5B8.3040807@pearwood.info>
Message-ID: <A715D7E005BF1C4D8505CA3CABB748F20463939D@HCAMAIL03.ochca.com>

Pythonistas,

I have a nicely formatted report in excel that is designed to be filled
in by an excel macro. But first I need to get the report worksheet into
52 separate excel workbooks.

Here's what I've tried so far. I'm snipping the code a bit. I have a wx
dialog that gets a directory where the excel files live that will have
the report worksheet added to them. The variable 'infile' is really a
directory, and comes from the results of the wx dialog. Then I step
through the directory and create a list of the files. Next I start excel
and open the file with the report, then I'm trying to copy that report
into each of the files in the directory.  Below is the error I get and
the syntax.

I'm also sure each time before I run it that there is no excel process
still running.

Any help is much appreciated! Thanks,
Matt

Here's the error:

Traceback (most recent call last):
  File "C:\Projects\Copy_Worksheets_20110713.py", line 50, in <module>
    reportWs(2).Copy(None, wbWorksheets(1))
  File "C:\Python25\lib\site-packages\win32com\client\dynamic.py", line
172, in __call__
    return
self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.def
aultDispatchName,None)
com_error: (-2147352573, 'Member not found.', None, None)


Here's the code:

fileList = ()
for infile in glob.iglob( os.path.join(infile, '*.xls') ):
    print "current file is: " + infile
    print ''
    
    fileList = fileList + (infile,)   


excel = win32com.client.Dispatch("Excel.Application")
reportWb =
excel.Workbooks.open("D:\\Data\\Excel\\BHS_Report_Format_20110713.xls")
reportWs = reportWb.Worksheets(1)

for f in fileList:
    print "processing file: " + f
    wb = excel.Workbooks.Open(f)
    wbWorksheets = wb.Worksheets(1)
    wbWorksheets.Activate()
    reportWs(2).Copy(None, wbWorksheets(1))
    wb.Close(True)

reportWb.Close(True)
exce.Quit()






Matthew Pirritano, Ph.D.
Research Analyst IV
Medical Services Initiative (MSI)
Orange County Health Care Agency
(714) 568-5648

From alan.gauld at btinternet.com  Tue Jul 12 22:30:19 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 12 Jul 2011 21:30:19 +0100
Subject: [Tutor] Get file last user
In-Reply-To: <CAFEP6HtFJVCGwYx0i4JDmFAkjd_RfdBthzBLTFpJArFKy9RMpA@mail.gmail.com>
References: <CAFEP6HtFJVCGwYx0i4JDmFAkjd_RfdBthzBLTFpJArFKy9RMpA@mail.gmail.com>
Message-ID: <4E1CAEDB.4090903@btinternet.com>

Susana Iraiis Delgado Rodriguez wrote:
> Hello list!!!
> 
> I want to get the last user who accessed to a file, ...
> Is there a way to find out who used the file for the last time?

You don't say wgich OS you are using, which bis alklimportant.l Heavy 
duty industrial OS like OS.390,Pick and VAX VMS do record an audit 
trail, if the admin has switched that on. But mid range OS like Windows 
and Unix do not, so far as I know, record who made a change, just when 
the change was made. But that also probably depends on the filesystem in 
Linux, some of the more exotic ones may support audit trails.

If you really need to know who made changes you need to use a version 
control system like RCS, CVS, SVN, etc. Thats what they are designed to 
do, amongst other things...

HTH,

Alan G.
(From my Netbook because my PC broke! Boohoo... :-(


From alan.gauld at btinternet.com  Tue Jul 12 22:36:01 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 12 Jul 2011 21:36:01 +0100
Subject: [Tutor] Get file last user
In-Reply-To: <CAFEP6HtFJVCGwYx0i4JDmFAkjd_RfdBthzBLTFpJArFKy9RMpA@mail.gmail.com>
References: <CAFEP6HtFJVCGwYx0i4JDmFAkjd_RfdBthzBLTFpJArFKy9RMpA@mail.gmail.com>
Message-ID: <4E1CB031.2010008@btinternet.com>

Susana Iraiis Delgado Rodriguez wrote:
> Hello list!!!
> 
> I want to get the last user who accessed to a file, ...
> Is there a way to find out who used the file for the last time?

You don't say which OS you are using, which is allimportant. Heavy duty 
industrial OS like OS.390,Pick and VAX VMS do record an audit trail, if 
the admin has switched that on. But mid range OS like Windows and Unix 
do not, so far as I know, record who made a change, just when the change 
was made. But that also probably depends on the filesystem in Linux, 
some of the more exotic ones may support audit trails.

If you really need to know who made changes you need to use a version 
control system like RCS, CVS, SVN, etc. Thats what they are designed to 
do, amongst other things...

HTH,

Alan G.
(From my Netbook because my PC broke! Boohoo... :-(


From alan.gauld at btinternet.com  Tue Jul 12 22:32:37 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 12 Jul 2011 21:32:37 +0100
Subject: [Tutor] Get file last user
In-Reply-To: <CAFEP6HtFJVCGwYx0i4JDmFAkjd_RfdBthzBLTFpJArFKy9RMpA@mail.gmail.com>
References: <CAFEP6HtFJVCGwYx0i4JDmFAkjd_RfdBthzBLTFpJArFKy9RMpA@mail.gmail.com>
Message-ID: <4E1CAF65.9060806@btinternet.com>

Susana Iraiis Delgado Rodriguez wrote:
> Hello list!!!
> 
> I want to get the last user who accessed to a file, ...
> Is there a way to find out who used the file for the last time?

You don't say wgich OS you are using, which bis alklimportant.l Heavy
duty industrial OS like OS.390,Pick and VAX VMS do record an audit
trail, if the admin has swirtchedv that on. But mid range OS like
Windows and Unix do not, so fgar as I know, record who made a change,
just when the change was made. But that also probably depends on the
filesystem in Linux, some of the more exotic ones may support audit trails.

If you really need to know who made changes you need to use a version
control system like RCS, CVS, SVN, etc. Thats what they are designed to
do, amongst other things...

HTH,





From alan.gauld at btinternet.com  Tue Jul 12 22:34:59 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 12 Jul 2011 21:34:59 +0100
Subject: [Tutor] Get file last user
In-Reply-To: <CAFEP6HtFJVCGwYx0i4JDmFAkjd_RfdBthzBLTFpJArFKy9RMpA@mail.gmail.com>
References: <CAFEP6HtFJVCGwYx0i4JDmFAkjd_RfdBthzBLTFpJArFKy9RMpA@mail.gmail.com>
Message-ID: <4E1CAFF3.7070500@btinternet.com>

Susana Iraiis Delgado Rodriguez wrote:
> Hello list!!!
> 
> I want to get the last user who accessed to a file, ...
> Is there a way to find out who used the file for the last time?

You don't say which OS you are using, which bis alklimportant.l Heavy
duty industrial OS like OS.390,Pick and VAX VMS do record an audit
trail, if the admin has swirtchedv that on. But mid range OS like
Windows and Unix do not, so fgar as I know, record who made a change,
just when the change was made. But that also probably depends on the
filesystem in Linux, some of the more exotic ones may support audit trails.

If you really need to know who made changes you need to use a version
control system like RCS, CVS, SVN, etc. Thats what they are designed to
do, amongst other things...

HTH,

Alan G



From knacktus at googlemail.com  Thu Jul 14 11:44:28 2011
From: knacktus at googlemail.com (Knacktus)
Date: Thu, 14 Jul 2011 11:44:28 +0200
Subject: [Tutor] Descriptors and type declaration order
Message-ID: <CAHsw7z+ZpjB49tDjR_T63ag5enLd+Juj=kTpjia9ajOb2ZOiyw@mail.gmail.com>

Hi guys,

I've got the following (not working) code:

class Attribute(object):

    def __init__(self, attribute_name, att_type_name):
        self._attribute_name = attribute_name
        try:
            self._attribute_type = globals()[att_type_name]
        except KeyError:
            self._attribute_type = getattr(globals()["__builtins__"],
att_type_name)

    def __get__(self, obj, obj_type):
        return getattr(obj, self._attribute_name)

    def __set__(self, obj, value):
        if isinstance(value, self._attribute_type):
            setattr(obj, self._attribute_name, value)
        else:
            raise ItemTypeException(self._attribute_type, type(value))

class BaseItem(object):

    ident = Attribute("ident", "int")
    owner = Attribute("owner", "str")
    item = Attribute("item", "BaseItem")

if __name__ == "__main__":
    print "About to create an item"
    test = BaseItem()
    print "OK"

The problem is that the descriptors are created when the module is
evaluated. But at this time the class BaseItem is not known yet. Any ideas?

Cheers,

Jan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110714/9ac857b1/attachment.html>

From samudhio at gmail.com  Thu Jul 14 14:13:36 2011
From: samudhio at gmail.com (Edgar Almonte)
Date: Thu, 14 Jul 2011 08:13:36 -0400
Subject: [Tutor] compare and arrange file
In-Reply-To: <ivkc18$rhe$1@dough.gmane.org>
References: <CAH0g_ay_0EjSJVTDmaxepN_MY5nqK0uMoe0HLyaP_VGKoB_QmA@mail.gmail.com>
	<ivfu3r$bdf$1@dough.gmane.org>
	<CAH0g_awUgNVnfTcLX7J57ropDGOp3n9OBTvt4uF0PgQnbSTkqg@mail.gmail.com>
	<ivgdf8$ka7$1@dough.gmane.org>
	<CAH0g_axFWROiO-dvZz9XX1nrbTB_SFuvGfLFcVMWKnzFteEccA@mail.gmail.com>
	<ivh526$bl3$1@dough.gmane.org>
	<CAH0g_aybrx47YV+Mb9hQ480xvb+3O3dUPXLE5JouHvGLZKqpRQ@mail.gmail.com>
	<ivj04k$9us$1@dough.gmane.org>
	<CAH0g_azYS67Y=5=rY17OGh1E-XEUS0TA_8DuE3sLoNJ=im6tsQ@mail.gmail.com>
	<ivkc18$rhe$1@dough.gmane.org>
Message-ID: <CAH0g_aypJ95Y-U0BvvULwNAzEC5XKOnnsNXL-k-7CXQeDVZa+w@mail.gmail.com>

On Wed, Jul 13, 2011 at 11:02 AM, Peter Otten <__peter__ at web.de> wrote:
> Edgar Almonte wrote:
>
>> fist time i saw the statement "with" , is part of the module csv ? ,
>> that make a loop through the file ? is not the sortkey function
>> waiting for a paramenter ( the row ) ? i don't see how is get pass ,
>> the "key" is a parameter of sorted function ? , reader is a function
>> of csv module ? if "with..." is a loop ?that go through the file is
>> the second with inside of that loop ? ( i dont see how the write of
>> the output file catch the line readed
>
> with open(filename) as fileobj:
> ? do_something_with(fileobj)
>
> is a shortcut for
>
> fileobj = open(filename)
> do_something_with(fileobj)
> fileobj.close()
>
> But it is not only shorter; it also guarantees that the file will be closed
> even if an error occurs while it is being processed.
>
> In my code the file object is wrapped into a csv.reader.
>
> for row in csv.reader(fileobj, delimiter="|"):
> ? ?# do something with row
>
> walks through the file one row at a time where the row is a list of the
> columns. To be able to sort these rows you have to read them all into
> memory. You typically do that with
>
> rows_iter = csv.reader(fileobj, delimiter="|")
> rows = list(rows_iter)
>
> and can then sort the rows with
>
> rows.sort()
>
> Because this two-step process is so common there is a builtin sorted() that
> converts an iterable (the rows here) into a sorted list. Now consider the
> following infile:
>
> $ cat infile.txt
> aXXXXXXXX XXXX| 0000000000000.00| 0000000011111.11|
> bXXXXXXXX XXXX| 0000000000000.00| 0000000011111.11|
> XXXXXXXXX XXXX| 0000000000000.00| 0000000088115.39|
> XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|
> XXXXXXXXX XXXX| 0000000000000.00| 0000000090443.29|
> cXXXXXXXX XXXX| 0000000011111.11| 0000000000000.00|
> XXXXXXXXX XXXX| 0000000088115.39| 0000000000000.00|
> XXXXXXXXX XXXX| 0000000000000.00| 0000000088335.39|
> XXXXXXXXX XXXX| 0000000090453.29| 0000000000000.00|
> XXXXXXXXX XXXX| 0000000088335.39| 0000000000000.00|
> XXXXXXXXX XXXX| 0000000090443.29| 0000000000000.00|
> dXXXXXXXX XXXX| 0000000011111.11| 0000000000000.00|
>
> If we read it and sort it we get the following:
>
>>>> import csv
>>>> with open("infile.txt") as fileobj:
> ... ? ? rows = sorted(csv.reader(fileobj, delimiter="|"))
> ...
>>>> from pprint import pprint
>>>> pprint(rows)
> [['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000088115.39', ''],
> ?['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000088335.39', ''],
> ?['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000090443.29', ''],
> ?['XXXXXXXXX XXXX', ' 0000000088115.39', ' 0000000000000.00', ''],
> ?['XXXXXXXXX XXXX', ' 0000000088335.39', ' 0000000000000.00', ''],
> ?['XXXXXXXXX XXXX', ' 0000000090443.29', ' 0000000000000.00', ''],
> ?['XXXXXXXXX XXXX', ' 0000000090453.29', ' 0000000000000.00', ''],
> ?['XXXXXXXXX XXXX', ' 0000000090453.29', ' 0000000000000.00', ''],
> ?['aXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000011111.11', ''],
> ?['bXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000011111.11', ''],
> ?['cXXXXXXXX XXXX', ' 0000000011111.11', ' 0000000000000.00', ''],
> ?['dXXXXXXXX XXXX', ' 0000000011111.11', ' 0000000000000.00', '']]
>
> Can you infer the sort order of the list of lists above? The rows are sorted
> by the first item in the list, then rows whose first item compares equal are
> sorted by the second and so on. This sort order is not something built into
> the sort() method, but rather the objects that are compared. sort() uses the
> usual operators like < and == internally. Now what would you do if you
> wanted to sort your data by the third column, say? Here the key parameter
> comes into play. You can use it to provide a function that takes an item in
> the list to be sorted and returns something that is used instead of the
> items to compare them to each other:
>
>>> def extract_third_column(row):
> ... ? ? return row[2]
> ...
>>>> rows.sort(key=extract_third_column)
>>>> pprint(rows)
> [['XXXXXXXXX XXXX', ' 0000000088115.39', ' 0000000000000.00', ''],
> ?['XXXXXXXXX XXXX', ' 0000000088335.39', ' 0000000000000.00', ''],
> ?['XXXXXXXXX XXXX', ' 0000000090443.29', ' 0000000000000.00', ''],
> ?['XXXXXXXXX XXXX', ' 0000000090453.29', ' 0000000000000.00', ''],
> ?['XXXXXXXXX XXXX', ' 0000000090453.29', ' 0000000000000.00', ''],
> ?['cXXXXXXXX XXXX', ' 0000000011111.11', ' 0000000000000.00', ''],
> ?['dXXXXXXXX XXXX', ' 0000000011111.11', ' 0000000000000.00', ''],
> ?['aXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000011111.11', ''],
> ?['bXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000011111.11', ''],
> ?['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000088115.39', ''],
> ?['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000088335.39', ''],
> ?['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000090443.29', '']]
>
> The key function you actually need is a bit more sophisticated. You want
> rows with equal nonzero values to end close together, no matter whether the
> interesting value is in the second or third column. Let's try:
>
>>>> def extract_nonzero_column(row):
> ... ? ? if row[1] == ' 0000000000000.00':
> ... ? ? ? ? ? ? return row[2]
> ... ? ? else:
> ... ? ? ? ? ? ? return row[1]
> ...
>
> Here's a preview of the keys:
>
>>>> for row in rows:
> ... ? ? print extract_nonzero_column(row)
> ...
> ?0000000088115.39
> ?0000000088335.39
> ?0000000090443.29
> ?0000000090453.29
> ?0000000090453.29
> ?0000000011111.11
> ?0000000011111.11
> ?0000000011111.11
> ?0000000011111.11
> ?0000000088115.39
> ?0000000088335.39
> ?0000000090443.29
>
> Looks good, let's apply:
>
>>>> pprint(sorted(rows, key=extract_nonzero_column))
> [['cXXXXXXXX XXXX', ' 0000000011111.11', ' 0000000000000.00', ''],
> ?['dXXXXXXXX XXXX', ' 0000000011111.11', ' 0000000000000.00', ''],
> ?['aXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000011111.11', ''],
> ?['bXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000011111.11', ''],
> ?['XXXXXXXXX XXXX', ' 0000000088115.39', ' 0000000000000.00', ''],
> ?['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000088115.39', ''],
> ?['XXXXXXXXX XXXX', ' 0000000088335.39', ' 0000000000000.00', ''],
> ?['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000088335.39', ''],
> ?['XXXXXXXXX XXXX', ' 0000000090443.29', ' 0000000000000.00', ''],
> ?['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000090443.29', ''],
> ?['XXXXXXXXX XXXX', ' 0000000090453.29', ' 0000000000000.00', ''],
> ?['XXXXXXXXX XXXX', ' 0000000090453.29', ' 0000000000000.00', '']]
>
> Almost there, but we want the rows with nonzero values in the third column
> before those with nonzero values in the second. Emile's and my solution was
> to add a flag to the sort key, True if the nonzero value is in the first,
> False else because False < True in python:
>
>>>> sorted([True, False, False, True, False])
> [False, False, False, True, True]
>
> Just as with the rows the flag is the second item in the result tuple, and
> is only used to sort the items if their first value compares equal.
>
>>>> def sortkey(row):
> ... ? ? if row[1] == ' 0000000000000.00':
> ... ? ? ? ? ? ? return row[2], False
> ... ? ? else:
> ... ? ? ? ? ? ? return row[1], True
> ...
>>>> rows.sort(key=sortkey)
>>>> pprint(rows)
> [['aXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000011111.11', ''],
> ?['bXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000011111.11', ''],
> ?['cXXXXXXXX XXXX', ' 0000000011111.11', ' 0000000000000.00', ''],
> ?['dXXXXXXXX XXXX', ' 0000000011111.11', ' 0000000000000.00', ''],
> ?['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000088115.39', ''],
> ?['XXXXXXXXX XXXX', ' 0000000088115.39', ' 0000000000000.00', ''],
> ?['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000088335.39', ''],
> ?['XXXXXXXXX XXXX', ' 0000000088335.39', ' 0000000000000.00', ''],
> ?['XXXXXXXXX XXXX', ' 0000000000000.00', ' 0000000090443.29', ''],
> ?['XXXXXXXXX XXXX', ' 0000000090443.29', ' 0000000000000.00', ''],
> ?['XXXXXXXXX XXXX', ' 0000000090453.29', ' 0000000000000.00', ''],
> ?['XXXXXXXXX XXXX', ' 0000000090453.29', ' 0000000000000.00', '']]
>
> Now you just have to write the result back to a file.
>
> Two problems remain: unpaired values are not detected and duplicate values
> destroy the right-left-right-left alteration, too.
>
> Bonus: Python's list.sort() method is "stable", it doesn't affect the
> relative order of items in the list that compare equal. This allows to
> replace one sort with a complex key with two sorts with simpler keys:
>
>>>> rows.sort(key=lambda row: row[1])
>>>> rows.sort(key=lambda row: max(row[1:]))
>
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Thanks a lot peter for you time to explain this to me , i do a fast
read of everything and i get almost everything , i will re-read later
and play with some test for better understand , thanks again !

From d at davea.name  Thu Jul 14 14:19:42 2011
From: d at davea.name (Dave Angel)
Date: Thu, 14 Jul 2011 08:19:42 -0400
Subject: [Tutor] Descriptors and type declaration order
In-Reply-To: <CAHsw7z+ZpjB49tDjR_T63ag5enLd+Juj=kTpjia9ajOb2ZOiyw@mail.gmail.com>
References: <CAHsw7z+ZpjB49tDjR_T63ag5enLd+Juj=kTpjia9ajOb2ZOiyw@mail.gmail.com>
Message-ID: <4E1EDEDE.7070103@davea.name>

On 07/14/2011 05:44 AM, Knacktus wrote:
> Hi guys,
>
> I've got the following (not working) code:
>
> class Attribute(object):
>
>      def __init__(self, attribute_name, att_type_name):
>          self._attribute_name = attribute_name
>          try:
>              self._attribute_type = globals()[att_type_name]
>          except KeyError:
>              self._attribute_type = getattr(globals()["__builtins__"],
> att_type_name)
>
>      def __get__(self, obj, obj_type):
>          return getattr(obj, self._attribute_name)
>
>      def __set__(self, obj, value):
>          if isinstance(value, self._attribute_type):
>              setattr(obj, self._attribute_name, value)
>          else:
>              raise ItemTypeException(self._attribute_type, type(value))
>
> class BaseItem(object):
>
>      ident = Attribute("ident", "int")
>      owner = Attribute("owner", "str")
>      item = Attribute("item", "BaseItem")
>
> if __name__ == "__main__":
>      print "About to create an item"
>      test = BaseItem()
>      print "OK"
>
> The problem is that the descriptors are created when the module is
> evaluated. But at this time the class BaseItem is not known yet. Any ideas?
>
> Cheers,
>
> Jan
>
It's customary to include a traceback when asking a question like this, 
because many people might then be able to give advice without actually 
having to create the file and try it.

So here's the error I get with 2.7.1

Traceback (most recent call last):
   File "test2.py", line 19, in <module>
     class BaseItem(object):
   File "test2.py", line 23, in BaseItem
     item = Attribute("item", "BaseItem")
   File "test2.py", line 8, in __init__
     self._attribute_type = getattr(globals()["__builtins__"], 
att_type_name)
AttributeError: 'module' object has no attribute 'BaseItem'


I had expected from your question that the error would occur when trying 
to instantiate the 'test' instance of BaseItem, but it never gets that 
far. The problem is that in creating the class, you're trying to use the 
class' type.  But that's not added to the globals dictionary till the 
class definition is complete.

One workaround is to move the last line of the class definition outside, 
so you end up with the following:

class BaseItem(object):

     ident = Attribute("ident", "int")
     owner = Attribute("owner", "str")

BaseItem.item = Attribute("item", "BaseItem")

There may very well be a better answer, and I'd enjoy knowing what it is.
-

DaveA


From emile at fenx.com  Thu Jul 14 14:22:07 2011
From: emile at fenx.com (Emile van Sebille)
Date: Thu, 14 Jul 2011 05:22:07 -0700
Subject: [Tutor] Descriptors and type declaration order
In-Reply-To: <CAHsw7z+ZpjB49tDjR_T63ag5enLd+Juj=kTpjia9ajOb2ZOiyw@mail.gmail.com>
References: <CAHsw7z+ZpjB49tDjR_T63ag5enLd+Juj=kTpjia9ajOb2ZOiyw@mail.gmail.com>
Message-ID: <ivmmto$q77$1@dough.gmane.org>

On 7/14/2011 2:44 AM Knacktus said...
> Hi guys,
>
> I've got the following (not working) code:
>
> class Attribute(object):
>
>      def __init__(self, attribute_name, att_type_name):
>          self._attribute_name = attribute_name
>          try:
>              self._attribute_type = globals()[att_type_name]
>          except KeyError:
>              self._attribute_type = getattr(globals()["__builtins__"],
> att_type_name)
>
>      def __get__(self, obj, obj_type):
>          return getattr(obj, self._attribute_name)
>
>      def __set__(self, obj, value):
>          if isinstance(value, self._attribute_type):
>              setattr(obj, self._attribute_name, value)
>          else:
>              raise ItemTypeException(self._attribute_type, type(value))
>
> class BaseItem(object):
>
>      ident = Attribute("ident", "int")
>      owner = Attribute("owner", "str")
>      item = Attribute("item", "BaseItem")
>
> if __name__ == "__main__":
>      print "About to create an item"
>      test = BaseItem()
>      print "OK"
>
> The problem is that the descriptors are created when the module is
> evaluated. But at this time the class BaseItem is not known yet. Any ideas?


You want to embed an instance of a class as an attribute of the same 
class? Does this help:

class BaseItem(object):

      ident = Attribute("ident", "int")
      owner = Attribute("owner", "str")


BaseItem.item = Attribute("item", "BaseItem")


Emile



From steve at pearwood.info  Thu Jul 14 15:01:19 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 14 Jul 2011 23:01:19 +1000
Subject: [Tutor] Descriptors and type declaration order
In-Reply-To: <CAHsw7z+ZpjB49tDjR_T63ag5enLd+Juj=kTpjia9ajOb2ZOiyw@mail.gmail.com>
References: <CAHsw7z+ZpjB49tDjR_T63ag5enLd+Juj=kTpjia9ajOb2ZOiyw@mail.gmail.com>
Message-ID: <4E1EE89F.1010907@pearwood.info>

Knacktus wrote:
> Hi guys,
> 
> I've got the following (not working) code:
[...]
> The problem is that the descriptors are created when the module is
> evaluated. But at this time the class BaseItem is not known yet. Any ideas?

Yes -- don't do that.

What are you actually trying to accomplish? Embedding an instance of the 
class in the class is a means to an end, not the end itself. What 
problem are you trying to solve? There may be a better way.

My *guess* is that you're trying to create properties that automatically 
check their type. As much as I think that's probably a bad idea, this is 
how I would solve that:


import functools

class CheckedProperty(property):
     def __init__(self, type, fget=None, fset=None, fdel=None, doc=None):
         if fset is not None:
             fset = self.checked(type, fset)
         super().__init__(fget, fset, fdel, doc)
     def checked(self, type, func):
         @functools.wraps(func)
         def inner(self, value):
             if not isinstance(value, type):
                 raise TypeError('invalid type')
             return func(self, value)
         return inner

class Test(object):
     def _getx(self):
         return self.__x
     def _setx(self, value):
         self.__x = value
     x = CheckedProperty(str, _getx, _setx)



But please don't over-use isinstance checks. They're a bad idea.


-- 
Steven


From susana.delgado_s at utzmg.edu.mx  Thu Jul 14 16:56:56 2011
From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez)
Date: Thu, 14 Jul 2011 09:56:56 -0500
Subject: [Tutor] Get file last user
In-Reply-To: <4E1CAEDB.4090903@btinternet.com>
References: <CAFEP6HtFJVCGwYx0i4JDmFAkjd_RfdBthzBLTFpJArFKy9RMpA@mail.gmail.com>
	<4E1CAEDB.4090903@btinternet.com>
Message-ID: <CAFEP6HvUyHh0QWjxm91=2=fhWtk_BHFX7npKOdKO6Zdcg=xBtA@mail.gmail.com>

Thank you Alan for your answer!!

Well, I'm using Windows XP to run this script!!

So I guess there's nothing I can do, about it.

Than you

2011/7/12 Alan Gauld <alan.gauld at btinternet.com>

> Susana Iraiis Delgado Rodriguez wrote:
>
>> Hello list!!!
>>
>> I want to get the last user who accessed to a file, ...
>>
>> Is there a way to find out who used the file for the last time?
>>
>
> You don't say wgich OS you are using, which bis alklimportant.l Heavy duty
> industrial OS like OS.390,Pick and VAX VMS do record an audit trail, if the
> admin has switched that on. But mid range OS like Windows and Unix do not,
> so far as I know, record who made a change, just when the change was made.
> But that also probably depends on the filesystem in Linux, some of the more
> exotic ones may support audit trails.
>
> If you really need to know who made changes you need to use a version
> control system like RCS, CVS, SVN, etc. Thats what they are designed to do,
> amongst other things...
>
> HTH,
>
> Alan G.
> (From my Netbook because my PC broke! Boohoo... :-(
>
>
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110714/b416b1ed/attachment.html>

From armvrt at gmail.com  Thu Jul 14 18:15:43 2011
From: armvrt at gmail.com (Shwinn Ricci)
Date: Thu, 14 Jul 2011 12:15:43 -0400
Subject: [Tutor] GUI selection help
In-Reply-To: <CAM-hM0Xgd38wjvDwbwJN3JiSOQU6nqX2jJd_CXWytLiadRSYZA@mail.gmail.com>
References: <CAM-hM0Xgd38wjvDwbwJN3JiSOQU6nqX2jJd_CXWytLiadRSYZA@mail.gmail.com>
Message-ID: <CAM-hM0Vuf8XRLGXqPQi3HZivS11bYYiX7myx4wu9GzCKByV=xw@mail.gmail.com>

by the way, I'm on a MAC if that helps/hurts at all.

On Wed, Jul 13, 2011 at 10:41 AM, Shwinn Ricci <armvrt at gmail.com> wrote:

> Hey all,
>
> I am browsing through the large list of apps for creating GUIs from python
> on http://wiki.python.org/moin/GuiProgramming but unfortunately don't know
> which one is the best for my project, which involves mapping a point on a
> 2-Dimensional surface to a 3-Dimensional structure by having users move
> their mouse over the 2-D surface to light up a respective point on the 3-D
> surface. The GUI should also allow me to implement rotated camera angles for
> the 3-D structure. Does the GUI I select matter at all? Any pointers would
> be appreciated.
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110714/b919825f/attachment.html>

From lmergner at gmail.com  Fri Jul 15 21:14:09 2011
From: lmergner at gmail.com (Luke Thomas Mergner)
Date: Fri, 15 Jul 2011 15:14:09 -0400
Subject: [Tutor] IDLE/tk in 10.6
Message-ID: <9887E9C5-1985-4A64-B020-9726CD6E44A0@gmail.com>

Hi,

I am not a professional programmer, but just trying to learn.

I'm running Mac 10.6 Snow Leopard.  I used MacPorts to install python26, python27, and python3.  My python interpreter loads 2.7.2 after I ran the python_select command, which is added via MacPorts I think.  

I'd like to try IDLE but there appears to be a known bug with 10.6's version of ActiveTCL.  I've installed a newer version 8.5 via their website, but this has not fixed the problem. The module tkinter is still unable to load.  Since both python and activeTCL are installed as "Frameworks" on my mac, I wonder if I need to tell python27 that there is another Tkinter installed elsewhere.  Can anyone give me some advice?

>>> import Tkinter
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 39, in <module>
    import _tkinter # If this fails your Python may not be configured for Tk
ImportError: No module named _tkinter

Luke Mergner
lmergner at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110715/5d74ecf0/attachment.html>

From charlesjohnemail at gmail.com  Fri Jul 15 21:27:31 2011
From: charlesjohnemail at gmail.com (Charles John)
Date: Fri, 15 Jul 2011 12:27:31 -0700
Subject: [Tutor] Filling orders FIFO
Message-ID: <CAHwsmpS_hSub8WvW-WFVYGxGzHO13A+Tk2P43MzQS+wDEjt7oA@mail.gmail.com>

Hi I am new to python and was wondering what the best way to create an
order(bid and offer) queue, then match a bid and offer so that if
bid==offer, creates a filled order FIFO in python cgi using mysql? Does
anybody have any ideas? It would be greatly appreciated.



Best
chuck
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110715/0d119ad3/attachment.html>

From rdmoores at gmail.com  Fri Jul 15 23:21:38 2011
From: rdmoores at gmail.com (Richard D. Moores)
Date: Fri, 15 Jul 2011 14:21:38 -0700
Subject: [Tutor] Hello World in Python without space
In-Reply-To: <ivc4h2$7ck$1@dough.gmane.org>
References: <SNT120-W4225B173E1E955B729669FBC420@phx.gbl>
	<ivc4h2$7ck$1@dough.gmane.org>
Message-ID: <CALMxxxkJ_GLxa-5TBc4Myem4wvZE6_0fxDG134VSsZsTVC_9aw@mail.gmail.com>

On Sun, Jul 10, 2011 at 05:05, Peter Otten <__peter__ at web.de> wrote:

> >>> help(print)
>
> shows
>
> print(...)
> ? ?print(value, ..., sep=' ', end='\n', file=sys.stdout)
>
> ? ?Prints the values to a stream, or to sys.stdout by default.
> ? ?Optional keyword arguments:
> ? ?file: a file-like object (stream); defaults to the current sys.stdout.
> ? ?sep: ?string inserted between values, default a space.
> ? ?end: ?string appended after the last value, default a newline.

I didn't know that printing to a file with print() was possible, so I tried

>>> print("Hello, world!", file="C:\test\test.txt")
Traceback (most recent call last):
  File "<string>", line 1, in <fragment>
builtins.AttributeError: 'str' object has no attribute 'write'
>>>

And the docs at
<http://docs.python.org/py3k/library/functions.html#print> tell me
"The file argument must be an object with a write(string) method; if
it is not present or None, sys.stdout will be used."

What do I do to test.txt to make it "an object with a write(string) method"?

Thanks,

Dick Moores

From stefan_ml at behnel.de  Fri Jul 15 23:47:23 2011
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 15 Jul 2011 23:47:23 +0200
Subject: [Tutor] Hello World in Python without space
In-Reply-To: <CALMxxxkJ_GLxa-5TBc4Myem4wvZE6_0fxDG134VSsZsTVC_9aw@mail.gmail.com>
References: <SNT120-W4225B173E1E955B729669FBC420@phx.gbl>	<ivc4h2$7ck$1@dough.gmane.org>
	<CALMxxxkJ_GLxa-5TBc4Myem4wvZE6_0fxDG134VSsZsTVC_9aw@mail.gmail.com>
Message-ID: <ivqchb$cs5$1@dough.gmane.org>

Richard D. Moores, 15.07.2011 23:21:
> On Sun, Jul 10, 2011 at 05:05, Peter Otten wrote:
>
>> >>> help(print)
>>
>> shows
>>
>> print(...)
>>     print(value, ..., sep=' ', end='\n', file=sys.stdout)
>>
>>     Prints the values to a stream, or to sys.stdout by default.
>>     Optional keyword arguments:
>>     file: a file-like object (stream); defaults to the current sys.stdout.
>>     sep:  string inserted between values, default a space.
>>     end:  string appended after the last value, default a newline.
>
> I didn't know that printing to a file with print() was possible, so I tried
>
> >>> print("Hello, world!", file="C:\test\test.txt")
> Traceback (most recent call last):
>    File "<string>", line 1, in<fragment>
> builtins.AttributeError: 'str' object has no attribute 'write'
> >>>
>
> And the docs at
> <http://docs.python.org/py3k/library/functions.html#print>  tell me
> "The file argument must be an object with a write(string) method; if
> it is not present or None, sys.stdout will be used."
>
> What do I do to test.txt to make it "an object with a write(string) method"?

Oh, there are countless ways to do that, e.g.

   class Writable(object):
       def __init__(self, something):
           print("Found a %s" % something))
       def write(self, s):
           print(s)

   print("Hello, world!", file=Writable("C:\\test\\test.txt"))

However, I'm fairly sure what you want is this:

     with open("C:\\test\\test.txt", "w") as file_object:
         print("Hello, world!", file=file_object)

Look up "open()" (open a file) and the "with statement" (used here 
basically as a safe way to make sure the file is closed after writing).

Also note that "\t" refers to a TAB character in Python, you used this 
twice in your file path string.

Stefan


From rdmoores at gmail.com  Sat Jul 16 00:58:55 2011
From: rdmoores at gmail.com (Richard D. Moores)
Date: Fri, 15 Jul 2011 15:58:55 -0700
Subject: [Tutor] Hello World in Python without space
In-Reply-To: <ivqchb$cs5$1@dough.gmane.org>
References: <SNT120-W4225B173E1E955B729669FBC420@phx.gbl>
	<ivc4h2$7ck$1@dough.gmane.org>
	<CALMxxxkJ_GLxa-5TBc4Myem4wvZE6_0fxDG134VSsZsTVC_9aw@mail.gmail.com>
	<ivqchb$cs5$1@dough.gmane.org>
Message-ID: <CALMxxxkFTF+_GhtCWHwFK=cX_w_bWMv3pWE+QQkKNO=44mBMuA@mail.gmail.com>

On Fri, Jul 15, 2011 at 14:47, Stefan Behnel <stefan_ml at behnel.de> wrote:
> Richard D. Moores, 15.07.2011 23:21:

>> What do I do to test.txt to make it "an object with a write(string)
>> method"?
>
> Oh, there are countless ways to do that, e.g.
>
> ?class Writable(object):
> ? ? ?def __init__(self, something):
> ? ? ? ? ?print("Found a %s" % something))
> ? ? ?def write(self, s):
> ? ? ? ? ?print(s)
>
> ?print("Hello, world!", file=Writable("C:\\test\\test.txt"))
>
> However, I'm fairly sure what you want is this:
>
> ? ?with open("C:\\test\\test.txt", "w") as file_object:
> ? ? ? ?print("Hello, world!", file=file_object)

Yes, went with

with open("C:\\test\\test.txt", "a+") as file_object:
      print("Hello, world!", file=file_object)

> Look up "open()" (open a file) and the "with statement" (used here basically
> as a safe way to make sure the file is closed after writing).
>
> Also note that "\t" refers to a TAB character in Python, you used this twice
> in your file path string.

Oops. I'd forgotten about that.

Thanks very much, Stefan and Donald.

Dick

From thudfoo at gmail.com  Sat Jul 16 01:21:50 2011
From: thudfoo at gmail.com (xDog Walker)
Date: Fri, 15 Jul 2011 16:21:50 -0700
Subject: [Tutor] Hello World in Python without space
In-Reply-To: <CALMxxxkFTF+_GhtCWHwFK=cX_w_bWMv3pWE+QQkKNO=44mBMuA@mail.gmail.com>
References: <SNT120-W4225B173E1E955B729669FBC420@phx.gbl>
	<ivqchb$cs5$1@dough.gmane.org>
	<CALMxxxkFTF+_GhtCWHwFK=cX_w_bWMv3pWE+QQkKNO=44mBMuA@mail.gmail.com>
Message-ID: <201107151621.50571.thudfoo@gmail.com>

On Friday 2011 July 15 15:58, Richard D. Moores wrote:
> On Fri, Jul 15, 2011 at 14:47, Stefan Behnel <stefan_ml at behnel.de> wrote:
> > Richard D. Moores, 15.07.2011 23:21:
> >> What do I do to test.txt to make it "an object with a write(string)
> >> method"?
> >
> > Oh, there are countless ways to do that, e.g.
> >
> > ?class Writable(object):
> > ? ? ?def __init__(self, something):
> > ? ? ? ? ?print("Found a %s" % something))
> > ? ? ?def write(self, s):
> > ? ? ? ? ?print(s)
> >
> > ?print("Hello, world!", file=Writable("C:\\test\\test.txt"))
> >
> > However, I'm fairly sure what you want is this:
> >
> > ? ?with open("C:\\test\\test.txt", "w") as file_object:
> > ? ? ? ?print("Hello, world!", file=file_object)
>
> Yes, went with
>
> with open("C:\\test\\test.txt", "a+") as file_object:
>       print("Hello, world!", file=file_object)
>
> > Look up "open()" (open a file) and the "with statement" (used here
> > basically as a safe way to make sure the file is closed after writing).
> >
> > Also note that "\t" refers to a TAB character in Python, you used this
> > twice in your file path string.

I believe on Windows, you can almost always use a forward slash in a path: 
C:/somewhere/somewhereelse/

-- 
I have seen the future and I am not in it.

From rdmoores at gmail.com  Sat Jul 16 01:39:32 2011
From: rdmoores at gmail.com (Richard D. Moores)
Date: Fri, 15 Jul 2011 16:39:32 -0700
Subject: [Tutor] Hello World in Python without space
In-Reply-To: <201107151621.50571.thudfoo@gmail.com>
References: <SNT120-W4225B173E1E955B729669FBC420@phx.gbl>
	<ivqchb$cs5$1@dough.gmane.org>
	<CALMxxxkFTF+_GhtCWHwFK=cX_w_bWMv3pWE+QQkKNO=44mBMuA@mail.gmail.com>
	<201107151621.50571.thudfoo@gmail.com>
Message-ID: <CALMxxxkEcwqDVj+z0wp8YOn1rjPPD9eCKR9fv8qbaWdPozLCDg@mail.gmail.com>

On Fri, Jul 15, 2011 at 16:21, xDog Walker <thudfoo at gmail.com> wrote:

> I believe on Windows, you can almost always use a forward slash in a path:
> C:/somewhere/somewhereelse/

with open("C:/test/test.txt", "a") as file_object:
     print("Hello, world!", file=file_object)

Yes, that works for me with Windows Vista. However, if test.txt is
empty, it puts in a blank line as line 1; line 2 is "Hello, world!".

Dick

From d at davea.name  Sat Jul 16 02:16:02 2011
From: d at davea.name (Dave Angel)
Date: Fri, 15 Jul 2011 20:16:02 -0400
Subject: [Tutor] Hello World in Python without space
In-Reply-To: <CALMxxxkEcwqDVj+z0wp8YOn1rjPPD9eCKR9fv8qbaWdPozLCDg@mail.gmail.com>
References: <SNT120-W4225B173E1E955B729669FBC420@phx.gbl>	<ivqchb$cs5$1@dough.gmane.org>	<CALMxxxkFTF+_GhtCWHwFK=cX_w_bWMv3pWE+QQkKNO=44mBMuA@mail.gmail.com>	<201107151621.50571.thudfoo@gmail.com>
	<CALMxxxkEcwqDVj+z0wp8YOn1rjPPD9eCKR9fv8qbaWdPozLCDg@mail.gmail.com>
Message-ID: <4E20D842.1070208@davea.name>

On 07/15/2011 07:39 PM, Richard D. Moores wrote:
> On Fri, Jul 15, 2011 at 16:21, xDog Walker<thudfoo at gmail.com>  wrote:
>
>> I believe on Windows, you can almost always use a forward slash in a path:
>> C:/somewhere/somewhereelse/
> with open("C:/test/test.txt", "a") as file_object:
>       print("Hello, world!", file=file_object)
>
> Yes, that works for me with Windows Vista. However, if test.txt is
> empty, it puts in a blank line as line 1; line 2 is "Hello, world!".
>
> Dick
> _
I expect that your extra newline was already in the "empty" file.  It 
cannot have anything to do with using the forward slash for the filename.

DaveA



-- 

DaveA


From rdmoores at gmail.com  Sat Jul 16 04:15:12 2011
From: rdmoores at gmail.com (Richard D. Moores)
Date: Fri, 15 Jul 2011 19:15:12 -0700
Subject: [Tutor] Hello World in Python without space
In-Reply-To: <4E20D842.1070208@davea.name>
References: <SNT120-W4225B173E1E955B729669FBC420@phx.gbl>
	<ivqchb$cs5$1@dough.gmane.org>
	<CALMxxxkFTF+_GhtCWHwFK=cX_w_bWMv3pWE+QQkKNO=44mBMuA@mail.gmail.com>
	<201107151621.50571.thudfoo@gmail.com>
	<CALMxxxkEcwqDVj+z0wp8YOn1rjPPD9eCKR9fv8qbaWdPozLCDg@mail.gmail.com>
	<4E20D842.1070208@davea.name>
Message-ID: <CALMxxx=ZzPoDZeV-+jTUV8Q0yhF-kOe-90XwJzyHgEhCmtJiBQ@mail.gmail.com>

On Fri, Jul 15, 2011 at 17:16, Dave Angel <d at davea.name> wrote:
> On 07/15/2011 07:39 PM, Richard D. Moores wrote:

>> with open("C:/test/test.txt", "a") as file_object:
>> ? ? ?print("Hello, world!", file=file_object)
>>
>> Yes, that works for me with Windows Vista. However, if test.txt is
>> empty, it puts in a blank line as line 1; line 2 is "Hello, world!".
>>
>> Dick
>> _
>
> I expect that your extra newline was already in the "empty" file. ?It cannot
> have anything to do with using the forward slash for the filename.

I see that you are correct. It seems that selecting all the text in a
text file (in Notepad), then hitting the delete key doesn't guarantee
that the file will be left truly blank. The way that consistently
works for me is to place the cursor in the upper left corner of the
file and hold down the delete key.

Running

with open("C:/test/test.txt", "w") as file_object:
      print(file=file_object)

Also works.

But that makes me wonder if there isn't a simpler way to do it with
Python -- to delete the contents of a file without deleting the file?

Dick

From steve at pearwood.info  Sat Jul 16 06:38:44 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 16 Jul 2011 14:38:44 +1000
Subject: [Tutor] Hello World in Python without space
In-Reply-To: <CALMxxx=ZzPoDZeV-+jTUV8Q0yhF-kOe-90XwJzyHgEhCmtJiBQ@mail.gmail.com>
References: <SNT120-W4225B173E1E955B729669FBC420@phx.gbl>	<ivqchb$cs5$1@dough.gmane.org>	<CALMxxxkFTF+_GhtCWHwFK=cX_w_bWMv3pWE+QQkKNO=44mBMuA@mail.gmail.com>	<201107151621.50571.thudfoo@gmail.com>	<CALMxxxkEcwqDVj+z0wp8YOn1rjPPD9eCKR9fv8qbaWdPozLCDg@mail.gmail.com>	<4E20D842.1070208@davea.name>
	<CALMxxx=ZzPoDZeV-+jTUV8Q0yhF-kOe-90XwJzyHgEhCmtJiBQ@mail.gmail.com>
Message-ID: <4E2115D4.3070205@pearwood.info>

Richard D. Moores wrote:

> But that makes me wonder if there isn't a simpler way to do it with
> Python -- to delete the contents of a file without deleting the file?

Opening a file for writing will flush the contents.

open(filename, 'w')

will do it, taking advantage of Python's garbage collector to 
(eventually) close the file. The more careful way is hardly any harder:

open(filename, 'w').close()

and this ensures that the file isn't left open any longer than necessary.


-- 
Steven

From steve at pearwood.info  Sat Jul 16 06:49:01 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 16 Jul 2011 14:49:01 +1000
Subject: [Tutor] Filling orders FIFO
In-Reply-To: <CAHwsmpS_hSub8WvW-WFVYGxGzHO13A+Tk2P43MzQS+wDEjt7oA@mail.gmail.com>
References: <CAHwsmpS_hSub8WvW-WFVYGxGzHO13A+Tk2P43MzQS+wDEjt7oA@mail.gmail.com>
Message-ID: <4E21183D.50900@pearwood.info>

Charles John wrote:
> Hi I am new to python and was wondering what the best way to create an
> order(bid and offer) queue, then match a bid and offer so that if
> bid==offer, creates a filled order FIFO in python cgi using mysql? Does
> anybody have any ideas? It would be greatly appreciated.

The simplest way to use a queue is with a list:

queue = []

You push items onto the queue with queue.append(item) and pop them off 
with queue.pop(0).

However, popping items may be slow if the queue grows very large (tens 
of thousands of items). It might be better to use a deque (double ended 
queue) instead of a list:

from collections import deque
queue = deque()

To push items onto the right hand side of the queue, then pop them off 
the left hand side:

queue.append(item)
queue.popleft()


As for the rest of your question, I don't understand what you mean by an 
order(bid and offer) queue. Perhaps you could give an example of what 
you mean.


-- 
Steven

From steve at pearwood.info  Sat Jul 16 06:54:38 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 16 Jul 2011 14:54:38 +1000
Subject: [Tutor] IDLE/tk in 10.6
In-Reply-To: <9887E9C5-1985-4A64-B020-9726CD6E44A0@gmail.com>
References: <9887E9C5-1985-4A64-B020-9726CD6E44A0@gmail.com>
Message-ID: <4E21198E.402@pearwood.info>

Luke Thomas Mergner wrote:
[...]
> I'd like to try IDLE but there appears to be a known bug with 10.6's version of ActiveTCL.  I've installed a newer version 8.5 via their website, but this has not fixed the problem. The module tkinter is still unable to load.  Since both python and activeTCL are installed as "Frameworks" on my mac, I wonder if I need to tell python27 that there is another Tkinter installed elsewhere.  Can anyone give me some advice?


This is not really the sort of question we can likely help you with 
here. This is for learned about Python as a programming language, not 
the ins and outs of getting it running on various operating systems.

You might get lucky and find another Mac user here who can advise you, 
but you will probably have more luck on the main Python list, 
python-list at python.com (also available on usenet, comp.lang.python) or 
on a more specialist Mac forum.


Good luck!



-- 
Steven

From rdmoores at gmail.com  Sat Jul 16 06:54:23 2011
From: rdmoores at gmail.com (Richard D. Moores)
Date: Fri, 15 Jul 2011 21:54:23 -0700
Subject: [Tutor] Hello World in Python without space
In-Reply-To: <4E2115D4.3070205@pearwood.info>
References: <SNT120-W4225B173E1E955B729669FBC420@phx.gbl>
	<ivqchb$cs5$1@dough.gmane.org>
	<CALMxxxkFTF+_GhtCWHwFK=cX_w_bWMv3pWE+QQkKNO=44mBMuA@mail.gmail.com>
	<201107151621.50571.thudfoo@gmail.com>
	<CALMxxxkEcwqDVj+z0wp8YOn1rjPPD9eCKR9fv8qbaWdPozLCDg@mail.gmail.com>
	<4E20D842.1070208@davea.name>
	<CALMxxx=ZzPoDZeV-+jTUV8Q0yhF-kOe-90XwJzyHgEhCmtJiBQ@mail.gmail.com>
	<4E2115D4.3070205@pearwood.info>
Message-ID: <CALMxxxnWXfLXAsHZY-0K04R_bS=wVyWWVu3KFHqtQ-ApNn_+7g@mail.gmail.com>

On Fri, Jul 15, 2011 at 21:38, Steven D'Aprano <steve at pearwood.info> wrote:
>
> Richard D. Moores wrote:
>
>> But that makes me wonder if there isn't a simpler way to do it with
>> Python -- to delete the contents of a file without deleting the file?
>
> Opening a file for writing will flush the contents.
>
> open(filename, 'w')
>
> will do it, taking advantage of Python's garbage collector to (eventually) close the file. The more careful way is hardly any harder:
>
> open(filename, 'w').close()
>
> and this ensures that the file isn't left open any longer than necessary.

open("C:/test/test.txt", 'w').close()

Good to know. Thanks, Steven.

Dick

From izzaddin.ruhulessin at gmail.com  Sat Jul 16 15:53:06 2011
From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin)
Date: Sat, 16 Jul 2011 15:53:06 +0200
Subject: [Tutor] Filling orders FIFO
In-Reply-To: <4E21183D.50900@pearwood.info>
References: <CAHwsmpS_hSub8WvW-WFVYGxGzHO13A+Tk2P43MzQS+wDEjt7oA@mail.gmail.com>
	<4E21183D.50900@pearwood.info>
Message-ID: <CA+sZtSmiQg2toWfS1UP3BAJFgyxm3TuWH86voH6U8gtZ=FntkQ@mail.gmail.com>

Why are you doing it at the low level? Have you consideren using a framework
like Django for example?

2011/7/16 Steven D'Aprano <steve at pearwood.info>

> Charles John wrote:
>
>> Hi I am new to python and was wondering what the best way to create an
>> order(bid and offer) queue, then match a bid and offer so that if
>> bid==offer, creates a filled order FIFO in python cgi using mysql? Does
>> anybody have any ideas? It would be greatly appreciated.
>>
>
> The simplest way to use a queue is with a list:
>
> queue = []
>
> You push items onto the queue with queue.append(item) and pop them off with
> queue.pop(0).
>
> However, popping items may be slow if the queue grows very large (tens of
> thousands of items). It might be better to use a deque (double ended queue)
> instead of a list:
>
> from collections import deque
> queue = deque()
>
> To push items onto the right hand side of the queue, then pop them off the
> left hand side:
>
> queue.append(item)
> queue.popleft()
>
>
> As for the rest of your question, I don't understand what you mean by an
> order(bid and offer) queue. Perhaps you could give an example of what you
> mean.
>
>
> --
> Steven
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110716/4a45d6e9/attachment.html>

From compbiocancerresearcher at gmail.com  Sat Jul 16 18:24:08 2011
From: compbiocancerresearcher at gmail.com (B G)
Date: Sat, 16 Jul 2011 12:24:08 -0400
Subject: [Tutor] Program to Predict Chemical Properties and Reactions
Message-ID: <CAFzgOAF8nw4bUmYvxmbuDvcKZ_THx336aR4gqU4iNd6waazn0Q@mail.gmail.com>

I was just wondering how feasible it would be to build something like the
following:

Brief background, in chemistry, the ionization energy is defined as the
energy required to remove an electron from an atom. The ionization energies
of different elements follow general trends (ie moving left to right across
the periodic table, the ionization energy increases; moving down a group the
ionization energy decreases).

What if I wanted something such that we could type in a few elements and the
program would list the elements in order of increasing ionization energy
(for, say, the first ionization energy).  Any suggestions for going about
this?  I'm trying to brush up on my chemistry and thought the funnest way to
do it would be to build a program that can do this (if it works, I'd also
like to replicate it for level of electronegativity, atomic radius size,
electron affinity, and ionization levels 2, 3, and 4). I have a good idea of
pseudocode that could make this happen in terms of the rules of chemistry,
but having some trouble visualizing the actual implementation.

Thanks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110716/13bae9e7/attachment.html>

From emile at fenx.com  Sat Jul 16 19:50:30 2011
From: emile at fenx.com (Emile van Sebille)
Date: Sat, 16 Jul 2011 10:50:30 -0700
Subject: [Tutor] Program to Predict Chemical Properties and Reactions
In-Reply-To: <CAFzgOAF8nw4bUmYvxmbuDvcKZ_THx336aR4gqU4iNd6waazn0Q@mail.gmail.com>
References: <CAFzgOAF8nw4bUmYvxmbuDvcKZ_THx336aR4gqU4iNd6waazn0Q@mail.gmail.com>
Message-ID: <ivsitj$gd5$1@dough.gmane.org>

On 7/16/2011 9:24 AM B G said...
> I was just wondering how feasible it would be to build something like
> the following:
>
> Brief background, in chemistry, the ionization energy is defined as the
> energy required to remove an electron from an atom. The ionization
> energies of different elements follow general trends (ie moving left to
> right across the periodic table, the ionization energy increases; moving
> down a group the ionization energy decreases).
>
> What if I wanted something such that we could type in a few elements and
> the program would list the elements in order of increasing ionization
> energy (for, say, the first ionization energy).  Any suggestions for
> going about this?

Build a dictionary of elements and ionization energies.  Then it's 
simply a matter of looking up the entered elements related values, 
sorting, and displaying.

> I'm trying to brush up on my chemistry and thought
> the funnest way to do it would be to build a program that can do this
> (if it works, I'd also like to replicate it for level of
> electronegativity, atomic radius size, electron affinity, and ionization
> levels 2, 3, and 4).

Extend the dictionary for the additional attributes.

Emile


> I have a good idea of pseudocode that could make
> this happen in terms of the rules of chemistry, but having some trouble
> visualizing the actual implementation.
>
> Thanks!
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



From fomcl at yahoo.com  Sat Jul 16 20:23:47 2011
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Sat, 16 Jul 2011 11:23:47 -0700 (PDT)
Subject: [Tutor] what is 'doubleword alignment'?
Message-ID: <1310840627.78806.YahooMailClassic@web110713.mail.gq1.yahoo.com>

Hello,

What is 'doubleword alignment'? It is used in the following sentence: "Fill up the buffer with the correctly encoded numeric and string values, taking care of blank padding and doubleword alignment." 

I know that the buffer is comprised of variables of 8-bytes, or multiples thereof, each. Numeric variables are 8 bytes, char vars are at least 8 bytes. For example, a 10-byte value is 'ceiled' to 18 bytes. This is done with padding (spaces, I think). But the aligment part...?

TIA

Cheers!!

Albert-Jan



~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110716/d55dcd3a/attachment.html>

From fomcl at yahoo.com  Sat Jul 16 22:53:55 2011
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Sat, 16 Jul 2011 13:53:55 -0700 (PDT)
Subject: [Tutor] what is 'doubleword alignment'?
In-Reply-To: <1310840627.78806.YahooMailClassic@web110713.mail.gq1.yahoo.com>
Message-ID: <1310849635.98543.YahooMailClassic@web110706.mail.gq1.yahoo.com>

Got it already, I think. The word boundary of one chunk of information (in my case 8 bytes) is aligned in the computer's memory such that the boundary's address is a power of two.

But correct me if I'm wrong ;-)

Cheers!!

Albert-Jan



~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

--- On Sat, 7/16/11, Albert-Jan Roskam <fomcl at yahoo.com> wrote:

From: Albert-Jan Roskam <fomcl at yahoo.com>
Subject: [Tutor] what is 'doubleword alignment'?
To: "Python Mailing List" <tutor at python.org>
Date: Saturday, July 16, 2011, 8:23 PM

Hello,

What is 'doubleword alignment'? It is used in the following sentence: "Fill up the buffer with the correctly encoded numeric and string values, taking care of blank padding and doubleword alignment." 

I know that the buffer is comprised of variables of 8-bytes, or multiples thereof, each. Numeric variables are 8 bytes, char vars are at least 8 bytes. For example, a 10-byte value is 'ceiled' to 18 bytes. This is done with padding (spaces, I think). But the aligment part...?

TIA

Cheers!!

Albert-Jan



~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-----Inline Attachment Follows-----

_______________________________________________
Tutor maillist? -? Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110716/87e74ee6/attachment-0001.html>

From compbiocancerresearcher at gmail.com  Sat Jul 16 23:32:17 2011
From: compbiocancerresearcher at gmail.com (B G)
Date: Sat, 16 Jul 2011 17:32:17 -0400
Subject: [Tutor] Program to Predict Chemical Properties and Reactions
Message-ID: <CAFzgOAHe9F7tZP1n749G1r=nsQ4SJ6oocmfUyCPGv+0ifpq3zQ@mail.gmail.com>

Thanks, Emile-- although I'm not sure I was completely clear about my
objective. What I really meant is that is there a way (via machine learning)
to give the computer a list of rules and exceptions, and then have it
predict based on these rules the ionization energy. Ultimately I'm pretty
interested in the idea of building a program that could predict the expected
result of a chemical reaction, but that's a huge project, so I wanted to
start with something much, much, much smaller and easier.

So I don't really want to manually input ionization energy, atomic radius
size, etc, since I'm not sure how much that would help towards the bigger
goal.  For this project, I already have the ~15 rules that describe trends
on the periodic table.  I want to write a program that, based on these rules
(and the few exceptions to them), could predict the inputs that I want.
 Does this make sense?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110716/c114e718/attachment.html>

From alan.gauld at btinternet.com  Fri Jul 15 23:32:07 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 15 Jul 2011 22:32:07 +0100
Subject: [Tutor] what is 'doubleword alignment'?
In-Reply-To: <1310849635.98543.YahooMailClassic@web110706.mail.gq1.yahoo.com>
References: <1310840627.78806.YahooMailClassic@web110713.mail.gq1.yahoo.com>
	<1310849635.98543.YahooMailClassic@web110706.mail.gq1.yahoo.com>
Message-ID: <4E20B1D7.9000403@btinternet.com>

Albert-Jan Roskam wrote:
> Got it already, I think. The word boundary of one chunk of information 
 > in my case 8 bytes) is aligned in the computer's memory
 > such that the boundary's address is a power of two.

Yes, you are right. It means that the storage of your data should always 
be aligned with addressable locations on your computer. The computers 
addressing scheme may not be linear and may not correspond to the "word" 
size in the programming environment. (eg The old Intel 8086 CPU used a 
segment:offset addressing scheme that meant any given memory location 
could be addressed in multiple ways. This was great for clever 
multi-tasking schemes but murder for normal computing because variable 
addresses could easily get messed up and accidentally overwrite other 
bits of data. Other CPUs have other schemes and running 32bit programs 
on 64bit hardware is another example where the two don't match!)


Ensuring that the programming view of memory and the hardware view 
matches up is A Very Good Thing(TM)...

HTH,

Alan G.


From alan.gauld at btinternet.com  Fri Jul 15 23:32:07 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 15 Jul 2011 22:32:07 +0100
Subject: [Tutor] what is 'doubleword alignment'?
In-Reply-To: <1310849635.98543.YahooMailClassic@web110706.mail.gq1.yahoo.com>
References: <1310840627.78806.YahooMailClassic@web110713.mail.gq1.yahoo.com>
	<1310849635.98543.YahooMailClassic@web110706.mail.gq1.yahoo.com>
Message-ID: <4E20B1D7.9000403@btinternet.com>

Albert-Jan Roskam wrote:
> Got it already, I think. The word boundary of one chunk of information 
 > in my case 8 bytes) is aligned in the computer's memory
 > such that the boundary's address is a power of two.

Yes, you are right. It means that the storage of your data should always 
be aligned with addressable locations on your computer. The computers 
addressing scheme may not be linear and may not correspond to the "word" 
size in the programming environment. (eg The old Intel 8086 CPU used a 
segment:offset addressing scheme that meant any given memory location 
could be addressed in multiple ways. This was great for clever 
multi-tasking schemes but murder for normal computing because variable 
addresses could easily get messed up and accidentally overwrite other 
bits of data. Other CPUs have other schemes and running 32bit programs 
on 64bit hardware is another example where the two don't match!)


Ensuring that the programming view of memory and the hardware view 
matches up is A Very Good Thing(TM)...

HTH,

Alan G.

From d at davea.name  Sun Jul 17 00:02:30 2011
From: d at davea.name (Dave Angel)
Date: Sat, 16 Jul 2011 18:02:30 -0400
Subject: [Tutor] what is 'doubleword alignment'?
In-Reply-To: <1310849635.98543.YahooMailClassic@web110706.mail.gq1.yahoo.com>
References: <1310849635.98543.YahooMailClassic@web110706.mail.gq1.yahoo.com>
Message-ID: <4E220A76.4050202@davea.name>


> --- On Sat, 7/16/11, Albert-Jan Roskam<fomcl at yahoo.com>  wrote:
>
> From: Albert-Jan Roskam<fomcl at yahoo.com>
> Subject: [Tutor] what is 'doubleword alignment'?
> To: "Python Mailing List"<tutor at python.org>
> Date: Saturday, July 16, 2011, 8:23 PM
>
> Hello,
>
> What is 'doubleword alignment'? It is used in the following sentence: "Fill up the buffer with the correctly encoded numeric and string values, taking care of blank padding and doubleword alignment."
>
> I know that the buffer is comprised of variables of 8-bytes, or multiples thereof, each. Numeric variables are 8 bytes, char vars are at least 8 bytes. For example, a 10-byte value is 'ceiled' to 18 bytes. This is done with padding (spaces, I think). But the aligment part...?
>
> TIA
>
> Cheers!!
>
> Albert-Jan
>
On 07/16/2011 04:53 PM, Albert-Jan Roskam wrote:
> Got it already, I think. The word boundary of one chunk of information (in my case 8 bytes) is aligned in the computer's memory such that the boundary's address is a power of two.
>
> But correct me if I'm wrong ;-)
>
> Cheers!!
>
> Albert-Jan
>
>
>

(please put your new text AFTER the text you're quoting.  I moved it in 
this case, but couldn't also get the indentation right)

Not quite.  Doubleword alignment is alignment on an 8byte boundary.  The 
address of such a boundary will be a multiple of 8, not a power of two.

So in your earlier example, the 10 byte string will be padded to 16, not 
18 bytes.  If the buffer starts aligned, then each such element will 
also be aligned.


-- 

DaveA


From d at davea.name  Sun Jul 17 00:06:23 2011
From: d at davea.name (Dave Angel)
Date: Sat, 16 Jul 2011 18:06:23 -0400
Subject: [Tutor] Program to Predict Chemical Properties and Reactions
In-Reply-To: <CAFzgOAHe9F7tZP1n749G1r=nsQ4SJ6oocmfUyCPGv+0ifpq3zQ@mail.gmail.com>
References: <CAFzgOAHe9F7tZP1n749G1r=nsQ4SJ6oocmfUyCPGv+0ifpq3zQ@mail.gmail.com>
Message-ID: <4E220B5F.2060008@davea.name>

On 07/16/2011 05:32 PM, B G wrote:
> Thanks, Emile-- although I'm not sure I was completely clear about my
> objective. What I really meant is that is there a way (via machine learning)
> to give the computer a list of rules and exceptions, and then have it
> predict based on these rules the ionization energy. Ultimately I'm pretty
> interested in the idea of building a program that could predict the expected
> result of a chemical reaction, but that's a huge project, so I wanted to
> start with something much, much, much smaller and easier.
>
> So I don't really want to manually input ionization energy, atomic radius
> size, etc, since I'm not sure how much that would help towards the bigger
> goal.  For this project, I already have the ~15 rules that describe trends
> on the periodic table.  I want to write a program that, based on these rules
> (and the few exceptions to them), could predict the inputs that I want.
>   Does this make sense?
>
>
Neither ordering nor trends will give values for individual items.  So 
unless these rules are much more numerical than the clues you've 
mentioned so far, the problem is clearly impossible.

But I suspect the problem is possible, and that you have much more 
information than you intend to tell us.

-- 

DaveA


From alan.gauld at btinternet.com  Sat Jul 16 00:32:07 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 15 Jul 2011 23:32:07 +0100
Subject: [Tutor] what is 'doubleword alignment'?
In-Reply-To: <4E220A76.4050202@davea.name>
References: <1310849635.98543.YahooMailClassic@web110706.mail.gq1.yahoo.com>
	<4E220A76.4050202@davea.name>
Message-ID: <4E20BFE7.1010709@btinternet.com>

Dave Angel wrote:
>> --- On Sat, 7/16/11, Albert-Jan Roskam<fomcl at yahoo.com>  wrote:

>> (in my case 8 bytes) is aligned in the computer's memory such that the 
>> boundary's address is a power of two.
> Not quite.  Doubleword alignment is alignment on an 8byte boundary.  The 
> address of such a boundary will be a multiple of 8, not a power of two.

Oops, when I said Albert was "right" I meant in terms of aligning with 
computer memory, I didn't register the "power of two" bit, which is, as 
you say, not correct. Apologies for any confusion caused!


Alan G.

From alan.gauld at btinternet.com  Sat Jul 16 00:32:07 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 15 Jul 2011 23:32:07 +0100
Subject: [Tutor] what is 'doubleword alignment'?
In-Reply-To: <4E220A76.4050202@davea.name>
References: <1310849635.98543.YahooMailClassic@web110706.mail.gq1.yahoo.com>
	<4E220A76.4050202@davea.name>
Message-ID: <4E20BFE7.1010709@btinternet.com>

Dave Angel wrote:
>> --- On Sat, 7/16/11, Albert-Jan Roskam<fomcl at yahoo.com>  wrote:

>> (in my case 8 bytes) is aligned in the computer's memory such that the 
>> boundary's address is a power of two.
> Not quite.  Doubleword alignment is alignment on an 8byte boundary.  The 
> address of such a boundary will be a multiple of 8, not a power of two.

Oops, when I said Albert was "right" I meant in terms of aligning with 
computer memory, I didn't register the "power of two" bit, which is, as 
you say, not correct. Apologies for any confusion caused!


Alan G.


From g.nius.ck at gmail.com  Sun Jul 17 01:21:33 2011
From: g.nius.ck at gmail.com (Christopher King)
Date: Sat, 16 Jul 2011 19:21:33 -0400
Subject: [Tutor] Program to Predict Chemical Properties and Reactions
In-Reply-To: <4E220B5F.2060008@davea.name>
References: <CAFzgOAHe9F7tZP1n749G1r=nsQ4SJ6oocmfUyCPGv+0ifpq3zQ@mail.gmail.com>
	<4E220B5F.2060008@davea.name>
Message-ID: <CAKBg9Z1=cBCuK0AXWSNrAjYAeGdb+To38fOU_+sFMWMVPzDqbg@mail.gmail.com>

Actually maybe not, depending on the complexity of the pattern, but it would
be difficult. You would have to know how much it decreases for every time
you go down or to the right.
If its more complex than that, you may have to program each rule in, not
just enter them in a prompt. I'm assuming none of the rules conflict,
because that would be a problem too.

On Sat, Jul 16, 2011 at 6:06 PM, Dave Angel <d at davea.name> wrote:

> On 07/16/2011 05:32 PM, B G wrote:
>
>> Thanks, Emile-- although I'm not sure I was completely clear about my
>> objective. What I really meant is that is there a way (via machine
>> learning)
>> to give the computer a list of rules and exceptions, and then have it
>> predict based on these rules the ionization energy. Ultimately I'm pretty
>> interested in the idea of building a program that could predict the
>> expected
>> result of a chemical reaction, but that's a huge project, so I wanted to
>> start with something much, much, much smaller and easier.
>>
>> So I don't really want to manually input ionization energy, atomic radius
>> size, etc, since I'm not sure how much that would help towards the bigger
>> goal.  For this project, I already have the ~15 rules that describe trends
>> on the periodic table.  I want to write a program that, based on these
>> rules
>> (and the few exceptions to them), could predict the inputs that I want.
>>  Does this make sense?
>>
>>
>>  Neither ordering nor trends will give values for individual items.  So
> unless these rules are much more numerical than the clues you've mentioned
> so far, the problem is clearly impossible.
>
> But I suspect the problem is possible, and that you have much more
> information than you intend to tell us.
>
> --
>
> DaveA
>
>
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110716/085297b6/attachment.html>

From d at davea.name  Sun Jul 17 03:41:45 2011
From: d at davea.name (Dave Angel)
Date: Sat, 16 Jul 2011 21:41:45 -0400
Subject: [Tutor] Program to Predict Chemical Properties and Reactions
In-Reply-To: <CAKBg9Z1=cBCuK0AXWSNrAjYAeGdb+To38fOU_+sFMWMVPzDqbg@mail.gmail.com>
References: <CAFzgOAHe9F7tZP1n749G1r=nsQ4SJ6oocmfUyCPGv+0ifpq3zQ@mail.gmail.com>	<4E220B5F.2060008@davea.name>
	<CAKBg9Z1=cBCuK0AXWSNrAjYAeGdb+To38fOU_+sFMWMVPzDqbg@mail.gmail.com>
Message-ID: <4E223DD9.20706@davea.name>

On 07/16/2011 07:21 PM, Christopher King wrote:
> Actually maybe not, depending on the complexity of the pattern, but it would
> be difficult. You would have to know how much it decreases for every time
> you go down or to the right.
> If its more complex than that, you may have to program each rule in, not
> just enter them in a prompt. I'm assuming none of the rules conflict,
> because that would be a problem too.
>
(Your response should always be after the part you're quoting.  There 
are far too many people lately breaking the tradition of these forums)

I certainly wouldn't be entering in "rules" at a prompt.  And I 
seriously doubt if the formulas are as simple as "how much it decreases 
for every time."

Anyway, this is a much different problem than the original post.


-- 

DaveA

From kasturisurya at gmail.com  Sun Jul 17 07:52:11 2011
From: kasturisurya at gmail.com (Surya P.K. Kasturi)
Date: Sun, 17 Jul 2011 11:22:11 +0530
Subject: [Tutor] how to add directory to python search list
Message-ID: <CAArdDCr=WzR=yMBbVry_BRPke=judFO-7jUn4mUkXMA33ntXMg@mail.gmail.com>

OS : Ubuntu Linux
Python Version : 2.6.4

I have some third party modules to be installed in my computer.
So, I want to add the module directory to python search list.

I used :

*>>> import sys*
*>>> sys.path.append('directory address')*
*
*
this could do my work but as soon as I close the terminal and reopen it, I
am not able to find the new directory I have just added.
I used the following code to check.

*>>> sys.path*
*
*
*how do I fix this problem ? *
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110717/8f3f7c1d/attachment.html>

From alan.gauld at btinternet.com  Sat Jul 16 08:18:27 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 16 Jul 2011 07:18:27 +0100
Subject: [Tutor] how to add directory to python search list
In-Reply-To: <CAArdDCr=WzR=yMBbVry_BRPke=judFO-7jUn4mUkXMA33ntXMg@mail.gmail.com>
References: <CAArdDCr=WzR=yMBbVry_BRPke=judFO-7jUn4mUkXMA33ntXMg@mail.gmail.com>
Message-ID: <4E212D33.1040209@btinternet.com>

Surya P.K. Kasturi wrote:
> OS : Ubuntu Linux
> Python Version : 2.6.4
> 
> I have some third party modules to be installed in my computer.
> So, I want to add the module directory to python search list.
> 
> I used :
> 
> *>>> import sys*
> *>>> sys.path.append('directory address')*
> *
> *
> this could do my work but as soon as I close the terminal and reopen it, I

You need to add the folder to your PYTHONPATH environment variable.
You usually do this your .login or .profile file.

Python will add the contents of PYTHONPATH to sys.path on startup.

HTH,


Alan G

From alan.gauld at btinternet.com  Sat Jul 16 08:18:27 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 16 Jul 2011 07:18:27 +0100
Subject: [Tutor] how to add directory to python search list
In-Reply-To: <CAArdDCr=WzR=yMBbVry_BRPke=judFO-7jUn4mUkXMA33ntXMg@mail.gmail.com>
References: <CAArdDCr=WzR=yMBbVry_BRPke=judFO-7jUn4mUkXMA33ntXMg@mail.gmail.com>
Message-ID: <4E212D33.1040209@btinternet.com>

Surya P.K. Kasturi wrote:
> OS : Ubuntu Linux
> Python Version : 2.6.4
> 
> I have some third party modules to be installed in my computer.
> So, I want to add the module directory to python search list.
> 
> I used :
> 
> *>>> import sys*
> *>>> sys.path.append('directory address')*
> *
> *
> this could do my work but as soon as I close the terminal and reopen it, I

You need to add the folder to your PYTHONPATH environment variable.
You usually do this your .login or .profile file.

Python will add the contents of PYTHONPATH to sys.path on startup.

HTH,


Alan G


From kasturisurya at gmail.com  Sun Jul 17 08:45:08 2011
From: kasturisurya at gmail.com (Surya P.K. Kasturi)
Date: Sun, 17 Jul 2011 12:15:08 +0530
Subject: [Tutor] how to add directory to python search list
In-Reply-To: <4E212D33.1040209@btinternet.com>
References: <CAArdDCr=WzR=yMBbVry_BRPke=judFO-7jUn4mUkXMA33ntXMg@mail.gmail.com>
	<4E212D33.1040209@btinternet.com>
Message-ID: <CAArdDCqav4D=bra59d0a27vWy2KsrN-GfSS71UJ6E4KQN6Gm=A@mail.gmail.com>

Mr. Gauld

can you tell me in detail how to do this.
I am new to linux.

On Sat, Jul 16, 2011 at 11:48 AM, Alan Gauld <alan.gauld at btinternet.com>wrote:

> Surya P.K. Kasturi wrote:
>
>> OS : Ubuntu Linux
>> Python Version : 2.6.4
>>
>> I have some third party modules to be installed in my computer.
>> So, I want to add the module directory to python search list.
>>
>> I used :
>>
>> *>>> import sys*
>> *>>> sys.path.append('directory address')*
>> *
>> *
>> this could do my work but as soon as I close the terminal and reopen it, I
>>
>
> You need to add the folder to your PYTHONPATH environment variable.
> You usually do this your .login or .profile file.
>
> Python will add the contents of PYTHONPATH to sys.path on startup.
>
> HTH,
>
>
> Alan G
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110717/9abb7a5a/attachment-0001.html>

From kasturisurya at gmail.com  Sun Jul 17 09:42:53 2011
From: kasturisurya at gmail.com (Surya P.K. Kasturi)
Date: Sun, 17 Jul 2011 13:12:53 +0530
Subject: [Tutor] error in using TurtleWorld modules, ThinkPython.org Book
Message-ID: <CAArdDCpkSEErHQiyboLM_vHJhDYu4pC7QLg3ZfZfowyZio6hqA@mail.gmail.com>

I am using Think Python book, <www.ThinkPython.org> to learn python.
There is a module TurtleWorld that they described to draw lines <
http://www.greenteapress.com/thinkpython/swampy/install.html>

Though I could run the below code in the python shell, I couldn't do it
through a script file.


This is the script :

from TurtleWorld import *

world = TurtleWorld
bob = Turtle()
print bob

fd(bob, 100)
lt(bob)
fd(bob, 100)
lt(bob)
fd(bob, 100)
lt(bob)
fd(bob, 100)

wait_for_user()

*This is the following error I got at terminal :*

<TurtleWorld.Turtle object at 0xb770a50c>
Traceback (most recent call last):
  File "turtle.py", line 7, in <module>
    fd(bob, 100)
  File "/usr/local/lib/python2.6/dist-packages/TurtleWorld.py", line 187, in
fd
    self.world.canvas.line([p1, p2], fill=self.pen_color)
AttributeError: 'NoneType' object has no attribute 'canvas'

*Could you help me to fix this error, please!*
*
*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110717/91e27b4b/attachment.html>

From __peter__ at web.de  Sun Jul 17 09:47:07 2011
From: __peter__ at web.de (Peter Otten)
Date: Sun, 17 Jul 2011 09:47:07 +0200
Subject: [Tutor] how to add directory to python search list
References: <CAArdDCr=WzR=yMBbVry_BRPke=judFO-7jUn4mUkXMA33ntXMg@mail.gmail.com>
Message-ID: <ivu41j$is0$1@dough.gmane.org>

Surya P.K. Kasturi wrote:

> OS : Ubuntu Linux
> Python Version : 2.6.4
> 
> I have some third party modules to be installed in my computer.
> So, I want to add the module directory to python search list.

The way I find most convenient is to create a text file with the .pth suffix
in a directory that is already seen by Python. I use the file

~/.local/lib/python2.6/site-packages/lib.pth

That file contains paths to the directories you want Python to see, one path 
per line.





From __peter__ at web.de  Sun Jul 17 11:26:30 2011
From: __peter__ at web.de (Peter Otten)
Date: Sun, 17 Jul 2011 11:26:30 +0200
Subject: [Tutor] error in using TurtleWorld modules, ThinkPython.org Book
References: <CAArdDCpkSEErHQiyboLM_vHJhDYu4pC7QLg3ZfZfowyZio6hqA@mail.gmail.com>
Message-ID: <ivu9rt$d0s$1@dough.gmane.org>

Surya P.K. Kasturi wrote:

> I am using Think Python book, <www.ThinkPython.org> to learn python.
> There is a module TurtleWorld that they described to draw lines <
> http://www.greenteapress.com/thinkpython/swampy/install.html>
> 
> Though I could run the below code in the python shell, I couldn't do it
> through a script file.
> 
> 
> This is the script :
> 
> from TurtleWorld import *
> 
> world = TurtleWorld

You forgot the parens in

world = TurtleWorld()

and therefore your turtle Bob

> bob = Turtle()
> fd(bob, 100)

has no world to live and move in.



From steve at pearwood.info  Sun Jul 17 13:11:33 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 17 Jul 2011 21:11:33 +1000
Subject: [Tutor] how to add directory to python search list
In-Reply-To: <CAArdDCqav4D=bra59d0a27vWy2KsrN-GfSS71UJ6E4KQN6Gm=A@mail.gmail.com>
References: <CAArdDCr=WzR=yMBbVry_BRPke=judFO-7jUn4mUkXMA33ntXMg@mail.gmail.com>	<4E212D33.1040209@btinternet.com>
	<CAArdDCqav4D=bra59d0a27vWy2KsrN-GfSS71UJ6E4KQN6Gm=A@mail.gmail.com>
Message-ID: <4E22C365.8090708@pearwood.info>

Surya P.K. Kasturi wrote:

> can you tell me in detail how to do this.
> I am new to linux.

"this" being:

> On Sat, Jul 16, 2011 at 11:48 AM, Alan Gauld <alan.gauld at btinternet.com>wrote:
>> You need to add the folder to your PYTHONPATH environment variable.
>> You usually do this your .login or .profile file.
>>
>> Python will add the contents of PYTHONPATH to sys.path on startup.

(Surya, on this list we prefer if people don't top-post.)

What Alan means is for you to edit your login file so that it creates an 
environment variable. How you do that depends on which shell you are 
using. If you don't know which shell, try this:

(1) Open a fresh terminal window.
(2) Type "echo $SHELL" (without the quotation marks) and press Enter.

This will print something like this:


[steve at sylar ~]$ echo $SHELL
/bin/bash


So I am running "bash" as my shell. So I have the following line in my 
bash login file, .bashrc:


export PYTHONPATH=/home/steve/python/


That creates an environment variable, PYTHONPATH, which Python will 
automatically add to sys.path.

(Other shells will do this differently.)


Another alternative: I also have set a startup file:


export PYTHONSTARTUP=/home/steve/python/startup.py


I can put any Python code I like in startup.py and it will be run just 
before the interactive interpreter.

Or you can follow Peter's advice and use a .pth file.



-- 
Steven


From lisi.reisz at gmail.com  Sun Jul 17 16:13:37 2011
From: lisi.reisz at gmail.com (Lisi)
Date: Sun, 17 Jul 2011 15:13:37 +0100
Subject: [Tutor] Hello World in Python without space
In-Reply-To: <CALMxxx=ZzPoDZeV-+jTUV8Q0yhF-kOe-90XwJzyHgEhCmtJiBQ@mail.gmail.com>
References: <SNT120-W4225B173E1E955B729669FBC420@phx.gbl>
	<4E20D842.1070208@davea.name>
	<CALMxxx=ZzPoDZeV-+jTUV8Q0yhF-kOe-90XwJzyHgEhCmtJiBQ@mail.gmail.com>
Message-ID: <201107171513.37749.lisi.reisz@gmail.com>

On Saturday 16 July 2011 03:15:12 Richard D. Moores wrote:
> But that makes me wonder if there isn't a simpler way to do it with
> Python -- to delete the contents of a file without deleting the file?

Up to now, knowing no better ;-), I have opened the file in, or copied and 
pasted the contents of a file into, a word processor and turned on the 
non-printing characters.  It is then easy to see extraneous spaces, empty 
lines etc.  I then go back to the editor and do the revealed editing.

Rough, ready and cobbled - but easy, and it works. ;-)

If you use Windows and have no idea what I am talking about, I apologise.  It 
is so long since I used Windows that I have forgotten much of what it can and 
cannot do; and I don't know whether it can do this.

Lisi

From kasturisurya at gmail.com  Sun Jul 17 16:28:38 2011
From: kasturisurya at gmail.com (Surya P.K. Kasturi)
Date: Sun, 17 Jul 2011 19:58:38 +0530
Subject: [Tutor] error in using TurtleWorld modules, ThinkPython.org Book
In-Reply-To: <ivu9rt$d0s$1@dough.gmane.org>
References: <CAArdDCpkSEErHQiyboLM_vHJhDYu4pC7QLg3ZfZfowyZio6hqA@mail.gmail.com>
	<ivu9rt$d0s$1@dough.gmane.org>
Message-ID: <CAArdDCq77d_uqJY=rgCctPSDQD8Sc4YXygp2jsDpx=Ttn8Hs7Q@mail.gmail.com>

Thanks, .. that was a silly mistake.


On Sun, Jul 17, 2011 at 2:56 PM, Peter Otten <__peter__ at web.de> wrote:

> Surya P.K. Kasturi wrote:
>
> > I am using Think Python book, <www.ThinkPython.org> to learn python.
> > There is a module TurtleWorld that they described to draw lines <
> > http://www.greenteapress.com/thinkpython/swampy/install.html>
> >
> > Though I could run the below code in the python shell, I couldn't do it
> > through a script file.
> >
> >
> > This is the script :
> >
> > from TurtleWorld import *
> >
> > world = TurtleWorld
>
> You forgot the parens in
>
> world = TurtleWorld()
>
> and therefore your turtle Bob
>
> > bob = Turtle()
> > fd(bob, 100)
>
> has no world to live and move in.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110717/0776ddba/attachment.html>

From kasturisurya at gmail.com  Sun Jul 17 16:38:26 2011
From: kasturisurya at gmail.com (Surya P.K. Kasturi)
Date: Sun, 17 Jul 2011 20:08:26 +0530
Subject: [Tutor] how to add directory to python search list
In-Reply-To: <4E22C365.8090708@pearwood.info>
References: <CAArdDCr=WzR=yMBbVry_BRPke=judFO-7jUn4mUkXMA33ntXMg@mail.gmail.com>
	<4E212D33.1040209@btinternet.com>
	<CAArdDCqav4D=bra59d0a27vWy2KsrN-GfSS71UJ6E4KQN6Gm=A@mail.gmail.com>
	<4E22C365.8090708@pearwood.info>
Message-ID: <CAArdDCrp9iuFnFNS_C4Sfx4uYsqNoAYE6Po6WizsLvNurKZbGg@mail.gmail.com>

Thanks a lot. your posts are really helpful.

On Sun, Jul 17, 2011 at 4:41 PM, Steven D'Aprano <steve at pearwood.info>wrote:

> Surya P.K. Kasturi wrote:
>
>  can you tell me in detail how to do this.
>> I am new to linux.
>>
>
> "this" being:
>
>  On Sat, Jul 16, 2011 at 11:48 AM, Alan Gauld <alan.gauld at btinternet.com>*
>> *wrote:
>>
>>> You need to add the folder to your PYTHONPATH environment variable.
>>>
>>> You usually do this your .login or .profile file.
>>>
>>> Python will add the contents of PYTHONPATH to sys.path on startup.
>>>
>>
> (Surya, on this list we prefer if people don't top-post.)
>
> What Alan means is for you to edit your login file so that it creates an
> environment variable. How you do that depends on which shell you are using.
> If you don't know which shell, try this:
>
> (1) Open a fresh terminal window.
> (2) Type "echo $SHELL" (without the quotation marks) and press Enter.
>
> This will print something like this:
>
>
> [steve at sylar ~]$ echo $SHELL
> /bin/bash
>
>
> So I am running "bash" as my shell. So I have the following line in my bash
> login file, .bashrc:
>
>
> export PYTHONPATH=/home/steve/python/
>
>
> That creates an environment variable, PYTHONPATH, which Python will
> automatically add to sys.path.
>
> (Other shells will do this differently.)
>
>
> Another alternative: I also have set a startup file:
>
>
> export PYTHONSTARTUP=/home/steve/**python/startup.py
>
>
> I can put any Python code I like in startup.py and it will be run just
> before the interactive interpreter.
>
> Or you can follow Peter's advice and use a .pth file.
>
>
>
> --
> Steven
>
>
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110717/331f89da/attachment.html>

From lisi.reisz at gmail.com  Sun Jul 17 16:26:33 2011
From: lisi.reisz at gmail.com (Lisi)
Date: Sun, 17 Jul 2011 15:26:33 +0100
Subject: [Tutor] what is 'doubleword alignment'?
In-Reply-To: <1310849635.98543.YahooMailClassic@web110706.mail.gq1.yahoo.com>
References: <1310849635.98543.YahooMailClassic@web110706.mail.gq1.yahoo.com>
Message-ID: <201107171526.33581.lisi.reisz@gmail.com>

On Saturday 16 July 2011 21:53:55 Albert-Jan Roskam wrote:
> I know that the buffer is comprised of variables of 8-bytes, or multiples
> thereof, each. Numeric variables are 8 bytes, char vars are at least 8
> bytes. For example, a 10-byte value is 'ceiled' to 18 bytes. This is done
> with padding (spaces, I think). But the aligment part...?
then wrote:
> Got it already, I think. The word boundary of one chunk of information (in
> my case 8 bytes) is aligned in the computer's memory such that the
> boundary's address is a power of two.

Sorry to be slow.  Blame virtually no sleep last night ;-(  But even were the 
power of two bit correct (and I see subsequently that it is not), how is 18 a 
power of two?

Lisi

From wprins at gmail.com  Sun Jul 17 17:45:52 2011
From: wprins at gmail.com (Walter Prins)
Date: Sun, 17 Jul 2011 16:45:52 +0100
Subject: [Tutor] what is 'doubleword alignment'?
In-Reply-To: <201107171526.33581.lisi.reisz@gmail.com>
References: <1310849635.98543.YahooMailClassic@web110706.mail.gq1.yahoo.com>
	<201107171526.33581.lisi.reisz@gmail.com>
Message-ID: <CANLXbfAidSnTv_w=dq0YHE+gij_HCtfc3u65xOnsEZmXuX_iAw@mail.gmail.com>

On 17 July 2011 15:26, Lisi <lisi.reisz at gmail.com> wrote:

> Sorry to be slow.  Blame virtually no sleep last night ;-(  But even were
> the
> power of two bit correct (and I see subsequently that it is not), how is 18
> a
> power of two?
>
>
The 18 bytes is a bit of an irrelevance.  The point is that if the start of
the buffer falls on a dword (double word) alligned memory location then in
theory the access should be faster.  The term is a little bit ambiguous
because strictly speaking different processors have different word sizes.
Even so, usually when people speak of double-word alignment, it's often the
case that the term word in such a context has its original meaning, e.g. 16
bits.  A dword is then 32bits or 4 bytes.   A doubleword aligned memory
address is, using these assumptions, therefore an address that is divisible
by 4.  Obviously if the word size is 32bits, then a double word would be
64bits and a doubleword aligned address would need to be divisible by 8.  As
an aside, this type of optimization is often taken care of by compilers
under the hood, and in any case it's generally not something that you'll
really be considering as a Python programmer.  (If however you were working
on one of the Python runtimes or implementations, then you might well be
sometimes considering this type of thing, depending on exactly how
performance critical what you are working might be and what the runtime was
being implemented in.)

Regards

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110717/6a51a81c/attachment-0001.html>

From steve at pearwood.info  Sun Jul 17 18:52:13 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 18 Jul 2011 02:52:13 +1000
Subject: [Tutor] Filling orders FIFO
In-Reply-To: <CA+sZtSmiQg2toWfS1UP3BAJFgyxm3TuWH86voH6U8gtZ=FntkQ@mail.gmail.com>
References: <CAHwsmpS_hSub8WvW-WFVYGxGzHO13A+Tk2P43MzQS+wDEjt7oA@mail.gmail.com>	<4E21183D.50900@pearwood.info>
	<CA+sZtSmiQg2toWfS1UP3BAJFgyxm3TuWH86voH6U8gtZ=FntkQ@mail.gmail.com>
Message-ID: <4E23133D.6030106@pearwood.info>

Izz ad-Din Ruhulessin wrote:
> Why are you doing it at the low level? Have you consideren using a framework
> like Django for example?

Who is this question addressed to? Me?

If so, my answer is that Django is an awfully large dependency if all 
you need is a queue.

But if you think that Django has a good solution to the problem, by all 
means show us how you would use it.


P.S. we prefer that you don't top-post on this mailing list. It makes it 
easier to understand replies if they follow what they are replying to, 
rather than come before.

Steven.



> 2011/7/16 Steven D'Aprano <steve at pearwood.info>
> 
>> Charles John wrote:
>>
>>> Hi I am new to python and was wondering what the best way to create an
>>> order(bid and offer) queue, then match a bid and offer so that if
>>> bid==offer, creates a filled order FIFO in python cgi using mysql? Does
>>> anybody have any ideas? It would be greatly appreciated.
>>>
>> The simplest way to use a queue is with a list:
>>
>> queue = []
>>
>> You push items onto the queue with queue.append(item) and pop them off with
>> queue.pop(0).
>>
>> However, popping items may be slow if the queue grows very large (tens of
>> thousands of items). It might be better to use a deque (double ended queue)
>> instead of a list:
>>
>> from collections import deque
>> queue = deque()
>>
>> To push items onto the right hand side of the queue, then pop them off the
>> left hand side:
>>
>> queue.append(item)
>> queue.popleft()
>>
>>
>> As for the rest of your question, I don't understand what you mean by an
>> order(bid and offer) queue. Perhaps you could give an example of what you
>> mean.
>>
>>
>> --
>> Steven
>> ______________________________**_________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>>
> 


From alan.gauld at btinternet.com  Sun Jul 17 23:36:23 2011
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Sun, 17 Jul 2011 22:36:23 +0100 (BST)
Subject: [Tutor] how to add directory to python search list
In-Reply-To: <CAArdDCqav4D=bra59d0a27vWy2KsrN-GfSS71UJ6E4KQN6Gm=A@mail.gmail.com>
References: <CAArdDCr=WzR=yMBbVry_BRPke=judFO-7jUn4mUkXMA33ntXMg@mail.gmail.com>
	<4E212D33.1040209@btinternet.com>
	<CAArdDCqav4D=bra59d0a27vWy2KsrN-GfSS71UJ6E4KQN6Gm=A@mail.gmail.com>
Message-ID: <1310938583.30623.YahooMailRC@web86707.mail.ird.yahoo.com>

It depends on what shell you are using.

Most beginners use the Bash shell and for that you need to open your 
.bash_profile (or .bashrc, I can't recall the preferred one for env vars...)
and add a line like:

export PYTHONPATH=$PYTHONPATH:/path/to/my/python/modules

Next time you login Python should find your modules OK.

HTH

 Alan Gauld
Author of the Learn To Program website
http://www.alan-g.me.uk/





________________________________
From: Surya P.K. Kasturi <kasturisurya at gmail.com>
To: Alan Gauld <alan.gauld at btinternet.com>
Cc: Tutor at python.org
Sent: Sunday, 17 July, 2011 7:45:08
Subject: Re: how to add directory to python search list

Mr. Gauld 

can you tell me in detail how to do this.
I am new to linux.


On Sat, Jul 16, 2011 at 11:48 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:

Surya P.K. Kasturi wrote:
>
>OS : Ubuntu Linux
>>Python Version : 2.6.4
>>
>>I have some third party modules to be installed in my computer.
>>So, I want to add the module directory to python search list.
>>
>>I used :
>>
>>*>>> import sys*
>>*>>> sys.path.append('directory address')*
>>*
>>*
>>this could do my work but as soon as I close the terminal and reopen it, I
>>

You need to add the folder to your PYTHONPATH environment variable.
>You usually do this your .login or .profile file.
>
>Python will add the contents of PYTHONPATH to sys.path on startup.
>
>HTH,
>
>
>Alan G
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110717/0ad81d71/attachment.html>

From kushal.kumaran+python at gmail.com  Mon Jul 18 08:39:44 2011
From: kushal.kumaran+python at gmail.com (Kushal Kumaran)
Date: Mon, 18 Jul 2011 12:09:44 +0530
Subject: [Tutor] what is 'doubleword alignment'?
In-Reply-To: <CANLXbfAidSnTv_w=dq0YHE+gij_HCtfc3u65xOnsEZmXuX_iAw@mail.gmail.com>
References: <1310849635.98543.YahooMailClassic@web110706.mail.gq1.yahoo.com>
	<201107171526.33581.lisi.reisz@gmail.com>
	<CANLXbfAidSnTv_w=dq0YHE+gij_HCtfc3u65xOnsEZmXuX_iAw@mail.gmail.com>
Message-ID: <CAH8GtdOw66J1ddNzichvTrckFxaaDJw6kjKpk8XQmboGFKX-cw@mail.gmail.com>

On Sun, Jul 17, 2011 at 9:15 PM, Walter Prins <wprins at gmail.com> wrote:
>
>
> On 17 July 2011 15:26, Lisi <lisi.reisz at gmail.com> wrote:
>>
>> Sorry to be slow. ?Blame virtually no sleep last night ;-( ?But even were
>> the
>> power of two bit correct (and I see subsequently that it is not), how is
>> 18 a
>> power of two?
>>
>
> The 18 bytes is a bit of an irrelevance.? The point is that if the start of
> the buffer falls on a dword (double word) alligned memory location then in
> theory the access should be faster.? The term is a little bit ambiguous
> because strictly speaking different processors have different word sizes.
> Even so, usually when people speak of double-word alignment, it's often the
> case that the term word in such a context has its original meaning, e.g. 16
> bits.? A dword is then 32bits or 4 bytes.?? A doubleword aligned memory
> address is, using these assumptions, therefore an address that is divisible
> by 4.? Obviously if the word size is 32bits, then a double word would be
> 64bits and a doubleword aligned address would need to be divisible by 8.? As
> an aside, this type of optimization is often taken care of by compilers
> under the hood, and in any case it's generally not something that you'll
> really be considering as a Python programmer.? (If however you were working
> on one of the Python runtimes or implementations, then you might well be
> sometimes considering this type of thing, depending on exactly how
> performance critical what you are working might be and what the runtime was
> being implemented in.)
>

It's not just about performance.  Some hardware simply cannot access
data that is not correctly aligned.  C programs that indiscriminately
cast among pointers to types of different sizes are a pain to port off
lenient architectures like x86.  If you're writing C code that deals
with pointers, you *always* need to keep alignment in mind.

-- 
regards,
kushal

From decrypthor at gmail.com  Mon Jul 18 10:26:51 2011
From: decrypthor at gmail.com (Ryan)
Date: Mon, 18 Jul 2011 15:26:51 +0700
Subject: [Tutor] Good Book
Message-ID: <CAFZKqUBgyCLvD5WcDSAgm00oOSnBiny09R7z7_cEG7uex2HspA@mail.gmail.com>

Dear All Pythonist,

I'm strarting learn python programming and I have been found many resources
on it but I have a problem. I don't know, what is the best complete book for
new learner like me.

I need your recommendation, thanks before . . .

-- 
It is no more than the conspiracy of 0 and 1
[decrypthor]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110718/4047647d/attachment.html>

From lists at solderintheveins.co.uk  Mon Jul 18 10:36:48 2011
From: lists at solderintheveins.co.uk (Peter Lavelle)
Date: Mon, 18 Jul 2011 09:36:48 +0100
Subject: [Tutor] Good Book
In-Reply-To: <CAFZKqUBgyCLvD5WcDSAgm00oOSnBiny09R7z7_cEG7uex2HspA@mail.gmail.com>
References: <CAFZKqUBgyCLvD5WcDSAgm00oOSnBiny09R7z7_cEG7uex2HspA@mail.gmail.com>
Message-ID: <4E23F0A0.2040208@solderintheveins.co.uk>

There's a free ebook aimed at beginners here:http://inventwithpython.com/

Regards

Peter Lavelle


On 18/07/11 09:26, Ryan wrote:
> Dear All Pythonist,
>
> I'm strarting learn python programming and I have been found many 
> resources on it but I have a problem. I don't know, what is the best 
> complete book for new learner like me.
>
> I need your recommendation, thanks before . . .
>
> -- 
> It is no more than the conspiracy of 0 and 1
> [decrypthor]
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


-- 
LinkedIn Profile: http://linkedin.com/in/pmjlavelle
Twitter: http://twitter.com/pmjlavelle

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110718/8669158b/attachment-0001.html>

From decrypthor at gmail.com  Mon Jul 18 10:39:44 2011
From: decrypthor at gmail.com (Neo Exodus)
Date: Mon, 18 Jul 2011 15:39:44 +0700
Subject: [Tutor] Good Book
In-Reply-To: <4E23F0A0.2040208@solderintheveins.co.uk>
References: <CAFZKqUBgyCLvD5WcDSAgm00oOSnBiny09R7z7_cEG7uex2HspA@mail.gmail.com>
	<4E23F0A0.2040208@solderintheveins.co.uk>
Message-ID: <CAFZKqUAMsA2oJ05q9cMvZ7SP6acvVO5jBnAbX5Y+EaeokqXYPQ@mail.gmail.com>

Ok, thank you All . . .

On Mon, Jul 18, 2011 at 3:36 PM, Peter Lavelle <lists at solderintheveins.co.uk
> wrote:

> **
> There's a free ebook aimed at beginners here:http://inventwithpython.com/
>
> Regards
>
> Peter Lavelle
>
>
>
> On 18/07/11 09:26, Ryan wrote:
>
> Dear All Pythonist,
>
>  I'm strarting learn python programming and I have been found many
> resources on it but I have a problem. I don't know, what is the best
> complete book for new learner like me.
>
>  I need your recommendation, thanks before . . .
>
> --
> It is no more than the conspiracy of 0 and 1
> [decrypthor]
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
>
> To unsubscribe or change subscription options:http://mail.python.org/mailman/listinfo/tutor
>
>
>
> --
> LinkedIn Profile: http://linkedin.com/in/pmjlavelle
> Twitter: http://twitter.com/pmjlavelle
>
>


-- 
It is no more than the conspiracy of 0 and 1
[decrypthor]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110718/a69dc84a/attachment.html>

From alan.gauld at btinternet.com  Sun Jul 17 11:00:17 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 17 Jul 2011 10:00:17 +0100
Subject: [Tutor] Good Book
In-Reply-To: <CAFZKqUBgyCLvD5WcDSAgm00oOSnBiny09R7z7_cEG7uex2HspA@mail.gmail.com>
References: <CAFZKqUBgyCLvD5WcDSAgm00oOSnBiny09R7z7_cEG7uex2HspA@mail.gmail.com>
Message-ID: <4E22A4A1.2000003@btinternet.com>

Ryan wrote:

> I'm strarting learn python programming and I have been found many resources
> on it but I have a problem. I don't know, what is the best complete book for
> new learner like me.

There are lots of books, both paper and electronic.
It depends on eactly what yopu want.

Can you already program in another language? If so,
the standard Python tutorial may be sufficient? If
not, one of the non-programmers tutorials
(like mine :-) will be better.

Personally I wouldn't recommed buyoing a paper book
until after you have learned the basics. Then you can
decide if you want a general reference (Python in a
Nutshell for example) or a specialist text like
Python Network Programming, say.

The Python.org site has many tutorials, in all
manner of styles, it just depends what kind of
tutorial you like.

??????


From alan.gauld at btinternet.com  Sun Jul 17 11:00:17 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 17 Jul 2011 10:00:17 +0100
Subject: [Tutor] Good Book
In-Reply-To: <CAFZKqUBgyCLvD5WcDSAgm00oOSnBiny09R7z7_cEG7uex2HspA@mail.gmail.com>
References: <CAFZKqUBgyCLvD5WcDSAgm00oOSnBiny09R7z7_cEG7uex2HspA@mail.gmail.com>
Message-ID: <4E22A4A1.2000003@btinternet.com>

Ryan wrote:

> I'm strarting learn python programming and I have been found many resources
> on it but I have a problem. I don't know, what is the best complete book for
> new learner like me.

There are lots of books, both paper and electronic.
It depends on eactly what yopu want.

Can you already program in another language? If so,
the standard Python tutorial may be sufficient? If
not, one of the non-programmers tutorials
(like mine :-) will be better.

Personally I wouldn't recommed buyoing a paper book
until after you have learned the basics. Then you can
decide if you want a general reference (Python in a
Nutshell for example) or a specialist text like
Python Network Programming, say.

The Python.org site has many tutorials, in all
manner of styles, it just depends what kind of
tutorial you like.

??????


From sayz at bil.omu.edu.tr  Mon Jul 18 11:22:11 2011
From: sayz at bil.omu.edu.tr (=?UTF-8?B?c2VmYSB5xLFsZMSxeg==?=)
Date: Mon, 18 Jul 2011 12:22:11 +0300
Subject: [Tutor] Good Book
In-Reply-To: <CAFZKqUBgyCLvD5WcDSAgm00oOSnBiny09R7z7_cEG7uex2HspA@mail.gmail.com>
References: <CAFZKqUBgyCLvD5WcDSAgm00oOSnBiny09R7z7_cEG7uex2HspA@mail.gmail.com>
Message-ID: <CAEPLMOXyzkY2FJcsVyOU=zDUNt3aNMndZePQ_x5khAR-7v8JeA@mail.gmail.com>

i think, this <http://openbookproject.net/thinkCSpy/index.html#> is good
book for you. (this <http://greenteapress.com/thinkpython/thinkCSpy.pdf> is
pdf version )
and also a few sources:
http://www.freenetpages.co.uk/hp/alan.gauld/
http://diveintopython.org/toc/index.html
http://www.mindview.net/Books/TIPyhttp://www.mindview.net/Books/TIPythonthon<http://www.mindview.net/Books/TIPython>
http://directory.google.com/Top/Computers/Programming/Languages/Python/FAQs,_Help,_and_Tutorials/

2011/7/18 Ryan <decrypthor at gmail.com>

> Dear All Pythonist,
>
> I'm strarting learn python programming and I have been found many resources
> on it but I have a problem. I don't know, what is the best complete book for
> new learner like me.
>
> I need your recommendation, thanks before . . .
>
> --
> It is no more than the conspiracy of 0 and 1
> [decrypthor]
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110718/1aa90593/attachment.html>

From lisi.reisz at gmail.com  Mon Jul 18 12:14:58 2011
From: lisi.reisz at gmail.com (Lisi)
Date: Mon, 18 Jul 2011 11:14:58 +0100
Subject: [Tutor] Good Book
In-Reply-To: <CAFZKqUBgyCLvD5WcDSAgm00oOSnBiny09R7z7_cEG7uex2HspA@mail.gmail.com>
References: <CAFZKqUBgyCLvD5WcDSAgm00oOSnBiny09R7z7_cEG7uex2HspA@mail.gmail.com>
Message-ID: <201107181114.58200.lisi.reisz@gmail.com>

On Monday 18 July 2011 09:26:51 Ryan wrote:
> Dear All Pythonist,
>
> I'm strarting learn python programming and I have been found many resources
> on it but I have a problem. I don't know, what is the best complete book
> for new learner like me.
>
> I need your recommendation, thanks before . . .

I am using Learn Python The Hard Way by Zed A Shaw;

http://learnpythonthehardway.org/

It is basic - assumes no knowledge of programming at all and is easy to 
follow.  But as a beginning beginner myself, I find that I do most of my 
actual learning from the marvellous people on this list, with help also from 
my local Linux User Group.  The book provides the exercises and structure.

But, as has been said, your choice will depend on your own style.

Lisi

From suryak at live.com  Mon Jul 18 16:00:43 2011
From: suryak at live.com (Surya P.K. Kasturi)
Date: Mon, 18 Jul 2011 19:30:43 +0530
Subject: [Tutor] Good Book
In-Reply-To: <CAFZKqUBgyCLvD5WcDSAgm00oOSnBiny09R7z7_cEG7uex2HspA@mail.gmail.com>
References: <CAFZKqUBgyCLvD5WcDSAgm00oOSnBiny09R7z7_cEG7uex2HspA@mail.gmail.com>
Message-ID: <CAArdDCr_vggEZD4wcFa1+aZzhNCgHaraVm0Vy7dfahdcETO+qw@mail.gmail.com>

Actually you have a lot of books that have been quoted in www.python.org.
One of them is ThinkPython book at www.thinkpython.org. Its really good.
You'll also find exercises at the end of units.


On Mon, Jul 18, 2011 at 1:56 PM, Ryan <decrypthor at gmail.com> wrote:

> Dear All Pythonist,
>
> I'm strarting learn python programming and I have been found many resources
> on it but I have a problem. I don't know, what is the best complete book for
> new learner like me.
>
> I need your recommendation, thanks before . . .
>
> --
> It is no more than the conspiracy of 0 and 1
> [decrypthor]
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110718/cd1cf578/attachment.html>

From suryak at live.com  Mon Jul 18 18:10:37 2011
From: suryak at live.com (surya k)
Date: Mon, 18 Jul 2011 21:40:37 +0530
Subject: [Tutor] getting error while solving a series that estimates the
	value of pi
Message-ID: <CAArdDCpFo3908hAQXy0oZEbLsN6rVF_n5WwkDsanVuWp6McmTg@mail.gmail.com>

Hi,

The problem is to estimate the value of pi using the following series.
 *1 / pi  = (( 2 * sqrt(2) )/ 9801 )  * SIGMA of k[ (4k)! (1103 + 26390*k) /
(k!^ 4 ) * 396^(4k)  ]*
*where k is [0, infinity)*
* Problem is located at : ThinkPython Book, www.thinkpython.org
   *Pg 89, Exercise 7.5, Think Python Book. *
*
*
the series should be considered till the last term of the sigma must be <
1e-15
I have written the below code :

*# program estimates the value of pi*
*# Ramanujan's series... *
*import math*
*
*
*def fact(n) : # def of factorial function.*
*    if n > 0 :    *
*       return n * fact(n-1)*
*    if n == 0 :*
*       return 1*
*
*
*k = 0*
*tot = 0*
*temp1 = 0*
*while k >= 0 and temp1 == 0 :*
*
*
*      a = ( 2 * math.sqrt(2) ) / 9801 # first term before sigma *
*      nu = fact (4*k) * (1103 + (26390*k) )  # numerator of series*
*      de = pow( fact(k), 4 ) * pow ( 396, 4*k )  # denominator of series*
*      *
*      if de / nu > 1e-15 : *
*            temp = nu / de*
*            tot = tot + temp*
*            temp1 = 0 *
*            k = k + 1 *
*      elif de / nu  == 1e-15 :*
*             series = a * tot  *
*             k = k + 1*
*             temp1 = 0*
*      elif de / nu < 1e-15 :*
*             print series*
*             temp1 = 1*


I am getting the following error : which is completely surprising!

*Traceback (most recent call last):*
*  File "pi.py", line 30, in <module>*
*    print series*
*NameError: name 'series' is not defined*

*
*
Thus I have removed name 'series' and replaced with  *a*tot, *
now I am getting this error

*Traceback (most recent call last):*
*  File "pi.py", line 30, in <module>*
*    print 1 / (a * tot)*
*ZeroDivisionError: float divisio*n



Thus I changed the first highlighted lines to

 *nu = float (fact (4*k) * (1103 + (26390*k) ) )*
*      de = float (pow( fact(k), 4 ) * pow ( 396, 4*k )) *


now I am getting

* Traceback (most recent call last):*
*  File "pi.py", line 18, in <module>*
*    de = float (pow( fact(k), 4 ) * pow ( 396, 4*k ) )*
*OverflowError: long int too large to convert to float*

*help me out of this problem, how could I fix this*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110718/4fa83c90/attachment.html>

From andreengels at gmail.com  Mon Jul 18 18:59:05 2011
From: andreengels at gmail.com (Andre Engels)
Date: Mon, 18 Jul 2011 18:59:05 +0200
Subject: [Tutor] getting error while solving a series that estimates the
 value of pi
In-Reply-To: <CAArdDCpFo3908hAQXy0oZEbLsN6rVF_n5WwkDsanVuWp6McmTg@mail.gmail.com>
References: <CAArdDCpFo3908hAQXy0oZEbLsN6rVF_n5WwkDsanVuWp6McmTg@mail.gmail.com>
Message-ID: <CAGzCZ0qdugVdZRGC6O7e8tHYVfaYzLuik4fzPiCm2PLorpTbnA@mail.gmail.com>

On Mon, Jul 18, 2011 at 6:10 PM, surya k <suryak at live.com> wrote:

> Hi,
>
> The problem is to estimate the value of pi using the following series.
>  *1 / pi  = (( 2 * sqrt(2) )/ 9801 )  * SIGMA of k[ (4k)! (1103 + 26390*k)
> / (k!^ 4 ) * 396^(4k)  ]*
> *where k is [0, infinity)*
> * Problem is located at : ThinkPython Book, www.thinkpython.org
>    *Pg 89, Exercise 7.5, Think Python Book. *
> *
> *
> the series should be considered till the last term of the sigma must be <
> 1e-15
> I have written the below code :
>
> *# program estimates the value of pi*
> *# Ramanujan's series... *
> *import math*
> *
> *
> *def fact(n) : # def of factorial function.*
> *    if n > 0 :    *
> *       return n * fact(n-1)*
> *    if n == 0 :*
> *       return 1*
> *
> *
> *k = 0*
> *tot = 0*
> *temp1 = 0*
> *while k >= 0 and temp1 == 0 :*
> *
> *
> *      a = ( 2 * math.sqrt(2) ) / 9801 # first term before sigma *
> *      nu = fact (4*k) * (1103 + (26390*k) )  # numerator of series*
> *      de = pow( fact(k), 4 ) * pow ( 396, 4*k )  # denominator of series*
> *      *
> *      if de / nu > 1e-15 : *
> *            temp = nu / de*
> *            tot = tot + temp*
> *            temp1 = 0 *
> *            k = k + 1 *
> *      elif de / nu  == 1e-15 :*
> *             series = a * tot  *
> *             k = k + 1*
> *             temp1 = 0*
> *      elif de / nu < 1e-15 :*
> *             print series*
> *             temp1 = 1*
>
>
> I am getting the following error : which is completely surprising!
>
> *Traceback (most recent call last):*
> *  File "pi.py", line 30, in <module>*
> *    print series*
> *NameError: name 'series' is not defined*
>
> *
> *
> Thus I have removed name 'series' and replaced with  *a*tot, *
> now I am getting this error
>
> *Traceback (most recent call last):*
> *  File "pi.py", line 30, in <module>*
> *    print 1 / (a * tot)*
> *ZeroDivisionError: float divisio*n
>
>
>
> Thus I changed the first highlighted lines to
>
>  *nu = float (fact (4*k) * (1103 + (26390*k) ) )*
> *      de = float (pow( fact(k), 4 ) * pow ( 396, 4*k )) *
>
>
> now I am getting
>
> * Traceback (most recent call last):*
> *  File "pi.py", line 18, in <module>*
> *    de = float (pow( fact(k), 4 ) * pow ( 396, 4*k ) )*
> *OverflowError: long int too large to convert to float*
>
> *help me out of this problem, how could I fix this*
>
>
You have the definitions of numerator and denominator switched.

-- 
Andr? Engels, andreengels at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110718/6c949564/attachment-0001.html>

From alan.gauld at btinternet.com  Sun Jul 17 18:59:32 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 17 Jul 2011 17:59:32 +0100
Subject: [Tutor] getting error while solving a series that estimates the
 value of pi
In-Reply-To: <CAArdDCpFo3908hAQXy0oZEbLsN6rVF_n5WwkDsanVuWp6McmTg@mail.gmail.com>
References: <CAArdDCpFo3908hAQXy0oZEbLsN6rVF_n5WwkDsanVuWp6McmTg@mail.gmail.com>
Message-ID: <4E2314F4.7020504@btinternet.com>

surya k wrote:
>
> *k = 0*
> *tot = 0*
> *temp1 = 0*
> *while k >= 0 and temp1 == 0 :*
> *      a = ( 2 * math.sqrt(2) ) / 9801 # first term before sigma *
> *      nu = fact (4*k) * (1103 + (26390*k) )  # numerator of series*
> *      de = pow( fact(k), 4 ) * pow ( 396, 4*k )  # denominator of series*
> *      *
> *      if de / nu > 1e-15 : *
> *            temp = nu / de*
> *            tot = tot + temp*
> *            temp1 = 0 *
> *            k = k + 1 *
> *      elif de / nu  == 1e-15 :*
> *             series = a * tot  *

Note that this is the only place you ever define series

> *             k = k + 1*
> *             temp1 = 0*
> *      elif de / nu < 1e-15 :*
> *             print series*

So if you ever get here without de/nu having previously been *exactly* 
1e-15 (which is pretty likely IMHO) you will get a name error.

> *             temp1 = 1*
> 
> 
> I am getting the following error : which is completely surprising!
> 
> *Traceback (most recent call last):*
> *  File "pi.py", line 30, in <module>*
> *    print series*
> *NameError: name 'series' is not defined*

Doesn't surprise me at all...

> Thus I have removed name 'series' and replaced with  *a*tot, *
> now I am getting this error

This is known as "poke 'n hope" debugging.
Better to work out why you got the previous error
message and fix it there. print statements are
your friend

HTH,

Alan G,

From alan.gauld at btinternet.com  Sun Jul 17 18:59:32 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 17 Jul 2011 17:59:32 +0100
Subject: [Tutor] getting error while solving a series that estimates the
 value of pi
In-Reply-To: <CAArdDCpFo3908hAQXy0oZEbLsN6rVF_n5WwkDsanVuWp6McmTg@mail.gmail.com>
References: <CAArdDCpFo3908hAQXy0oZEbLsN6rVF_n5WwkDsanVuWp6McmTg@mail.gmail.com>
Message-ID: <4E2314F4.7020504@btinternet.com>

surya k wrote:
>
> *k = 0*
> *tot = 0*
> *temp1 = 0*
> *while k >= 0 and temp1 == 0 :*
> *      a = ( 2 * math.sqrt(2) ) / 9801 # first term before sigma *
> *      nu = fact (4*k) * (1103 + (26390*k) )  # numerator of series*
> *      de = pow( fact(k), 4 ) * pow ( 396, 4*k )  # denominator of series*
> *      *
> *      if de / nu > 1e-15 : *
> *            temp = nu / de*
> *            tot = tot + temp*
> *            temp1 = 0 *
> *            k = k + 1 *
> *      elif de / nu  == 1e-15 :*
> *             series = a * tot  *

Note that this is the only place you ever define series

> *             k = k + 1*
> *             temp1 = 0*
> *      elif de / nu < 1e-15 :*
> *             print series*

So if you ever get here without de/nu having previously been *exactly* 
1e-15 (which is pretty likely IMHO) you will get a name error.

> *             temp1 = 1*
> 
> 
> I am getting the following error : which is completely surprising!
> 
> *Traceback (most recent call last):*
> *  File "pi.py", line 30, in <module>*
> *    print series*
> *NameError: name 'series' is not defined*

Doesn't surprise me at all...

> Thus I have removed name 'series' and replaced with  *a*tot, *
> now I am getting this error

This is known as "poke 'n hope" debugging.
Better to work out why you got the previous error
message and fix it there. print statements are
your friend

HTH,

Alan G,


From eire1130 at gmail.com  Mon Jul 18 19:08:55 2011
From: eire1130 at gmail.com (James Reynolds)
Date: Mon, 18 Jul 2011 13:08:55 -0400
Subject: [Tutor] getting error while solving a series that estimates the
 value of pi
In-Reply-To: <CAArdDCpFo3908hAQXy0oZEbLsN6rVF_n5WwkDsanVuWp6McmTg@mail.gmail.com>
References: <CAArdDCpFo3908hAQXy0oZEbLsN6rVF_n5WwkDsanVuWp6McmTg@mail.gmail.com>
Message-ID: <CAE0jAbrcHmVk9qUnmg2Zg_S-5be4VijkEDvOQN2tsssd=LDpqg@mail.gmail.com>

On Mon, Jul 18, 2011 at 12:10 PM, surya k <suryak at live.com> wrote:

> Hi,
>
> The problem is to estimate the value of pi using the following series.
>  *1 / pi  = (( 2 * sqrt(2) )/ 9801 )  * SIGMA of k[ (4k)! (1103 + 26390*k)
> / (k!^ 4 ) * 396^(4k)  ]*
> *where k is [0, infinity)*
> * Problem is located at : ThinkPython Book, www.thinkpython.org
>    *Pg 89, Exercise 7.5, Think Python Book. *
> *
> *
> the series should be considered till the last term of the sigma must be <
> 1e-15
> I have written the below code :
>
> *# program estimates the value of pi*
> *# Ramanujan's series... *
> *import math*
> *
> *
> *def fact(n) : # def of factorial function.*
> *    if n > 0 :    *
> *       return n * fact(n-1)*
> *    if n == 0 :*
> *       return 1*
> *
> *
> *k = 0*
> *tot = 0*
> *temp1 = 0*
> *while k >= 0 and temp1 == 0 :*
> *
> *
> *      a = ( 2 * math.sqrt(2) ) / 9801 # first term before sigma *
> *      nu = fact (4*k) * (1103 + (26390*k) )  # numerator of series*
> *      de = pow( fact(k), 4 ) * pow ( 396, 4*k )  # denominator of series*
> *      *
> *      if de / nu > 1e-15 : *
> *            temp = nu / de*
> *            tot = tot + temp*
> *            temp1 = 0 *
> *            k = k + 1 *
> *      elif de / nu  == 1e-15 :*
> *             series = a * tot  *
> *             k = k + 1*
> *             temp1 = 0*
> *      elif de / nu < 1e-15 :*
> *             print series*
> *             temp1 = 1*
>
>
> I am getting the following error : which is completely surprising!
>
> *Traceback (most recent call last):*
> *  File "pi.py", line 30, in <module>*
> *    print series*
> *NameError: name 'series' is not defined*
>
> *
> *
> Thus I have removed name 'series' and replaced with  *a*tot, *
> now I am getting this error
>
> *Traceback (most recent call last):*
> *  File "pi.py", line 30, in <module>*
> *    print 1 / (a * tot)*
> *ZeroDivisionError: float divisio*n
>
>
>
> Thus I changed the first highlighted lines to
>
>  *nu = float (fact (4*k) * (1103 + (26390*k) ) )*
> *      de = float (pow( fact(k), 4 ) * pow ( 396, 4*k )) *
>
>
> now I am getting
>
> * Traceback (most recent call last):*
> *  File "pi.py", line 18, in <module>*
> *    de = float (pow( fact(k), 4 ) * pow ( 396, 4*k ) )*
> *OverflowError: long int too large to convert to float*
>
> *help me out of this problem, how could I fix this*
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


I am getting the following error : which is completely surprising!


You only define "series" when nu/de == XXX. Just don't print series outside
of where it is defined, or print it outside of the while loop if you can be
assured it is defined when the while loop ends.

Even so, you would still end up with the overflow error, because you have de
/ nu and I'm assuming you want nu / de. As an aside, you might want to
consider creating a variable above all the if statements called nude = nu /
de and replace all of the nu / de 's to nude. This way you only divide once
and not (potentially) three times per loop.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110718/00a2b0b9/attachment.html>

From suryak at live.com  Mon Jul 18 19:12:38 2011
From: suryak at live.com (surya k)
Date: Mon, 18 Jul 2011 22:42:38 +0530
Subject: [Tutor] getting error while solving a series that estimates the
 value of pi
In-Reply-To: <CAE0jAbrcHmVk9qUnmg2Zg_S-5be4VijkEDvOQN2tsssd=LDpqg@mail.gmail.com>
References: <CAArdDCpFo3908hAQXy0oZEbLsN6rVF_n5WwkDsanVuWp6McmTg@mail.gmail.com>
	<CAE0jAbrcHmVk9qUnmg2Zg_S-5be4VijkEDvOQN2tsssd=LDpqg@mail.gmail.com>
Message-ID: <CAArdDCpVbWcf22pYUC6jyJv7EQ9Chd9MyC=hKXcAAq=PLPcn2A@mail.gmail.com>

Let me write the code again..
Thanks for your help.

On Mon, Jul 18, 2011 at 10:38 PM, James Reynolds <eire1130 at gmail.com> wrote:

>
>
> On Mon, Jul 18, 2011 at 12:10 PM, surya k <suryak at live.com> wrote:
>
>> Hi,
>>
>> The problem is to estimate the value of pi using the following series.
>>  *1 / pi  = (( 2 * sqrt(2) )/ 9801 )  * SIGMA of k[ (4k)! (1103 +
>> 26390*k) / (k!^ 4 ) * 396^(4k)  ]*
>> *where k is [0, infinity)*
>> * Problem is located at : ThinkPython Book, www.thinkpython.org
>>    *Pg 89, Exercise 7.5, Think Python Book. *
>> *
>> *
>> the series should be considered till the last term of the sigma must be <
>> 1e-15
>> I have written the below code :
>>
>> *# program estimates the value of pi*
>> *# Ramanujan's series... *
>> *import math*
>> *
>> *
>> *def fact(n) : # def of factorial function.*
>> *    if n > 0 :    *
>> *       return n * fact(n-1)*
>> *    if n == 0 :*
>> *       return 1*
>> *
>> *
>> *k = 0*
>> *tot = 0*
>> *temp1 = 0*
>> *while k >= 0 and temp1 == 0 :*
>> *
>> *
>> *      a = ( 2 * math.sqrt(2) ) / 9801 # first term before sigma *
>> *      nu = fact (4*k) * (1103 + (26390*k) )  # numerator of series*
>> *      de = pow( fact(k), 4 ) * pow ( 396, 4*k )  # denominator of series
>> *
>> *      *
>> *      if de / nu > 1e-15 : *
>> *            temp = nu / de*
>> *            tot = tot + temp*
>> *            temp1 = 0 *
>> *            k = k + 1 *
>> *      elif de / nu  == 1e-15 :*
>> *             series = a * tot  *
>> *             k = k + 1*
>> *             temp1 = 0*
>> *      elif de / nu < 1e-15 :*
>> *             print series*
>> *             temp1 = 1*
>>
>>
>> I am getting the following error : which is completely surprising!
>>
>> *Traceback (most recent call last):*
>> *  File "pi.py", line 30, in <module>*
>> *    print series*
>> *NameError: name 'series' is not defined*
>>
>> *
>> *
>> Thus I have removed name 'series' and replaced with  *a*tot, *
>> now I am getting this error
>>
>> *Traceback (most recent call last):*
>> *  File "pi.py", line 30, in <module>*
>> *    print 1 / (a * tot)*
>> *ZeroDivisionError: float divisio*n
>>
>>
>>
>> Thus I changed the first highlighted lines to
>>
>>  *nu = float (fact (4*k) * (1103 + (26390*k) ) )*
>> *      de = float (pow( fact(k), 4 ) * pow ( 396, 4*k )) *
>>
>>
>> now I am getting
>>
>> * Traceback (most recent call last):*
>> *  File "pi.py", line 18, in <module>*
>> *    de = float (pow( fact(k), 4 ) * pow ( 396, 4*k ) )*
>> *OverflowError: long int too large to convert to float*
>>
>> *help me out of this problem, how could I fix this*
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
>
> I am getting the following error : which is completely surprising!
>
>
> You only define "series" when nu/de == XXX. Just don't print series outside
> of where it is defined, or print it outside of the while loop if you can be
> assured it is defined when the while loop ends.
>
> Even so, you would still end up with the overflow error, because you have
> de / nu and I'm assuming you want nu / de. As an aside, you might want to
> consider creating a variable above all the if statements called nude = nu /
> de and replace all of the nu / de 's to nude. This way you only divide once
> and not (potentially) three times per loop.
>
>
>
>
>
>
>
>
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110718/3dda771e/attachment-0001.html>

From merrickdav at gmail.com  Tue Jul 19 10:45:36 2011
From: merrickdav at gmail.com (David Merrick)
Date: Tue, 19 Jul 2011 20:45:36 +1200
Subject: [Tutor] Installing module and running
Message-ID: <CA+=McKbWpdvaNTfo-dv6ZGQT3kgWnaDdVpcTNzAXU1OXVETRqw@mail.gmail.com>

I want to install the first module

http://code.google.com/p/python-nose/downloads/list

-- 
Dave Merrick

merrickdav at gmail.com

Ph   03 3423 121
Cell 027 3089 169
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110719/102ad32e/attachment.html>

From wprins at gmail.com  Tue Jul 19 11:15:49 2011
From: wprins at gmail.com (Walter Prins)
Date: Tue, 19 Jul 2011 10:15:49 +0100
Subject: [Tutor] Installing module and running
In-Reply-To: <CA+=McKbWpdvaNTfo-dv6ZGQT3kgWnaDdVpcTNzAXU1OXVETRqw@mail.gmail.com>
References: <CA+=McKbWpdvaNTfo-dv6ZGQT3kgWnaDdVpcTNzAXU1OXVETRqw@mail.gmail.com>
Message-ID: <CANLXbfCFofTiXxUHosHQ20n=Q7cKxO9DuifYUsvkvtLFAGPdQg@mail.gmail.com>

Hi David,


On 19 July 2011 09:45, David Merrick <merrickdav at gmail.com> wrote:

> I want to install the first module
>
> http://code.google.com/p/python-nose/downloads/list
>
>
What operating system?  What version of Python?

Even so, ignoring the OS and Python version issues for now (and noting that
that may affect the comments below), I'll say that normally the easiest way
to install Python packages is using the "easy_install" command which is part
of the "setuptools" package, available here:
http://pypi.python.org/pypi/setuptools#using-setuptools-and-easyinstall , by
using the command:

easy_install nose

(This assumes that easy_install is on the search path, or that your current
directory is the Python\Scripts folder already.)

Alternatively you can download the tarball (tar.gz file) you want, extract
it, then install it by changing into the folder you've extracted to and
running the "setup.py" script with an "install" parameter:

python setup.py install

(Again, this assumes that python is on your environment/shell search PATH,
and that your current folder is the root folder of the nose package, e.g.
nose-1.0.0.)

If you don't know how to extract/open tart.gz files, then install IZArc,
available here: http://www.izarc.org/


Having said all that, you really should just "easy_install nose" or perhaps
preferably "pip install nose", it's the easiest, not just for this package,
but for any other packages you might care to install into your Python
distribution...

Regards,

Walter


--
Don't be a vampire (http://slash7.com/pages/vampires)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110719/ee353173/attachment.html>

From johan at accesstel.com.au  Tue Jul 19 12:57:29 2011
From: johan at accesstel.com.au (Johan Geldenhuys)
Date: Tue, 19 Jul 2011 20:57:29 +1000
Subject: [Tutor] Using pexpect to SCP files
In-Reply-To: <be4fbf920701241805g19cb916ave04dae11410f97e9@mail.gmail.com>
References: <6f5b2c4e0701241751g773ba3ebt9486168e950d04b0@mail.gmail.com>
	<be4fbf920701241805g19cb916ave04dae11410f97e9@mail.gmail.com>
Message-ID: <018b01cc4602$a87a5490$f96efdb0$@com.au>

Hi there all,

 

I am using pexpect in a script to SCP files to a inux server.

Here is a snippet from the code:

 

    def doScp(self, user, password, host, path, files):

        

        fNames = " ".join(files)

        self.logger.log('Running command for %s' % fNames)

        try:

            

            self.child = pexpect.spawn("scp %s %s@%s:%s"%(fNames, user,
host, path)) 

            i = self.child.expect(['assword:', r"yes/no"], timeout=30)

        except:

            self.logger.logException()

            

        if i==0:

            self.logger.log('Sending password')

            self.child.sendline(password)

        elif i==1:

            self.logger.log('Sending yes and password')

            self.child.sendline("yes")

            self.child.expect("assword:", timeout=30)

            self.child.sendline(password)

            try:

                data = self.child.read()

                self.logger.log(`data`)

            except:

                self.logger.logException()

                

            self.child.expect(PROMPT)

        self.logger.log('Done with SCP')

 

 

This executes to the line in red and then times out. From what I can see
using tcpdump on the linux side, the scp traffic is going into the linux
server, but it is not sending anything back.

Is there anything obvious wrong here and is there a way I can see the exact
command sent to out?

 

The reason I chose to use pexpect is that is a pure Python method for doing
interactive sessions for scp. 

Is there a different way of doing scp in a pure pythin self contained
module? Piramiko is not an option because I cannot install it on the device
I run my script on.

 

Thank for helping.

 

Johan

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110719/4f8f3156/attachment.html>

From johan at accesstel.com.au  Tue Jul 19 13:20:34 2011
From: johan at accesstel.com.au (Johan Geldenhuys)
Date: Tue, 19 Jul 2011 21:20:34 +1000
Subject: [Tutor] Resend: Using pexpect to SCP files
In-Reply-To: <be4fbf920701241805g19cb916ave04dae11410f97e9@mail.gmail.com>
References: <6f5b2c4e0701241751g773ba3ebt9486168e950d04b0@mail.gmail.com>
	<be4fbf920701241805g19cb916ave04dae11410f97e9@mail.gmail.com>
Message-ID: <019001cc4605$e2760d30$a7622790$@com.au>

Resend in text format

Hi there all,

I am using pexpect in a script to SCP files to a inux server.
Here is a snippet from the code:

def doScp(self, user, password, host, path, files):
??????? 
??? fNames = " ".join(files)
??? self.logger.log('Running command for %s' % fNames)
??? try:
??????? 
??????? self.child = pexpect.spawn("scp %s %s@%s:%s"%(fNames, user, host,
path))
        # The script times out here: 
??????? i = self.child.expect(['assword:', r"yes/no"], timeout=30)
??? except:
??????? self.logger.logException()
??????? 
??? if i==0:
??????? self.logger.log('Sending password')
??? ????self.child.sendline(password)
??? elif i==1:
??????? self.logger.log('Sending yes and password')
??????? self.child.sendline("yes")
??????? self.child.expect("assword:", timeout=30)
??????? self.child.sendline(password)
??????? try:
??????????? data = self.child.read()
??????????? self.logger.log(`data`)
??????? except:
??????????? self.logger.logException()
??????????? 
   ???? self.child.expect(PROMPT)
??? self.logger.log('Done with SCP')


This executes at the line " i = self.child.expect(['assword:', r"yes/no"],
timeout=30)". From what I can see using tcpdump on the linux side, the scp
traffic is going into the linux server, but it is not sending anything back.
Is there anything obvious wrong here and is there a way I can see the exact
command sent to out?

The reason I chose to use pexpect is that is a pure Python method for doing
interactive sessions for scp. 
Is there a different way of doing scp in a pure pythin self contained
module? Piramiko is not an option because I cannot install it on the device
I run my script on.

Thank for helping.

Johan



From sander.sweers at gmail.com  Tue Jul 19 14:12:03 2011
From: sander.sweers at gmail.com (Sander Sweers)
Date: Tue, 19 Jul 2011 14:12:03 +0200
Subject: [Tutor] Resend: Using pexpect to SCP files
In-Reply-To: <019001cc4605$e2760d30$a7622790$@com.au>
References: <6f5b2c4e0701241751g773ba3ebt9486168e950d04b0@mail.gmail.com>
	<be4fbf920701241805g19cb916ave04dae11410f97e9@mail.gmail.com>
	<019001cc4605$e2760d30$a7622790$@com.au>
Message-ID: <CACipEsjWQHupDPsO=bnoX8PAGs4RQHO1SSR4wZRO1Mprf+RSHg@mail.gmail.com>

On 19 July 2011 13:20, Johan Geldenhuys <johan at accesstel.com.au> wrote:

It works fine for me in an interactive idle session.. Have you tried
this to see if works like this? Does the command work when run
directly from the command line?

> I am using pexpect in a script to SCP files to a inux server.
> Here is a snippet from the code:
>
> def doScp(self, user, password, host, path, files):
>
> ??? fNames = " ".join(files)
> ??? self.logger.log('Running command for %s' % fNames)
> ??? try:
>
> ??????? self.child = pexpect.spawn("scp %s %s@%s:%s"%(fNames, user, host,
> path))
> ? ? ? ?# The script times out here:

Add a print here to see what is actually send to scp (or log it to your logger).

> ??????? i = self.child.expect(['assword:', r"yes/no"], timeout=30)
> ??? except:
> ??????? self.logger.logException()
>
> ??? if i==0:
> ??????? self.logger.log('Sending password')
> ??? ????self.child.sendline(password)
> ??? elif i==1:
> ??????? self.logger.log('Sending yes and password')
> ??????? self.child.sendline("yes")
> ??????? self.child.expect("assword:", timeout=30)
> ??????? self.child.sendline(password)
> ??????? try:
> ??????????? data = self.child.read()
> ??????????? self.logger.log(`data`)
> ??????? except:
> ??????????? self.logger.logException()

The above 5 lines are only run when i == 1, not sure if this was intended.

> ? ???? self.child.expect(PROMPT)
> ??? self.logger.log('Done with SCP')

You never close the child so you *might*t have zombie processes
around. Which might cause the server not to respond to you. Regardless
It is always good to close so add self.child.close().

> This executes at the line " i = self.child.expect(['assword:', r"yes/no"],
> timeout=30)". From what I can see using tcpdump on the linux side, the scp
> traffic is going into the linux server, but it is not sending anything back.
> Is there anything obvious wrong here and is there a way I can see the exact
> command sent to out?
>
> The reason I chose to use pexpect is that is a pure Python method for doing
> interactive sessions for scp.
> Is there a different way of doing scp in a pure pythin self contained
> module? Piramiko is not an option because I cannot install it on the device
> I run my script on.

It works fine for me with the below function.

Br
Sander

def doScp(user,password, host, path, files):
    fNames = ' '.join(files)
    print fNames
    child = pexpect.spawn('scp %s %s@%s:%s' % (fNames, user, host,path))
    print 'scp %s %s@%s:%s' % (fNames, user, host,path)
        i = child.expect(['assword:', r"yes/no"], timeout=30)
        if i == 0:
            child.sendline(password)
        elif i == 1:
            child.sendline("yes")
            child.expect("assword:", timeout=30)
            child.sendline(password)
        data = child.read()
        print data
        child.close()

From thisisonlyatest at gmx.com  Wed Jul 20 04:37:16 2011
From: thisisonlyatest at gmx.com (brandon w)
Date: Tue, 19 Jul 2011 22:37:16 -0400
Subject: [Tutor] NameError: <nothing> is defined
Message-ID: <4E263F5C.7080700@gmx.com>

Hi
I am running Linux with Python 2.6.6. I have done lists, tuples, 
dictionaries, etc. Now I want to move on to creating a "class". I keep 
getting an error for everything I try. Here is the error: *

NameError: name 'MyClass' is not defined*

I had originally tried to create my own class by watching some video 
tutorials. Nothing worked. Then from the python2.6-doc documentation I 
just decided to copy and paste from the documentation.

*class  MyClass:
     """A simple example class"""
     i  =  12345
     def  f(self):
         return  'hello world'*


*>>> MyClass
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'MyClass' is not defined*

Still the same error. What am I doing wrong?
I tried this in gnome-terminal in a Python shell and using IDLE.

First I do: *import myscript.py
*(no errors)*
*
Then I run: *MyClass*
(error)

I try:  n = *MyClass()*
(error)

I try:
*MyClass.n
n.MyClass
i.MyClass
MyClass.i
i.MyClass()
f.MyClass
f.MyClass()*

(nothing but errors)



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110719/fb8d6283/attachment.html>

From redacted@example.com  Wed Jul 20 05:39:01 2011
From: redacted@example.com (Alexander Quest)
Date: Tue, 19 Jul 2011 20:39:01 -0700
Subject: [Tutor] Basic question on spaces
Message-ID: <CAHgjEe2W6SWiVhTymcNABq7JyJw8ifJ=_V9Uem+jq7Ai9uL9yg@mail.gmail.com>

Hello; I'm a new student of Python using "Python Programming for Absolute
Beginners" 3rd edition by Michael Dawson as my guide. This is a basic
question regarding spaces. I'm not sure how to make it so spaces do not show
up between variables and basic strings, particularly before commas and after
dollar signs, as in the simple "tipper" program I have below.

____________________________
#Tip program: calculates 15% and 20% tip for a given bill.

bill = int(input("Hello! Welcome to the tipper program. \nWhat is the amount
of "
             "your bill, in dollars please: "))

percent15 = bill * .15
percent20 = bill * .20
print("\nOkay, based on that bill, a 15% tip would be $", percent15, ", and
\n"
      "a 20% tip would be $", percent20, ".")
input("\n\nPress the enter key to exit.")

____________________________

As you can see, this is quite rudimentary; I have not discovered any special
function that eliminates spaces yet, if such a function exits. The problem
is, as stated above, unwanted spaces after both dollar signs, before the
comma after '15.0' and before the period after '20.0." Apologies for asking
such a basic question, but any help will be appreciated.

-Alex
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110719/3258cf79/attachment.html>

From steve at alchemy.com  Wed Jul 20 05:46:05 2011
From: steve at alchemy.com (Steve Willoughby)
Date: Tue, 19 Jul 2011 20:46:05 -0700
Subject: [Tutor] Basic question on spaces
In-Reply-To: <CAHgjEe2W6SWiVhTymcNABq7JyJw8ifJ=_V9Uem+jq7Ai9uL9yg@mail.gmail.com>
References: <CAHgjEe2W6SWiVhTymcNABq7JyJw8ifJ=_V9Uem+jq7Ai9uL9yg@mail.gmail.com>
Message-ID: <4E264F7D.4020104@alchemy.com>

On 19-Jul-11 20:39, Alexander Quest wrote:
> Hello; I'm a new student of Python using "Python Programming for
> Absolute Beginners" 3rd edition by Michael Dawson as my guide. This is a
> basic question regarding spaces. I'm not sure how to make it so spaces
> do not show up between variables and basic strings, particularly before
> commas and after dollar signs, as in the simple "tipper" program I have
> below.

You don't want to use print with a comma-separated list of values, then. 
  Your best bet would be the format string method, like this:

print """
Okay, based on that bill, a 15% tip would be ${0}, and
a 20% tip would be ${1}.
""".format(percent15, percent20)


-- 
Steve Willoughby / steve at alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C

From andreengels at gmail.com  Wed Jul 20 07:45:18 2011
From: andreengels at gmail.com (Andre Engels)
Date: Wed, 20 Jul 2011 07:45:18 +0200
Subject: [Tutor] NameError: <nothing> is defined
In-Reply-To: <4E263F5C.7080700@gmx.com>
References: <4E263F5C.7080700@gmx.com>
Message-ID: <CAGzCZ0rrn60OULb1g99yc8V1Q5t3ywUD8zHwJBu1A9_xGhUPPg@mail.gmail.com>

On Wed, Jul 20, 2011 at 4:37 AM, brandon w <thisisonlyatest at gmx.com> wrote:

> **
> Hi
> I am running Linux with Python 2.6.6. I have done lists, tuples,
> dictionaries, etc. Now I want to move on to creating a "class". I keep
> getting an error for everything I try. Here is the error: *
>
> NameError: name 'MyClass' is not defined*
>
> I had originally tried to create my own class by watching some video
> tutorials. Nothing worked. Then from the python2.6-doc documentation I just
> decided to copy and paste from the documentation.
>
>  *class MyClass:
>     """A simple example class"""
>     i = 12345
>     def f(self):
>         return 'hello world'*
>
>
> *>>> MyClass
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> NameError: name 'MyClass' is not defined*
>
> Still the same error. What am I doing wrong?
> I tried this in gnome-terminal in a Python shell and using IDLE.
>
> First I do: *import myscript.py
> *(no errors)*
> *
> Then I run: *MyClass*
> (error)
>
> I try:  n = *MyClass()*
> (error)
>
> I try:
> *MyClass.n
> n.MyClass
> i.MyClass
> MyClass.i
> i.MyClass()
> f.MyClass
> f.MyClass()*
>
> (nothing but errors)
>

You have to specify where MyClass lives. In this case it's in myscript.py.
So you have to do:

import myscript    #Note: without .py
n = myscript.MyClass()

or:

from myscript import MyClass
n = MyClass()

-- 
Andr? Engels, andreengels at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110720/45c6ece3/attachment.html>

From alan.gauld at btinternet.com  Tue Jul 19 09:31:03 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 19 Jul 2011 08:31:03 +0100
Subject: [Tutor] Basic question on spaces
In-Reply-To: <CAHgjEe2W6SWiVhTymcNABq7JyJw8ifJ=_V9Uem+jq7Ai9uL9yg@mail.gmail.com>
References: <CAHgjEe2W6SWiVhTymcNABq7JyJw8ifJ=_V9Uem+jq7Ai9uL9yg@mail.gmail.com>
Message-ID: <4E2532B7.3050904@btinternet.com>

Alexander Quest wrote:

> As you can see, this is quite rudimentary; I have not discovered any special
> function that eliminates spaces yet, if such a function exits. 

There was a thread on this a week or so back.
There you will find several suggestions however, in Python 3 the
simplest is probably to use print() itself. print takes a couple of 
optional parameters, one of which defines the separator character, by 
default a space. You can specify an empty string instead and then hard 
code your spaces.

Try
 >>> help(print)

for more details.


The other options include using a format string  or string concatenation 
to create the string you want before you send it to print.

HTH,

Alan G.


From alan.gauld at btinternet.com  Tue Jul 19 09:31:03 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 19 Jul 2011 08:31:03 +0100
Subject: [Tutor] Basic question on spaces
In-Reply-To: <CAHgjEe2W6SWiVhTymcNABq7JyJw8ifJ=_V9Uem+jq7Ai9uL9yg@mail.gmail.com>
References: <CAHgjEe2W6SWiVhTymcNABq7JyJw8ifJ=_V9Uem+jq7Ai9uL9yg@mail.gmail.com>
Message-ID: <4E2532B7.3050904@btinternet.com>

Alexander Quest wrote:

> As you can see, this is quite rudimentary; I have not discovered any special
> function that eliminates spaces yet, if such a function exits. 

There was a thread on this a week or so back.
There you will find several suggestions however, in Python 3 the
simplest is probably to use print() itself. print takes a couple of 
optional parameters, one of which defines the separator character, by 
default a space. You can specify an empty string instead and then hard 
code your spaces.

Try
 >>> help(print)

for more details.


The other options include using a format string  or string concatenation 
to create the string you want before you send it to print.

HTH,

Alan G.


From wprins at gmail.com  Wed Jul 20 11:38:49 2011
From: wprins at gmail.com (Walter Prins)
Date: Wed, 20 Jul 2011 10:38:49 +0100
Subject: [Tutor] Installing module and running
In-Reply-To: <CA+=McKZ4ev3FuO9m1LNn7D7LYy49OXdpe5F_BTbVCG7481zstg@mail.gmail.com>
References: <CA+=McKbWpdvaNTfo-dv6ZGQT3kgWnaDdVpcTNzAXU1OXVETRqw@mail.gmail.com>
	<CANLXbfAuYQwEbzWGnSiUJz4Zdj1yRrjiY=aEfSbAHTM2fnvqCA@mail.gmail.com>
	<CA+=McKYSRmCXf+q+mO4Gx2y1vkKXBK21YhAvyXk4ZF4x5dQLYA@mail.gmail.com>
	<CANLXbfBWpLtTkW1YY2Ehnb282-GqehVJc=Kge=GMG_hC8azGRg@mail.gmail.com>
	<CA+=McKZ4ev3FuO9m1LNn7D7LYy49OXdpe5F_BTbVCG7481zstg@mail.gmail.com>
Message-ID: <CANLXbfD5BZMPk4io_6_Lko739P0a=EFpOCm2FJE=J4oQcmSjeg@mail.gmail.com>

Hi David,

On 19 July 2011 20:34, David Merrick <merrickdav at gmail.com> wrote:

> Thanks for you help.Its 64 bit windows. What directory would the module go
> in? Scripts or site-packages in Lib?
>
> I have Python 2.6 in C drive but the files I am using are in a directory on
> d drive.
>
> Does the the module have to be in in the same directory as the files that
> use it?
>
>
When you install additional packages into Python (for example, the "nose"
package as in your case), they become part of your Python installation.
Because of this, you can import them just like you can import any other
module that is part of Python already and in some cases they add new
scripts/commands that can be run from a command line.

Physically what happens during installation is that the .py files (and
folders/packages) get put into your "Python\Lib" folder (for example
"C:\Python27\Lib" on my machine.)  As an aside, the reason Python is able to
find modules in this folder automatically is that the Python\Lib folder is
(by default) one of the folders that Python searches in when it encounters
an import statement.  Consequently, when you put a python module in the
Python\Lib folder, it becomes effectively available to any other Python
script you might want to run regardless of where the script being run is
physically located.

As mentioned previously, Python packages oftentimes also include command
line programs to interface with the Python installation, or provide other
functionality.  Typically such modules/programs are put into the
"Python\Scripts" folder, the idea being that you as a user can then run
these programs from there.  Unfortunately by default (at least on Windows),
the "Python\Scripts" folder is not on your command line (system) path and so
won't be found if you type only the script/command name at the command
prompt.  Consequently, if you want to use a Python script installed in the
Python\Scripts folder, you have to make that the current working directory
before running the script or specify the full path to the script, otherwise
the system obviously won't know where to find the script to run and will
respond with a "Bad command or filename" response.

What you want to do is to add the "Python\Scripts" folder to your system
path, then you'll be able to run these Python scripts/commands as if they're
inbuilt operating system commands without having to either be in the
Python\Scripts folder or specify the full path to run them.  To do this,
click on the "Start" button, right click "Computer", click "Properties",
click "Advanced System settings", click "Environment variables" button
below, find the "PATH" entry in the "System variables" list and click it to
select it, then click "Edit" below that list, press "End" to move to the end
of the line and append the scripts folder with a semicolon to delimit it
from the previous path.  In my case I therefore would append (excluding the
quotes): ";c:\Python27\Scripts" Click OK, OK again, OK again. Now when you
open a command prompt any script inside of the Python\Scrtips folder will be
directly runnable.

Now about Python package installation:  By convention if you download a
Python package manually, you can manually install it by extracting the
package archive, then changing the working directory to the root of
extracted package, and then running the "setup.py" script that is usually
included with Python packages, with an "install" option, e.g.:

python setup.py install

This does the donkey work to copy the modules of the package into the
Python\Lib folder, and Python\Scripts folder, if relevant, plus anything
else that might need to be done.  You could install your nose package like
this, e.g. by downloading it, extracting it, then running the above command
in the root of the nose folder.

I'd like to reiterate though, that one of the packages that make the
installation other Python packages even easier, is the "setuptools" package,
which amongst other things creates the "easy_install" script under the
Python\Scripts folder.  What it does, is to allow you to install other
Python packages directly from the Python package archive without having to
manually download them.  Eg once you have setuptools installed and thus have
easy_setup available as a command/script (runnable from anywhere if you've
updated your system PATH as above), then you can install nose (or any other
common package available in the Python package repository) by simply opening
a command prompt and issuing:

easy_install <packagename>

So in your case you'd enter:

easy_install nose

That's it!  This will then automatically download the nose package from the
internet, and install it for you. It really is worth it to install
setuptools (or one of the newer variants like "pip" or "distribute"...) as
this makes your life as a Python developer a lot easier when it comes to
getting packages downloaded and installed into your Python environment.

Does that give you enough understanding to get you going?

Cheers

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110720/b5e645a5/attachment.html>

From rdmoores at gmail.com  Wed Jul 20 15:41:42 2011
From: rdmoores at gmail.com (Richard D. Moores)
Date: Wed, 20 Jul 2011 06:41:42 -0700
Subject: [Tutor] Is the Python 3.2.1 documentation available as a .chm file?
Message-ID: <CALMxxxnzNiFMpNJ0VZLdGhBMO_eHuXX+DH_RZAJezTATEuFnXQ@mail.gmail.com>

Is the Python 3.2.1 documentation available as a .chm file from Python.org?

Thanks,

Dick Moores

From alan.gauld at btinternet.com  Tue Jul 19 16:05:26 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 19 Jul 2011 15:05:26 +0100
Subject: [Tutor] Is the Python 3.2.1 documentation available as a .chm
	file?
In-Reply-To: <CALMxxxnzNiFMpNJ0VZLdGhBMO_eHuXX+DH_RZAJezTATEuFnXQ@mail.gmail.com>
References: <CALMxxxnzNiFMpNJ0VZLdGhBMO_eHuXX+DH_RZAJezTATEuFnXQ@mail.gmail.com>
Message-ID: <j06nbh$nq2$1@dough.gmane.org>

Richard D. Moores wrote:
> Is the Python 3.2.1 documentation available as a .chm file from Python.org?

I think you'll need to go to Activestate for that.

Alan g


From rdmoores at gmail.com  Wed Jul 20 16:06:49 2011
From: rdmoores at gmail.com (Richard D. Moores)
Date: Wed, 20 Jul 2011 07:06:49 -0700
Subject: [Tutor] Is the Python 3.2.1 documentation available as a .chm
	file?
In-Reply-To: <D35D4ADAE41B404A9EB381E750C1A5A57950BC@CAPPRWMMBX14.central.ad.capita.co.uk>
References: <CALMxxxnzNiFMpNJ0VZLdGhBMO_eHuXX+DH_RZAJezTATEuFnXQ@mail.gmail.com>
	<D35D4ADAE41B404A9EB381E750C1A5A57950BC@CAPPRWMMBX14.central.ad.capita.co.uk>
Message-ID: <CALMxxxkLe78o8R8Ktnypmvp4QFXDM0t2kim3hRYFVQgE=g2Onw@mail.gmail.com>

On Wed, Jul 20, 2011 at 06:58, Flynn, Stephen (L & P - IT)
<Steve.Flynn at capita.co.uk> wrote:
> Saying that, there's nothing stopping you from taking the html version
> and compiling your own chm from it. Pretty easy to do.

Great! But how?

Dick

From wprins at gmail.com  Wed Jul 20 16:28:43 2011
From: wprins at gmail.com (Walter Prins)
Date: Wed, 20 Jul 2011 15:28:43 +0100
Subject: [Tutor] Is the Python 3.2.1 documentation available as a .chm
	file?
In-Reply-To: <CALMxxxkLe78o8R8Ktnypmvp4QFXDM0t2kim3hRYFVQgE=g2Onw@mail.gmail.com>
References: <CALMxxxnzNiFMpNJ0VZLdGhBMO_eHuXX+DH_RZAJezTATEuFnXQ@mail.gmail.com>
	<D35D4ADAE41B404A9EB381E750C1A5A57950BC@CAPPRWMMBX14.central.ad.capita.co.uk>
	<CALMxxxkLe78o8R8Ktnypmvp4QFXDM0t2kim3hRYFVQgE=g2Onw@mail.gmail.com>
Message-ID: <CANLXbfDXhffspubeHOLb0pbP+koM_YmmvZ6wchHvZ-9YH-9Jxw@mail.gmail.com>

On 20 July 2011 15:06, Richard D. Moores <rdmoores at gmail.com> wrote:

> On Wed, Jul 20, 2011 at 06:58, Flynn, Stephen (L & P - IT)
> <Steve.Flynn at capita.co.uk> wrote:
> > Saying that, there's nothing stopping you from taking the html version
> > and compiling your own chm from it. Pretty easy to do.
>
> Great! But how?
>
>
Google throws up this as most relevant IMHO:
http://msdn.microsoft.com/en-us/library/ms670169%28v=vs.85%29.aspx

Google also throws up this (http://chmprocessor.sourceforge.net/) which may
be interesting/relevant.

W
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110720/f5bc22f6/attachment.html>

From timo.smieszek at daad-alumni.de  Wed Jul 20 16:26:54 2011
From: timo.smieszek at daad-alumni.de (Timo Smieszek)
Date: Wed, 20 Jul 2011 10:26:54 -0400
Subject: [Tutor] Unstable IDLE
Message-ID: <4E26E5AE.4070806@daad-alumni.de>

Hi

I use Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) on a 
Macbook Pro (Mac OS X 10.6.7).
Whenever I want to open a new window in the IDLE or whenever I work with 
.py file within the IDLE, it crashes either immediately (in case of 
opening a new window) or after a short time (in case of opening an 
existing file).

I already installed Python a second time, but this also does not help.

Has anybody an idea how to fix this problem?

Thanks and all best

Timo



From rdmoores at gmail.com  Wed Jul 20 17:15:50 2011
From: rdmoores at gmail.com (Richard D. Moores)
Date: Wed, 20 Jul 2011 08:15:50 -0700
Subject: [Tutor] Is the Python 3.2.1 documentation available as a .chm
	file?
In-Reply-To: <CANLXbfDXhffspubeHOLb0pbP+koM_YmmvZ6wchHvZ-9YH-9Jxw@mail.gmail.com>
References: <CALMxxxnzNiFMpNJ0VZLdGhBMO_eHuXX+DH_RZAJezTATEuFnXQ@mail.gmail.com>
	<D35D4ADAE41B404A9EB381E750C1A5A57950BC@CAPPRWMMBX14.central.ad.capita.co.uk>
	<CALMxxxkLe78o8R8Ktnypmvp4QFXDM0t2kim3hRYFVQgE=g2Onw@mail.gmail.com>
	<CANLXbfDXhffspubeHOLb0pbP+koM_YmmvZ6wchHvZ-9YH-9Jxw@mail.gmail.com>
Message-ID: <CALMxxxm_-0ue6TgpPS8FktcUm=9w799oS=G_oF2x-w9XnwX4PA@mail.gmail.com>

On Wed, Jul 20, 2011 at 07:28, Walter Prins <wprins at gmail.com> wrote:
>
>
> On 20 July 2011 15:06, Richard D. Moores <rdmoores at gmail.com> wrote:
>>
>> On Wed, Jul 20, 2011 at 06:58, Flynn, Stephen (L & P - IT)
>> <Steve.Flynn at capita.co.uk> wrote:
>> > Saying that, there's nothing stopping you from taking the html version
>> > and compiling your own chm from it. Pretty easy to do.
>>
>> Great! But how?
>>
>
> Google throws up this as most relevant IMHO:
> http://msdn.microsoft.com/en-us/library/ms670169%28v=vs.85%29.aspx

Sorry, I just can't make sense of that page.

> Google also throws up this (http://chmprocessor.sourceforge.net/) which may
> be interesting/relevant.

So I downloaded and installed chmProcessor only to find that "Only one
HTML file can be used as source", and there are many in the Python
docs.

Dick

From shahdharmit at gmail.com  Wed Jul 20 17:22:03 2011
From: shahdharmit at gmail.com (Dharmit Shah)
Date: Wed, 20 Jul 2011 20:52:03 +0530
Subject: [Tutor] Web Programming
Message-ID: <CAJQZradGVZ0+5FqLfMxpRPYxYiew08qG_7Z-jS=buW7c3r_Tdg@mail.gmail.com>

Hi all,

I have been reading Head First
Python<http://www.headfirstlabs.com/books/hfpython/> since
some time now. I am stuck in a chapter on Web Development. Web Development
has never been an area of my interest and hence I feel stuck in there. If
anyone here has read the book, I wish to know if it's okay to skip that
chapter and read further?

-- 
Regards

Dharmit Shah <http://about.me/dharmit>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110720/86a0d009/attachment.html>

From eire1130 at gmail.com  Wed Jul 20 17:54:20 2011
From: eire1130 at gmail.com (James Reynolds)
Date: Wed, 20 Jul 2011 11:54:20 -0400
Subject: [Tutor] Web Programming
In-Reply-To: <CAJQZradGVZ0+5FqLfMxpRPYxYiew08qG_7Z-jS=buW7c3r_Tdg@mail.gmail.com>
References: <CAJQZradGVZ0+5FqLfMxpRPYxYiew08qG_7Z-jS=buW7c3r_Tdg@mail.gmail.com>
Message-ID: <CAE0jAbrZ6uzPWo5gsokgbSbGj=how9uTeOJNPCzURYSRfT93mg@mail.gmail.com>

If it doesn't interest you, skip it and move on. You can always come back
and learn it later, which will be easier anyway, with a more robust
background.

On Wed, Jul 20, 2011 at 11:22 AM, Dharmit Shah <shahdharmit at gmail.com>wrote:

> Hi all,
>
> I have been reading Head First Python<http://www.headfirstlabs.com/books/hfpython/> since
> some time now. I am stuck in a chapter on Web Development. Web Development
> has never been an area of my interest and hence I feel stuck in there. If
> anyone here has read the book, I wish to know if it's okay to skip that
> chapter and read further?
>
> --
> Regards
>
> Dharmit Shah <http://about.me/dharmit>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110720/7188185b/attachment-0001.html>

From armvrt at gmail.com  Wed Jul 20 17:57:19 2011
From: armvrt at gmail.com (Shwinn Ricci)
Date: Wed, 20 Jul 2011 11:57:19 -0400
Subject: [Tutor] Pyglet for 2.7
Message-ID: <CAM-hM0VcLkzbqkMfRbhKDN3-GKsQavnQOdrZ9bq1JDxDhe-7mA@mail.gmail.com>

Is this out yet?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110720/ef121e0a/attachment.html>

From armvrt at gmail.com  Wed Jul 20 17:57:51 2011
From: armvrt at gmail.com (Shwinn Ricci)
Date: Wed, 20 Jul 2011 11:57:51 -0400
Subject: [Tutor] Pyglet for 2.7
Message-ID: <CAM-hM0W_EZsvET1Bp4TnF2hMCRstOtgQk9rrm-GRGnHypZOJVA@mail.gmail.com>

(on a mac. 2.7 python just in case)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110720/e599544c/attachment.html>

From thudfoo at gmail.com  Wed Jul 20 18:04:18 2011
From: thudfoo at gmail.com (xDog Walker)
Date: Wed, 20 Jul 2011 09:04:18 -0700
Subject: [Tutor] Is the Python 3.2.1 documentation available as a .chm
	file?
In-Reply-To: <CALMxxxnzNiFMpNJ0VZLdGhBMO_eHuXX+DH_RZAJezTATEuFnXQ@mail.gmail.com>
References: <CALMxxxnzNiFMpNJ0VZLdGhBMO_eHuXX+DH_RZAJezTATEuFnXQ@mail.gmail.com>
Message-ID: <201107200904.18846.thudfoo@gmail.com>

On Wednesday 2011 July 20 06:41, Richard D. Moores wrote:
> Is the Python 3.2.1 documentation available as a .chm file from Python.org?
>

http://www.python.org/ftp/python/3.2.1/python321.chm

HTH

-- 
I have seen the future and I am not in it.

From waynejwerner at gmail.com  Wed Jul 20 18:10:44 2011
From: waynejwerner at gmail.com (Wayne Werner)
Date: Wed, 20 Jul 2011 11:10:44 -0500
Subject: [Tutor] Pyglet for 2.7
In-Reply-To: <CAM-hM0W_EZsvET1Bp4TnF2hMCRstOtgQk9rrm-GRGnHypZOJVA@mail.gmail.com>
References: <CAM-hM0W_EZsvET1Bp4TnF2hMCRstOtgQk9rrm-GRGnHypZOJVA@mail.gmail.com>
Message-ID: <CAPM86NeNbTkQPRD9-heF5eEdL-iYEGFhq15-6ZrarHou90Vniw@mail.gmail.com>

What does their website say?

On Wed, Jul 20, 2011 at 10:57 AM, Shwinn Ricci <armvrt at gmail.com> wrote:

> (on a mac. 2.7 python just in case)
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110720/d1d05192/attachment.html>

From rdmoores at gmail.com  Wed Jul 20 19:10:58 2011
From: rdmoores at gmail.com (Richard D. Moores)
Date: Wed, 20 Jul 2011 10:10:58 -0700
Subject: [Tutor] Is the Python 3.2.1 documentation available as a .chm
	file?
In-Reply-To: <201107200904.18846.thudfoo@gmail.com>
References: <CALMxxxnzNiFMpNJ0VZLdGhBMO_eHuXX+DH_RZAJezTATEuFnXQ@mail.gmail.com>
	<201107200904.18846.thudfoo@gmail.com>
Message-ID: <CALMxxx=aMLmSFOQv1140C_74SCC7z_BjstxAC2pX3fwD2TwUKA@mail.gmail.com>

On Wed, Jul 20, 2011 at 09:04, xDog Walker <thudfoo at gmail.com> wrote:
> On Wednesday 2011 July 20 06:41, Richard D. Moores wrote:
>> Is the Python 3.2.1 documentation available as a .chm file from Python.org?
>>
>
> http://www.python.org/ftp/python/3.2.1/python321.chm

Did that work for you? It got me a chm file that says everywhere,
"Navigation to the web
page was cancelled".

Dick

From waynejwerner at gmail.com  Wed Jul 20 19:37:39 2011
From: waynejwerner at gmail.com (Wayne Werner)
Date: Wed, 20 Jul 2011 12:37:39 -0500
Subject: [Tutor] Unstable IDLE
In-Reply-To: <4E26E5AE.4070806@daad-alumni.de>
References: <4E26E5AE.4070806@daad-alumni.de>
Message-ID: <CAPM86NdwAjH7twHBAed=rqJaavRsuX5UiJ1eeUQJe25TTRmpXg@mail.gmail.com>

On Wed, Jul 20, 2011 at 9:26 AM, Timo Smieszek <timo.smieszek at daad-alumni.de
> wrote:

> Hi
>
> I use Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) on a
> Macbook Pro (Mac OS X 10.6.7).
> Whenever I want to open a new window in the IDLE or whenever I work with
> .py file within the IDLE, it crashes either immediately (in case of opening
> a new window) or after a short time (in case of opening an existing file).
>
> I already installed Python a second time, but this also does not help.
>
> Has anybody an idea how to fix this problem?


Try launching from the command line - you should be able to open the
terminal and type idle at the prompt. You'll probably get some more useful
information from the traceback when it crashes. If you copy the last line
and search Google for "mac python idle crash " + line, then it might get you
some good information. If not, you could copy/paste the entire traceback
here and maybe someone can point you in the right direction.

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110720/ad1f86e4/attachment.html>

From fomcl at yahoo.com  Wed Jul 20 20:49:19 2011
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Wed, 20 Jul 2011 11:49:19 -0700 (PDT)
Subject: [Tutor] questions on encoding
Message-ID: <1311187759.6783.YahooMailClassic@web110704.mail.gq1.yahoo.com>

Hi,

I am looking for test data with accented and multibyte characters. I have found a good resource that I could use to cobble something together (http://www.inter-locale.com/whitepaper/learn/learn-to-test.html) but I was hoping somebody knows some ready resource.

I also have some questions about encoding. In the code below, is there a difference between unicode() and .decode?
s = "??????"
x = unicode(s, "utf-8")
y = s.decode("utf-8")
x == y # returns True

Also, is it, at least theoretically, possible to mix different encodings in byte strings? I'd say no, unless there are multiple BOMs or so. Not that I'd like to try this, but it'd improve my understanding of this sort of obscure topic.


Cheers!!

Albert-Jan



~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110720/00d9b207/attachment-0001.html>

From fomcl at yahoo.com  Wed Jul 20 21:12:46 2011
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Wed, 20 Jul 2011 12:12:46 -0700 (PDT)
Subject: [Tutor] what is 'doubleword alignment'?
In-Reply-To: <CAH8GtdOw66J1ddNzichvTrckFxaaDJw6kjKpk8XQmboGFKX-cw@mail.gmail.com>
Message-ID: <1311189166.61425.YahooMailClassic@web110701.mail.gq1.yahoo.com>

--- On Mon, 7/18/11, Kushal Kumaran <kushal.kumaran+python at gmail.com> wrote:

From: Kushal Kumaran <kushal.kumaran+python at gmail.com>
Subject: Re: [Tutor] what is 'doubleword alignment'?
To: "Walter Prins" <wprins at gmail.com>
Cc: tutor at python.org
Date: Monday, July 18, 2011, 8:39 AM

On Sun, Jul 17, 2011 at 9:15 PM, Walter Prins <wprins at gmail.com> wrote:
>
>
> On 17 July 2011 15:26, Lisi <lisi.reisz at gmail.com> wrote:
>>
>> Sorry to be slow. ?Blame virtually no sleep last night ;-( ?But even were
>> the
>> power of two bit correct (and I see subsequently that it is not), how is
>> 18 a
>> power of two?
>>
>
> The 18 bytes is a bit of an irrelevance.? The point is that if the start of
> the buffer falls on a dword (double word) alligned memory location then in
> theory the access should be faster.? The term is a little bit ambiguous
> because strictly speaking different processors have different word sizes.
> Even so, usually when people speak of double-word alignment, it's often the
> case that the term word in such a context has its original meaning, e.g. 16
> bits.? A dword is then 32bits or 4 bytes.?? A doubleword aligned memory
> address is, using these assumptions, therefore an address that is divisible
> by 4.? Obviously if the word size is 32bits, then a double word would be
> 64bits and a doubleword aligned address would need to be divisible by 8.? As
> an aside, this type of optimization is often taken care of by compilers
> under the hood, and in any case it's generally not something that you'll
> really be considering as a Python programmer.? (If however you were working
> on one of the Python runtimes or implementations, then you might well be
> sometimes considering this type of thing, depending on exactly how
> performance critical what you are working might be and what the runtime was
> being implemented in.)
>

It's not just about performance.? Some hardware simply cannot access
data that is not correctly aligned.? C programs that indiscriminately
cast among pointers to types of different sizes are a pain to port off
lenient architectures like x86.? If you're writing C code that deals
with pointers, you *always* need to keep alignment in mind.

-- 
regards,
kushal

===> Hello, 

Sorry for the late reply. Thank you all for your replies. I said '18' but I meant '16' (maybe my fingers are too big ;-). 

The text I put in my original post was from the documentation of a .dll/.so file (programmed in C). It was part of a procedure that reads out data. Each variable is 8 bytes or (for string variables) mutliples of 8 bytes (and each byte is 8 bits). I am using struct.unpack and ctypes to process the data in python. It works now, although I still want to read more about this. Where does the distinction little/big endian enter this story?

Thanks again, I appreciate it!

Albert-Jan
_______________________________________________
Tutor maillist? -? Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110720/2f54baf3/attachment.html>

From alan.gauld at btinternet.com  Tue Jul 19 23:43:40 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 19 Jul 2011 22:43:40 +0100
Subject: [Tutor] little/big endian was Re: what is 'doubleword alignment'?
In-Reply-To: <1311189166.61425.YahooMailClassic@web110701.mail.gq1.yahoo.com>
References: <CAH8GtdOw66J1ddNzichvTrckFxaaDJw6kjKpk8XQmboGFKX-cw@mail.gmail.com>
	<1311189166.61425.YahooMailClassic@web110701.mail.gq1.yahoo.com>
Message-ID: <4E25FA8C.10006@btinternet.com>

Albert-Jan Roskam wrote:
 > and ctypes to process the data in python. It works now, although I
 > still want to read more about this. Where does the distinction
 > little/big endian enter this story?

That's to do with which bit in a byte/word is most significant.

e.g. is the decimal value 1 stored as

00000001   # the one on the right hand nibble
or as
00010000   # the one on the left hand nibble

Now scale that up to word sized numbers...
Different CPUs do it differently.

I can't recall which is which - I'm sure wikipedia will
reveal all! :-)

HTH,

Alan G.
Growing to hate my Netbook keyboard more by the day!
And hating my PC repairer even more!

From alan.gauld at btinternet.com  Tue Jul 19 23:43:40 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 19 Jul 2011 22:43:40 +0100
Subject: [Tutor] little/big endian was Re: what is 'doubleword alignment'?
In-Reply-To: <1311189166.61425.YahooMailClassic@web110701.mail.gq1.yahoo.com>
References: <CAH8GtdOw66J1ddNzichvTrckFxaaDJw6kjKpk8XQmboGFKX-cw@mail.gmail.com>
	<1311189166.61425.YahooMailClassic@web110701.mail.gq1.yahoo.com>
Message-ID: <4E25FA8C.10006@btinternet.com>

Albert-Jan Roskam wrote:
 > and ctypes to process the data in python. It works now, although I
 > still want to read more about this. Where does the distinction
 > little/big endian enter this story?

That's to do with which bit in a byte/word is most significant.

e.g. is the decimal value 1 stored as

00000001   # the one on the right hand nibble
or as
00010000   # the one on the left hand nibble

Now scale that up to word sized numbers...
Different CPUs do it differently.

I can't recall which is which - I'm sure wikipedia will
reveal all! :-)

HTH,

Alan G.
Growing to hate my Netbook keyboard more by the day!
And hating my PC repairer even more!


From kbaclig at yahoo.com  Wed Jul 20 23:54:52 2011
From: kbaclig at yahoo.com (Ken Baclig)
Date: Wed, 20 Jul 2011 14:54:52 -0700 (PDT)
Subject: [Tutor] Homework problem
Message-ID: <1311198892.78716.YahooMailNeo@web126002.mail.ne1.yahoo.com>

Hi,

I'm trying to make a function that receives text (a string) as an argument and returns the same text (as string), but with 1 added to each word that is a number.

I need help getting started.

So far, I have:

def FindNumbers(a_string):

?? ?for index, char in enumerate(a_string):
?? ? ? ?if char.isdigit():
a_string[index] =?


def Test():

?? ?sometext = "I got 432 when I counted, but Jim got 433 which is a lot foronly 6 cats, or were there 12 cats?"
?? ?
?? ?FindNumbers(sometext)

Test()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110720/db519cf1/attachment.html>

From marc.tompkins at gmail.com  Thu Jul 21 00:45:46 2011
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Wed, 20 Jul 2011 15:45:46 -0700
Subject: [Tutor] Homework problem
In-Reply-To: <1311198892.78716.YahooMailNeo@web126002.mail.ne1.yahoo.com>
References: <1311198892.78716.YahooMailNeo@web126002.mail.ne1.yahoo.com>
Message-ID: <CAKK8jXYs8wRvibiY6nV8O4MuXEYbcB3hrmQndpTBP366feRkTg@mail.gmail.com>

On Wed, Jul 20, 2011 at 2:54 PM, Ken Baclig <kbaclig at yahoo.com> wrote:

> Hi,
>
> I'm trying to make a function that receives text (a string) as an argument
> and returns the same text (as string), but with 1 added to each word that is
> a number.
>
> I need help getting started.
>
> So far, I have:
>
> def FindNumbers(a_string):
>
>     for index, char in enumerate(a_string):
>         if char.isdigit():
> a_string[index] =
>
>
> def Test():
>
>     sometext = "I got 432 when I counted, but Jim got 433 which is a lot
> foronly 6 cats, or were there 12 cats?"
>
>     FindNumbers(sometext)
>
> Test()
>

First of all, don't enumerate() the string; split() it instead - this will
give you a list of words instead of characters.
Then, look at each item in that list; check to see whether it's numeric -
isdigit() works for this.
If it _is_ numeric, convert it to an int, add one to it, and turn it back
into a string.
Join the list back into a string, and you're done.

Note: you can step through the items in a list by saying (for example) "for
word in words:" - but if you do it that way you can't modify any of the
items.  If you need to modify them - by adding 1, for example - you need to
refer to them by index instead, and the quickest way to do that is "for x in
range(len(words)):  print words[x]".

That was a bunch of broad hints - if you need help putting them together,
feel free to ask.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110720/c2d1c4bf/attachment-0001.html>

From kbaclig at yahoo.com  Thu Jul 21 00:51:04 2011
From: kbaclig at yahoo.com (Ken Baclig)
Date: Wed, 20 Jul 2011 15:51:04 -0700 (PDT)
Subject: [Tutor] Homework problem
In-Reply-To: <CAKK8jXYs8wRvibiY6nV8O4MuXEYbcB3hrmQndpTBP366feRkTg@mail.gmail.com>
References: <1311198892.78716.YahooMailNeo@web126002.mail.ne1.yahoo.com>
	<CAKK8jXYs8wRvibiY6nV8O4MuXEYbcB3hrmQndpTBP366feRkTg@mail.gmail.com>
Message-ID: <1311202264.96356.YahooMailNeo@web126011.mail.ne1.yahoo.com>

Does this look right? ?Still a little confused....

?? ? ? ?if char.isdigit():
?? ? ? ? ? num = int(char) + 1
?? ? ? ? ? a_string[index] = str(num)
print a_string




________________________________
From: Marc Tompkins <marc.tompkins at gmail.com>
To: Ken Baclig <kbaclig at yahoo.com>
Cc: "tutor at python.org" <tutor at python.org>
Sent: Wednesday, July 20, 2011 3:45 PM
Subject: Re: [Tutor] Homework problem


On Wed, Jul 20, 2011 at 2:54 PM, Ken Baclig <kbaclig at yahoo.com> wrote:

Hi,
>
>
>I'm trying to make a function that receives text (a string) as an argument and returns the same text (as string), but with 1 added to each word that is a number.
>
>
>I need help getting started.
>
>
>So far, I have:
>
>
>def FindNumbers(a_string):
>
>
>?? ?for index, char in enumerate(a_string):
>?? ? ? ?if char.isdigit():
>a_string[index] =?
>
>
>
>
>def Test():
>
>
>?? ?sometext = "I got 432 when I counted, but Jim got 433 which is a lot foronly 6 cats, or were there 12 cats?"
>?? ?
>?? ?FindNumbers(sometext)
>
>
>Test()
First of all, don't enumerate() the string; split() it instead - this will give you a list of words instead of characters.
Then, look at each item in that list; check to see whether it's numeric - isdigit() works for this.
If it _is_ numeric, convert it to an int, add one to it, and turn it back into a string.
Join the list back into a string, and you're done.

Note: you can step through the items in a list by saying (for example) "for word in words:" - but if you do it that way you can't modify any of the items.? If you need to modify them - by adding 1, for example - you need to refer to them by index instead, and the quickest way to do that is "for x in range(len(words)):? print words[x]".

That was a bunch of broad hints - if you need help putting them together, feel free to ask. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110720/40d7da5a/attachment.html>

From alan.gauld at btinternet.com  Wed Jul 20 01:14:31 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 20 Jul 2011 00:14:31 +0100
Subject: [Tutor] Homework problem
In-Reply-To: <1311202264.96356.YahooMailNeo@web126011.mail.ne1.yahoo.com>
References: <1311198892.78716.YahooMailNeo@web126002.mail.ne1.yahoo.com>	<CAKK8jXYs8wRvibiY6nV8O4MuXEYbcB3hrmQndpTBP366feRkTg@mail.gmail.com>
	<1311202264.96356.YahooMailNeo@web126011.mail.ne1.yahoo.com>
Message-ID: <4E260FD7.3010400@btinternet.com>

Ken Baclig wrote:
> Does this look right?  Still a little confused....
> 

Nope.
Notice that Marc said NOT to operate on characters but to split() the 
string into a wordlist. Then test for each word in the wordlist to see 
if it isdigit(). Igf so then convert the word to an int() and add one.
Then convert the new int back to a str()and insert back into your 
wordlist. Finally join() your wordlist with spaces to get your
original "sentence" back.


>         if char.isdigit():
>            num = int(char) + 1
>            a_string[index] = str(num)
> print a_string

> If you need to modify them - by adding 1, for example - you need to 
 > refer to them by index instead, and the quickest way to do that is
 > "for x in range(len(words)):  print words[x]".

Or use the enumerate() function you started with....

HTH,

Alan G.


From alan.gauld at btinternet.com  Wed Jul 20 01:14:31 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 20 Jul 2011 00:14:31 +0100
Subject: [Tutor] Homework problem
In-Reply-To: <1311202264.96356.YahooMailNeo@web126011.mail.ne1.yahoo.com>
References: <1311198892.78716.YahooMailNeo@web126002.mail.ne1.yahoo.com>	<CAKK8jXYs8wRvibiY6nV8O4MuXEYbcB3hrmQndpTBP366feRkTg@mail.gmail.com>
	<1311202264.96356.YahooMailNeo@web126011.mail.ne1.yahoo.com>
Message-ID: <4E260FD7.3010400@btinternet.com>

Ken Baclig wrote:
> Does this look right?  Still a little confused....
> 

Nope.
Notice that Marc said NOT to operate on characters but to split() the 
string into a wordlist. Then test for each word in the wordlist to see 
if it isdigit(). Igf so then convert the word to an int() and add one.
Then convert the new int back to a str()and insert back into your 
wordlist. Finally join() your wordlist with spaces to get your
original "sentence" back.


>         if char.isdigit():
>            num = int(char) + 1
>            a_string[index] = str(num)
> print a_string

> If you need to modify them - by adding 1, for example - you need to 
 > refer to them by index instead, and the quickest way to do that is
 > "for x in range(len(words)):  print words[x]".

Or use the enumerate() function you started with....

HTH,

Alan G.


From steve at pearwood.info  Thu Jul 21 03:11:27 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 21 Jul 2011 11:11:27 +1000
Subject: [Tutor] Homework problem
In-Reply-To: <1311198892.78716.YahooMailNeo@web126002.mail.ne1.yahoo.com>
References: <1311198892.78716.YahooMailNeo@web126002.mail.ne1.yahoo.com>
Message-ID: <4E277CBF.3080106@pearwood.info>

Ken Baclig wrote:
> Hi,
> 
> I'm trying to make a function that receives text (a string) as an argument and returns the same text (as string), but with 1 added to each word that is a number.


What counts as a number? In the string:

"Hello world 1234 ham spam"

which of these do you expect to get back?

"Hello world 2345 ham spam"  # Add one to each digit.
"Hello world 1235 ham spam"  # Add one to each number.

What about strings without spaces like "foo123bar"?

I'm going to assume that you mean to add 1 to any digit, not just to 
complete numbers.



> I need help getting started.
> 
> So far, I have:
> 
> def FindNumbers(a_string):
> 
>     for index, char in enumerate(a_string):
>         if char.isdigit():
> a_string[index] = 



This can't work, because strings are immutable. They cannot be changed 
in place. You have to form a new string.

The approach I would take is something like this. Here's a version which 
doesn't actually add one to each digit, but merely turns any digit into 
an asterisk. Your job is to make it do what it is supposed to do.


def add_one_to_digits(a_string):
     # Give the function a name that says what it does. It doesn't
     # just FindNumbers, that name is completely inappropriate.
     result = []  # Holder to build up a new string.
     for char in a_string:
         if char.isdigit():
             char = "*"
         # Anything else gets passed through unchanged.
         result.append(char)
     # Assemble the characters into a string.
     return ''.join(result)




> def Test():
>     sometext = "I got 432 when I counted, but Jim got 433 which is a lot foronly 6 cats, or were there 12 cats?"
>     FindNumbers(sometext)
> 
> Test()


Test functions should actually test something. Try this instead:


def test():
     source = ("I got 432 when I counted, but Jim got 433 which "
               "is a lot for only 6 cats, or were there 12 cats?")
     expected = ("I got 543 when I counted, but Jim got 544 which "
               "is a lot for only 7 cats, or were there 23 cats?")
     actual = add_one_to_digits(source)
     if actual == expected:
         print("Test passes!")
     else:
         print("Test fails!")
         print("Expected '%s'" % expected)
         print("but actually got '%s'" % actual)



By the way, the test case is not very good, because there is one digit 
which is special compared to the others, and it doesn't get tested. 
Think about it... out of the 10 possible digits, 9 of them are obvious: 
0 -> 1
1 -> 2
2 -> 3 etc.

but one digit is not obvious. Can you see which one? So you need to 
include that digit in the test case, so you know it gets handled correctly.




-- 
Steven

From steve at pearwood.info  Thu Jul 21 03:36:05 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 21 Jul 2011 11:36:05 +1000
Subject: [Tutor] questions on encoding
In-Reply-To: <1311187759.6783.YahooMailClassic@web110704.mail.gq1.yahoo.com>
References: <1311187759.6783.YahooMailClassic@web110704.mail.gq1.yahoo.com>
Message-ID: <4E278285.80602@pearwood.info>

Albert-Jan Roskam wrote:
> Hi,
> 
> I am looking for test data with accented and multibyte characters. I have found a good resource that I could use to cobble something together (http://www.inter-locale.com/whitepaper/learn/learn-to-test.html) but I was hoping somebody knows some ready resource.
> 
> I also have some questions about encoding. In the code below, is there a difference between unicode() and .decode?

Not functionality-wise. unicode may be slightly faster, on account of 
being a function rather than a method, for small strings. But in Python 
3, unicode is gone as no longer needed.


> s = "??????"
> x = unicode(s, "utf-8")
> y = s.decode("utf-8")
> x == y # returns True

The fact that this works at all is a fluke, dependent on the settings of 
your terminal.  If I copy and paste the line

s = "??????"

into my terminal, with an arbitrarily chosen encoding, I get this:

 >>> unicode(s, 'utf-8')
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa7 in position 0: 
unexpected code byte

(I get a hint that things are not as they should, because the characters 
of s look different too.)

Without knowing what encoding your terminal is set to, it is impossible 
to tell what bytes s *actually* includes. But whatever they are, whether 
they are valid UTF-8 is a matter of chance.



> Also, is it, at least theoretically, possible to mix different encodings in byte strings? I'd say no, unless there are multiple BOMs or so. Not that I'd like to try this, but it'd improve my understanding of this sort of obscure topic.

Of course it is! That gives you a broken file, like taking a file 
containing a jpeg and appending it to a file containing an mp3. The 
resultant file is neither a well-formed mp3 nor a well-formed jpeg. 
Unless you have some way of telling where one part ends and the other 
starts, you've just broken your file.

Going back to a terminal with the default encoding (whatever that is!), 
I can do this:

 >>> s = "??????"  # copy and pasted from your email
 >>> # note the chars look different in my terminal and email client!
...
 >>> a = unicode(s, 'utf-8')  # treat it as UTF-8 bytes
 >>> b = unicode(s, 'utf-16')  # treat it as UTF-16 bytes
 >>> t = a.encode('utf-8') + b.encode('utf-16')  # mix them together
 >>> t
'\xc2\xa7\xc3\x87\xc3\x87\xc2\xbc\xc3\x8d\xc3\x8d\xff\xfe\xc2\xa7\xc3\x87\xc3\x87\xc2\xbc\xc3\x8d\xc3\x8d'
 >>> t.decode('utf-8')
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "/usr/lib/python2.5/encodings/utf_8.py", line 16, in decode
     return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 12: 
unexpected code byte
 >>> t.decode('utf-16')
u'\ua7c2\u87c3\u87c3\ubcc2\u8dc3\u8dc3\ufeff\ua7c2\u87c3\u87c3\ubcc2\u8dc3\u8dc3'

So the mixed bytes t does *not* make valid utf-8, but it happens to make 
valid utf-16. That's an accident of the particular bytes that happened 
to be in the string s. There's no guarantee that it will always work, 
but even when it does, you rarely get a sensible string of characters.

In the same way, a random chunk of bytes from an mp3 file might, by 
chance, happen to make up a valid jpeg file -- but it almost certainly 
won't make a nice picture, rather just a blob of random pixels.



-- 
Steven


From d at davea.name  Thu Jul 21 04:34:24 2011
From: d at davea.name (Dave Angel)
Date: Wed, 20 Jul 2011 22:34:24 -0400
Subject: [Tutor] little/big endian was Re: what is 'doubleword
	alignment'?
In-Reply-To: <4E25FA8C.10006@btinternet.com>
References: <CAH8GtdOw66J1ddNzichvTrckFxaaDJw6kjKpk8XQmboGFKX-cw@mail.gmail.com>	<1311189166.61425.YahooMailClassic@web110701.mail.gq1.yahoo.com>
	<4E25FA8C.10006@btinternet.com>
Message-ID: <4E279030.9000908@davea.name>

On 07/19/2011 05:43 PM, Alan Gauld wrote:
> Albert-Jan Roskam wrote:
> > and ctypes to process the data in python. It works now, although I
> > still want to read more about this. Where does the distinction
> > little/big endian enter this story?
>
> That's to do with which bit in a byte/word is most significant.
>
> e.g. is the decimal value 1 stored as
>
> 00000001   # the one on the right hand nibble
> or as
> 00010000   # the one on the left hand nibble
>
> Now scale that up to word sized numbers...
> Different CPUs do it differently.
>
> I can't recall which is which - I'm sure wikipedia will
> reveal all! :-)
Little-endian is the method used by the Intel processor (such as the 
Pentium).  Big-endian is the system used by most network protocols, as 
well as the 68000 and many other processors.

For our purposes, it's the ordering of the bytes within a 16 or 32 bit 
number.  Little-endian puts the least significant byte first, while 
big-endian puts the most significant byte first.

-- 

DaveA


From kbaclig at yahoo.com  Thu Jul 21 04:39:06 2011
From: kbaclig at yahoo.com (Ken Baclig)
Date: Wed, 20 Jul 2011 19:39:06 -0700 (PDT)
Subject: [Tutor] Homework problem
In-Reply-To: <4E277CBF.3080106@pearwood.info>
References: <1311198892.78716.YahooMailNeo@web126002.mail.ne1.yahoo.com>
	<4E277CBF.3080106@pearwood.info>
Message-ID: <1311215946.71648.YahooMailNeo@web126013.mail.ne1.yahoo.com>

The instructions are to add one to each number. ?So the expected result would be:

I got 433 when I counted, but Jim got 434 which is a lot for only 7 cats, or were there 13 cats?



________________________________
From: Steven D'Aprano <steve at pearwood.info>
To: "tutor at python.org" <tutor at python.org>
Sent: Wednesday, July 20, 2011 6:11 PM
Subject: Re: [Tutor] Homework problem

Ken Baclig wrote:
> Hi,
> 
> I'm trying to make a function that receives text (a string) as an argument and returns the same text (as string), but with 1 added to each word that is a number.


What counts as a number? In the string:

"Hello world 1234 ham spam"

which of these do you expect to get back?

"Hello world 2345 ham spam"? # Add one to each digit.
"Hello world 1235 ham spam"? # Add one to each number.

What about strings without spaces like "foo123bar"?

I'm going to assume that you mean to add 1 to any digit, not just to complete numbers.



> I need help getting started.
> 
> So far, I have:
> 
> def FindNumbers(a_string):
> 
>? ?  for index, char in enumerate(a_string):
>? ? ? ?  if char.isdigit():
> a_string[index] = 



This can't work, because strings are immutable. They cannot be changed in place. You have to form a new string.

The approach I would take is something like this. Here's a version which doesn't actually add one to each digit, but merely turns any digit into an asterisk. Your job is to make it do what it is supposed to do.


def add_one_to_digits(a_string):
? ? # Give the function a name that says what it does. It doesn't
? ? # just FindNumbers, that name is completely inappropriate.
? ? result = []? # Holder to build up a new string.
? ? for char in a_string:
? ? ? ? if char.isdigit():
? ? ? ? ? ? char = "*"
? ? ? ? # Anything else gets passed through unchanged.
? ? ? ? result.append(char)
? ? # Assemble the characters into a string.
? ? return ''.join(result)




> def Test():
>? ?  sometext = "I got 432 when I counted, but Jim got 433 which is a lot foronly 6 cats, or were there 12 cats?"
>? ?  FindNumbers(sometext)
> 
> Test()


Test functions should actually test something. Try this instead:


def test():
? ? source = ("I got 432 when I counted, but Jim got 433 which "
? ? ? ? ? ? ? "is a lot for only 6 cats, or were there 12 cats?")
? ? expected = ("I got 543 when I counted, but Jim got 544 which "
? ? ? ? ? ? ? "is a lot for only 7 cats, or were there 23 cats?")
? ? actual = add_one_to_digits(source)
? ? if actual == expected:
? ? ? ? print("Test passes!")
? ? else:
? ? ? ? print("Test fails!")
? ? ? ? print("Expected '%s'" % expected)
? ? ? ? print("but actually got '%s'" % actual)



By the way, the test case is not very good, because there is one digit which is special compared to the others, and it doesn't get tested. Think about it... out of the 10 possible digits, 9 of them are obvious: 0 -> 1
1 -> 2
2 -> 3 etc.

but one digit is not obvious. Can you see which one? So you need to include that digit in the test case, so you know it gets handled correctly.




-- Steven
_______________________________________________
Tutor maillist? -? Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110720/948d0e05/attachment.html>

From Michael at shamirlens.co.uk  Thu Jul 21 13:59:14 2011
From: Michael at shamirlens.co.uk (Michael M Mason)
Date: Thu, 21 Jul 2011 11:59:14 +0000
Subject: [Tutor] Is the Python 3.2.1 documentation available as a
	.chm	file?
In-Reply-To: <CALMxxx=aMLmSFOQv1140C_74SCC7z_BjstxAC2pX3fwD2TwUKA@mail.gmail.com>
References: <CALMxxxnzNiFMpNJ0VZLdGhBMO_eHuXX+DH_RZAJezTATEuFnXQ@mail.gmail.com>
	<201107200904.18846.thudfoo@gmail.com>
	<CALMxxx=aMLmSFOQv1140C_74SCC7z_BjstxAC2pX3fwD2TwUKA@mail.gmail.com>
Message-ID: <5378B081D0A21C45A6135E92E182BD7F2A63D04E@Mail1-Shamir.shamir.org.il>

Richard D. Moores wrote on 20 July 2011 at 18:11
> On Wed, Jul 20, 2011 at 09:04, xDog Walker <thudfoo at gmail.com> wrote:
> > On Wednesday 2011 July 20 06:41, Richard D. Moores wrote:
> > > Is the Python 3.2.1 documentation available as a .chm file from Python.org?
> >
> > http://www.python.org/ftp/python/3.2.1/python321.chm
> Did that work for you? It got me a chm file that says everywhere,
> "Navigation to the web page was cancelled".

The CHM file you downloaded is being blocked by Windows because it knows you downloaded it from the Internet and you haven't told Windows that it's safe yet.

You need to right-click the CHM file, select 'Properties', and then click the 'Unblock' button.

-- 
Michael


This mail was sent via Mail-SeCure System.



 
 
************************************************************************************
This footnote confirms that this email message has been scanned by
PineApp Mail-SeCure for the presence of malicious code, vandals & computer viruses.
************************************************************************************




From steve at pearwood.info  Thu Jul 21 14:56:45 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 21 Jul 2011 22:56:45 +1000
Subject: [Tutor] little/big endian was Re: what is
	'doubleword	alignment'?
In-Reply-To: <4E279030.9000908@davea.name>
References: <CAH8GtdOw66J1ddNzichvTrckFxaaDJw6kjKpk8XQmboGFKX-cw@mail.gmail.com>	<1311189166.61425.YahooMailClassic@web110701.mail.gq1.yahoo.com>	<4E25FA8C.10006@btinternet.com>
	<4E279030.9000908@davea.name>
Message-ID: <4E28220D.5070707@pearwood.info>

Dave Angel wrote:

> Little-endian is the method used by the Intel processor (such as the 
> Pentium).  Big-endian is the system used by most network protocols, as 
> well as the 68000 and many other processors.

There used to be mainframes with various forms of middle-endian layouts. 
Fortunately they are no longer around.

http://www.retrologic.com/jargon/M/middle-endian.html


> For our purposes, it's the ordering of the bytes within a 16 or 32 bit 
> number.  Little-endian puts the least significant byte first, while 
> big-endian puts the most significant byte first.

In this context, least significant and most significant may need explaining.

In decimal numbers, we write one hundred and twenty-three as 123. The 1 
is most significant, because it represents 1 HUNDRED rather than 1 UNIT. 
And similarly the 3 is least significant. So numbers using Arabic 
numerals are big-endian.

The same applies for computer integers. 123 written in hexadecimal is 
7B, which of course is big-endian just like decimal. But when storing 
this number in memory, we have a choice: we can store it in big-endian 
format, just like we write it: 7B, where the 7 is the "left-most" 
(lowest address) number. Or we can store it in little-endian format, B7, 
where the 7 has the higher address, and read from right-to-left.

And of course, bytes themselves can be either little-endian or 
big-endian, *independently* of byte ordering within larger units.

http://en.wikipedia.org/wiki/Endianness
http://en.wikipedia.org/wiki/Bit_numbering



-- 
Steven

From lisi.reisz at gmail.com  Thu Jul 21 16:21:00 2011
From: lisi.reisz at gmail.com (Lisi)
Date: Thu, 21 Jul 2011 15:21:00 +0100
Subject: [Tutor] little/big endian was Re: what is 'doubleword
	alignment'?
In-Reply-To: <4E25FA8C.10006@btinternet.com>
References: <CAH8GtdOw66J1ddNzichvTrckFxaaDJw6kjKpk8XQmboGFKX-cw@mail.gmail.com>
	<1311189166.61425.YahooMailClassic@web110701.mail.gq1.yahoo.com>
	<4E25FA8C.10006@btinternet.com>
Message-ID: <201107211521.01015.lisi.reisz@gmail.com>

On Tuesday 19 July 2011 22:43:40 Alan Gauld wrote:
> Growing to hate my Netbook keyboard more by the day!

Attach another keyboard?  (To keep life simple it would have to be usb, but 
you can even get a keyboard that will roll up for carrying.  I have neither 
seen nor tried one, so it may be no good!)

Lisi

From eire1130 at gmail.com  Thu Jul 21 16:40:53 2011
From: eire1130 at gmail.com (James Reynolds)
Date: Thu, 21 Jul 2011 10:40:53 -0400
Subject: [Tutor] Python editor for Ipad
Message-ID: <CAE0jAbpUO8PGbQ+X3yDWxFo8Vz6c6555O=svx0hMSeDJb65=Uw@mail.gmail.com>

I might have to discuss some routines I've written in Python (and possibly
C). It would be easier to whip out the Ipad and show them some of the things
I've done, rather than a bulky laptop.

I could of course PDF everything with highlighting off of eclipse, but
ideally Ideally I would prefer a way for the user to interact with the text,
rather than an image.

So basically, an IDE or text editor with syntax highlighting for python.

If you have any thoughts, I would greatly appreciate it!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110721/d0dd69ab/attachment.html>

From rdmoores at gmail.com  Thu Jul 21 17:48:24 2011
From: rdmoores at gmail.com (Richard D. Moores)
Date: Thu, 21 Jul 2011 08:48:24 -0700
Subject: [Tutor] Is the Python 3.2.1 documentation available as a .chm
	file?
In-Reply-To: <5378B081D0A21C45A6135E92E182BD7F2A63D04E@Mail1-Shamir.shamir.org.il>
References: <CALMxxxnzNiFMpNJ0VZLdGhBMO_eHuXX+DH_RZAJezTATEuFnXQ@mail.gmail.com>
	<201107200904.18846.thudfoo@gmail.com>
	<CALMxxx=aMLmSFOQv1140C_74SCC7z_BjstxAC2pX3fwD2TwUKA@mail.gmail.com>
	<5378B081D0A21C45A6135E92E182BD7F2A63D04E@Mail1-Shamir.shamir.org.il>
Message-ID: <CALMxxx=Pu2pLMs31nf+j+S-VL64yzhzOsOdJoFcatLxxRN342g@mail.gmail.com>

On Thu, Jul 21, 2011 at 04:59, Michael M Mason <Michael at shamirlens.co.uk> wrote:
> Richard D. Moores wrote on 20 July 2011 at 18:11
>> On Wed, Jul 20, 2011 at 09:04, xDog Walker <thudfoo at gmail.com> wrote:
>> > On Wednesday 2011 July 20 06:41, Richard D. Moores wrote:
>> > > Is the Python 3.2.1 documentation available as a .chm file from Python.org?
>> >
>> > http://www.python.org/ftp/python/3.2.1/python321.chm
>> Did that work for you? It got me a chm file that says everywhere,
>> "Navigation to the web page was cancelled".
>
> The CHM file you downloaded is being blocked by Windows because it knows you downloaded it from the Internet and you haven't told Windows that it's safe yet.
>
> You need to right-click the CHM file, select 'Properties', and then click the 'Unblock' button.

Yes! Thank you, Michael.

Dick

From simon_seys at hotmail.com  Thu Jul 21 18:24:01 2011
From: simon_seys at hotmail.com (Ryan on the Beach)
Date: Thu, 21 Jul 2011 12:24:01 -0400
Subject: [Tutor] Avoiding reauthentication to web services?
Message-ID: <BAY147-W111DC72ED873D447A3A4A9FA4F0@phx.gbl>



Hello.
I am trying to write a python program to control a  lighting controller through it's rest interface.  It requires ssl and basic authentication.  I have been successful using urllib2.  However, the authentication takes a very long time on the controller so multiple http gets are slow.  I believe this is because of the controller itself.
In a web browser after I authenticate each request is very fast, presumably because the browser is not re-authenticating again and again.    In an attempt to fix this I tried httplib2 after some googling thinking it might give me the desired result, but it does not either.  
Can anyone suggest how this would be accomplished?  I want to keep the connection "open".  At least so it does not re-authenticate over and over again, similar to how it works within a web browser.  Is this possible?
Thanks.Si. 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110721/81435e7e/attachment.html>

From kb1pkl at aim.com  Thu Jul 21 18:30:48 2011
From: kb1pkl at aim.com (Corey Richardson)
Date: Thu, 21 Jul 2011 12:30:48 -0400
Subject: [Tutor] Python editor for Ipad
In-Reply-To: <CAE0jAbpUO8PGbQ+X3yDWxFo8Vz6c6555O=svx0hMSeDJb65=Uw@mail.gmail.com>
References: <CAE0jAbpUO8PGbQ+X3yDWxFo8Vz6c6555O=svx0hMSeDJb65=Uw@mail.gmail.com>
Message-ID: <1311265193-sup-979@dalek>

Excerpts from James Reynolds's message of Thu Jul 21 10:40:53 -0400 2011:
> I might have to discuss some routines I've written in Python (and possibly
> C). It would be easier to whip out the Ipad and show them some of the things
> I've done, rather than a bulky laptop.
> 
> I could of course PDF everything with highlighting off of eclipse, but
> ideally Ideally I would prefer a way for the user to interact with the text,
> rather than an image.
> 
> So basically, an IDE or text editor with syntax highlighting for python.
> 
> If you have any thoughts, I would greatly appreciate it!

If you have a browser, Cloud9 IDE might be able to do it. Or you could use
pygments to render the text to HTML and ... do you even have filesystem
access on an ipad? (This is assuming you don't want your code out public
for the whole world to see). So your best bet would probably be Cloud9 or 
a similar product. 
-- 
Corey Richardson
  "Those who deny freedom to others, deserve it not for themselves"
     -- Abraham Lincoln
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 490 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20110721/8133f687/attachment-0001.pgp>

From fsalamero at gmail.com  Thu Jul 21 19:16:28 2011
From: fsalamero at gmail.com (Fernando Salamero)
Date: Thu, 21 Jul 2011 19:16:28 +0200
Subject: [Tutor] Editor por iPad
Message-ID: <CAD2H8ARCzR0QyWE7Xrm27-UD4dYGN4QZDiqnUFoL7v7TTJuLzw@mail.gmail.com>

For an editor, 'Textastic' have syntax highlighting. It's Great!. 'Koder' is
nice, too.
For run (basic) python scripts, try 'PythonMath' and 'PyPad'

Fernando Salamero.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110721/45ea87e8/attachment.html>

From websterhamster at felton4h.net  Thu Jul 21 19:53:45 2011
From: websterhamster at felton4h.net (Ryan Porter)
Date: Thu, 21 Jul 2011 10:53:45 -0700
Subject: [Tutor] Removing characters in a string using format()
Message-ID: <4E2867A9.6070509@felton4h.net>

Hi there,

In one part of a program I'm writing, I want a list to be printed to the 
string. Here's my code:

# Begin snippet
listString = input('Please enter a single item: >').strip();

/        print();
         itemList.append(listString);
/

/...
/

/print('And here it is in alphabetical order:', itemList)
# End Snippet
/

However, when I print the list, I get something like this: ['Python', 
'best', 'ever', 'is', 'language', 'programming', 'the'] with brackets. 
Is there a way to use format() to remove the brackets before the list is 
printed?

Thanks for the help!
//


From d at davea.name  Thu Jul 21 20:12:04 2011
From: d at davea.name (Dave Angel)
Date: Thu, 21 Jul 2011 14:12:04 -0400
Subject: [Tutor] Removing characters in a string using format()
In-Reply-To: <4E2867A9.6070509@felton4h.net>
References: <4E2867A9.6070509@felton4h.net>
Message-ID: <4E286BF4.7020906@davea.name>

On 07/21/2011 01:53 PM, Ryan Porter wrote:
> Hi there,
>
> In one part of a program I'm writing, I want a list to be printed to 
> the string. Here's my code:
>
> # Begin snippet
> listString = input('Please enter a single item: >').strip();
>
> /        print();
>         itemList.append(listString);
> /
>
> /...
> /
>
> /print('And here it is in alphabetical order:', itemList)
> # End Snippet
> /
>
> However, when I print the list, I get something like this: ['Python', 
> 'best', 'ever', 'is', 'language', 'programming', 'the'] with brackets. 
> Is there a way to use format() to remove the brackets before the list 
> is printed?
>
> Thanks for the help!
> //

itemlist isn't a string, it's presumably a list.   If you pass a list to 
string, it'll turn it into a string, using approximately the following 
rules:

Put brackets on the end, and between them call repr() on each item of 
the list, separating the items with commas.

If all you like the rest of it, but don't want the brackets, try (untested)

    print('And here it is in alphabetical order:', 
str(itemList).strip('[]'))

This explicitly converts the list to a string, then strips both ends of 
the specified characters.

DaveA



From eire1130 at gmail.com  Thu Jul 21 20:13:21 2011
From: eire1130 at gmail.com (James Reynolds)
Date: Thu, 21 Jul 2011 14:13:21 -0400
Subject: [Tutor] Removing characters in a string using format()
In-Reply-To: <4E2867A9.6070509@felton4h.net>
References: <4E2867A9.6070509@felton4h.net>
Message-ID: <CAE0jAbrxrVA0OQX8ea-c-9J-AwCkXzFvMULH-hzCijV4PaX8EA@mail.gmail.com>

Since you're using python 3, you can just use a star to unpack the list

like so:

>>> print(*x)
a b
>>> print(*x, sep = ', ')
a, b

You can use sep to change the separator if you want the commas still.


On Thu, Jul 21, 2011 at 1:53 PM, Ryan Porter <websterhamster at felton4h.net>wrote:

> Hi there,
>
> In one part of a program I'm writing, I want a list to be printed to the
> string. Here's my code:
>
> # Begin snippet
> listString = input('Please enter a single item: >').strip();
>
> /        print();
>        itemList.append(listString);
> /
>
> /...
> /
>
> /print('And here it is in alphabetical order:', itemList)
> # End Snippet
> /
>
> However, when I print the list, I get something like this: ['Python',
> 'best', 'ever', 'is', 'language', 'programming', 'the'] with brackets. Is
> there a way to use format() to remove the brackets before the list is
> printed?
>
> Thanks for the help!
> //
>
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110721/cc243948/attachment.html>

From ramit.prasad at jpmchase.com  Thu Jul 21 19:57:00 2011
From: ramit.prasad at jpmchase.com (Prasad, Ramit)
Date: Thu, 21 Jul 2011 13:57:00 -0400
Subject: [Tutor] little/big endian was Re: what is
	'doubleword	alignment'?
In-Reply-To: <201107211521.01015.lisi.reisz@gmail.com>
References: <CAH8GtdOw66J1ddNzichvTrckFxaaDJw6kjKpk8XQmboGFKX-cw@mail.gmail.com>
	<1311189166.61425.YahooMailClassic@web110701.mail.gq1.yahoo.com>
	<4E25FA8C.10006@btinternet.com>
	<201107211521.01015.lisi.reisz@gmail.com>
Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2E5F490D57@EMARC112VS01.exchad.jpmchase.net>

>Attach another keyboard?  (To keep life simple it would have to be usb, but 
>you can even get a keyboard that will roll up for carrying.  I have neither 
>seen nor tried one, so it may be no good!)

On the plus side, roll-up keyboards tend to be sealed and proof against liquids. Plus, they are usually fairly quiet. 

Ramit


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



This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase &
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.

From ramit.prasad at jpmchase.com  Thu Jul 21 20:05:07 2011
From: ramit.prasad at jpmchase.com (Prasad, Ramit)
Date: Thu, 21 Jul 2011 14:05:07 -0400
Subject: [Tutor] Removing characters in a string using format()
In-Reply-To: <4E2867A9.6070509@felton4h.net>
References: <4E2867A9.6070509@felton4h.net>
Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2E5F490D86@EMARC112VS01.exchad.jpmchase.net>

-----Original Message-----
From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of Ryan Porter
Sent: Thursday, July 21, 2011 12:54 PM
To: tutor at python.org
Subject: [Tutor] Removing characters in a string using format()

Hi there,

In one part of a program I'm writing, I want a list to be printed to the 
string. Here's my code:

# Begin snippet
listString = input('Please enter a single item: >').strip();

/        print();
         itemList.append(listString);
/

/...
/

/print('And here it is in alphabetical order:', itemList)
# End Snippet
/

However, when I print the list, I get something like this: ['Python', 
'best', 'ever', 'is', 'language', 'programming', 'the'] with brackets. 
Is there a way to use format() to remove the brackets before the list is 
printed?

Thanks for the help!
//

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

That is because you are printing a list and not a string. ['Python', 'best', 'ever', 'is', 'language', 'programming', 'the'] is a list where the first element is 'Python', the second element is 'best', and etc. To print a string instead of a list you can use a string's join function to convert a list into a string.

>>> ' '.join( itemlist )
'Python is the best programming language'
>>> ' '.join( sorted( itemlist ) )
'Python best is language programming the'


Ramit


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


This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase &
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.

From fomcl at yahoo.com  Thu Jul 21 21:46:27 2011
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Thu, 21 Jul 2011 12:46:27 -0700 (PDT)
Subject: [Tutor] little/big endian was Re: what is 'doubleword
	alignment'?
In-Reply-To: <4E28220D.5070707@pearwood.info>
Message-ID: <1311277587.3471.YahooMailClassic@web110712.mail.gq1.yahoo.com>

Thanks a lot for your explanations, that was most helpful! I never realized my mother tongue (Dutch) is Little Endian, whereas English is Big Endian, e.g.:
dutch: negen-en-twintig (nine-and-twenty)
english: twenty-nine

I will improve my program based on what you all have said. I will let the program:
-find out the encoding of the input file
-find out the encoding of the terminal
-if necessary: find out if there are any other, compatible encodings on the terminal

Thanks again!

Cheers!!

Albert-Jan



~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

--- On Thu, 7/21/11, Steven D'Aprano <steve at pearwood.info> wrote:

From: Steven D'Aprano <steve at pearwood.info>
Subject: Re: [Tutor] little/big endian was Re: what is 'doubleword alignment'?
To: tutor at python.org
Date: Thursday, July 21, 2011, 2:56 PM

Dave Angel wrote:

> Little-endian is the method used by the Intel processor (such as the Pentium).? Big-endian is the system used by most network protocols, as well as the 68000 and many other processors.

There used to be mainframes with various forms of middle-endian layouts. Fortunately they are no longer around.

http://www.retrologic.com/jargon/M/middle-endian.html


> For our purposes, it's the ordering of the bytes within a 16 or 32 bit number.? Little-endian puts the least significant byte first, while big-endian puts the most significant byte first.

In this context, least significant and most significant may need explaining.

In decimal numbers, we write one hundred and twenty-three as 123. The 1 is most significant, because it represents 1 HUNDRED rather than 1 UNIT. And similarly the 3 is least significant. So numbers using Arabic numerals are big-endian.

The same applies for computer integers. 123 written in hexadecimal is 7B, which of course is big-endian just like decimal. But when storing this number in memory, we have a choice: we can store it in big-endian format, just like we write it: 7B, where the 7 is the "left-most" (lowest address) number. Or we can store it in little-endian format, B7, where the 7 has the higher address, and read from right-to-left.

And of course, bytes themselves can be either little-endian or big-endian, *independently* of byte ordering within larger units.

http://en.wikipedia.org/wiki/Endianness
http://en.wikipedia.org/wiki/Bit_numbering



-- Steven
_______________________________________________
Tutor maillist? -? Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110721/81916932/attachment.html>

From steve at pearwood.info  Thu Jul 21 21:58:44 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 22 Jul 2011 05:58:44 +1000
Subject: [Tutor] Avoiding reauthentication to web services?
In-Reply-To: <BAY147-W111DC72ED873D447A3A4A9FA4F0@phx.gbl>
References: <BAY147-W111DC72ED873D447A3A4A9FA4F0@phx.gbl>
Message-ID: <4E2884F4.5070805@pearwood.info>

Ryan on the Beach wrote:
> 
> Hello.
> I am trying to write a python program to control a  lighting controller through it's rest interface.  It requires ssl and basic authentication.  I have been successful using urllib2.  However, the authentication takes a very long time on the controller so multiple http gets are slow.  I believe this is because of the controller itself.
> In a web browser after I authenticate each request is very fast, presumably because the browser is not re-authenticating again and again.    In an attempt to fix this I tried httplib2 after some googling thinking it might give me the desired result, but it does not either.  
> Can anyone suggest how this would be accomplished?  I want to keep the connection "open".  At least so it does not re-authenticate over and over again, similar to how it works within a web browser.  Is this possible?

My guess is that it may use cookies to stay authenticated. See the 
cookielib. What happens if you tell the browser to reject cookies?



-- 
Steven


From tahir.hafiz at gmail.com  Thu Jul 21 22:24:22 2011
From: tahir.hafiz at gmail.com (Tahir Hafiz)
Date: Thu, 21 Jul 2011 21:24:22 +0100
Subject: [Tutor] Python editor for Ipad
In-Reply-To: <1311265193-sup-979@dalek>
References: <CAE0jAbpUO8PGbQ+X3yDWxFo8Vz6c6555O=svx0hMSeDJb65=Uw@mail.gmail.com>
	<1311265193-sup-979@dalek>
Message-ID: <CALmb6fuQLHKfWEmMck5k7EDh-v8nCUqwNoTGgG3E7h9sTx8OFw@mail.gmail.com>

Cloud9 seems interesting as a browser based IDE. Do you know if there is a
way to run Python code as well create/edit it?

Thanks,
Tahir

On Thu, Jul 21, 2011 at 5:30 PM, Corey Richardson <kb1pkl at aim.com> wrote:

> Excerpts from James Reynolds's message of Thu Jul 21 10:40:53 -0400 2011:
> > I might have to discuss some routines I've written in Python (and
> possibly
> > C). It would be easier to whip out the Ipad and show them some of the
> things
> > I've done, rather than a bulky laptop.
> >
> > I could of course PDF everything with highlighting off of eclipse, but
> > ideally Ideally I would prefer a way for the user to interact with the
> text,
> > rather than an image.
> >
> > So basically, an IDE or text editor with syntax highlighting for python.
> >
> > If you have any thoughts, I would greatly appreciate it!
>
> If you have a browser, Cloud9 IDE might be able to do it. Or you could use
> pygments to render the text to HTML and ... do you even have filesystem
> access on an ipad? (This is assuming you don't want your code out public
> for the whole world to see). So your best bet would probably be Cloud9 or
> a similar product.
> --
> Corey Richardson
>  "Those who deny freedom to others, deserve it not for themselves"
>     -- Abraham Lincoln
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110721/8d419367/attachment.html>

From ian.douglas at iandouglas.com  Thu Jul 21 22:44:17 2011
From: ian.douglas at iandouglas.com (ian douglas)
Date: Thu, 21 Jul 2011 13:44:17 -0700
Subject: [Tutor] Python editor for Ipad
In-Reply-To: <CALmb6fuQLHKfWEmMck5k7EDh-v8nCUqwNoTGgG3E7h9sTx8OFw@mail.gmail.com>
References: <CAE0jAbpUO8PGbQ+X3yDWxFo8Vz6c6555O=svx0hMSeDJb65=Uw@mail.gmail.com>	<1311265193-sup-979@dalek>
	<CALmb6fuQLHKfWEmMck5k7EDh-v8nCUqwNoTGgG3E7h9sTx8OFw@mail.gmail.com>
Message-ID: <4E288FA1.4090109@iandouglas.com>

Yes, Cloud9 supports running/debugging/testing. They've also got github 
support for pulling in your projects. It's a pretty clever tool.


On 07/21/2011 01:24 PM, Tahir Hafiz wrote:
> Cloud9 seems interesting as a browser based IDE. Do you know if there 
> is a way to run Python code as well create/edit it?
>
> Thanks,
> Tahir
>
> On Thu, Jul 21, 2011 at 5:30 PM, Corey Richardson <kb1pkl at aim.com 
> <mailto:kb1pkl at aim.com>> wrote:
>
>     Excerpts from James Reynolds's message of Thu Jul 21 10:40:53
>     -0400 2011:
>     > I might have to discuss some routines I've written in Python
>     (and possibly
>     > C). It would be easier to whip out the Ipad and show them some
>     of the things
>     > I've done, rather than a bulky laptop.
>     >
>     > I could of course PDF everything with highlighting off of
>     eclipse, but
>     > ideally Ideally I would prefer a way for the user to interact
>     with the text,
>     > rather than an image.
>     >
>     > So basically, an IDE or text editor with syntax highlighting for
>     python.
>     >
>     > If you have any thoughts, I would greatly appreciate it!
>
>     If you have a browser, Cloud9 IDE might be able to do it. Or you
>     could use
>     pygments to render the text to HTML and ... do you even have
>     filesystem
>     access on an ipad? (This is assuming you don't want your code out
>     public
>     for the whole world to see). So your best bet would probably be
>     Cloud9 or
>     a similar product.
>     --
>     Corey Richardson
>      "Those who deny freedom to others, deserve it not for themselves"
>         -- Abraham Lincoln
>
>     _______________________________________________
>     Tutor maillist  - Tutor at python.org <mailto:Tutor at python.org>
>     To unsubscribe or change subscription options:
>     http://mail.python.org/mailman/listinfo/tutor
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110721/a55cac4a/attachment-0001.html>

From kb1pkl at aim.com  Thu Jul 21 22:40:02 2011
From: kb1pkl at aim.com (Corey Richardson)
Date: Thu, 21 Jul 2011 16:40:02 -0400
Subject: [Tutor] Python editor for Ipad
In-Reply-To: <CALmb6fuQLHKfWEmMck5k7EDh-v8nCUqwNoTGgG3E7h9sTx8OFw@mail.gmail.com>
References: <CAE0jAbpUO8PGbQ+X3yDWxFo8Vz6c6555O=svx0hMSeDJb65=Uw@mail.gmail.com>
	<1311265193-sup-979@dalek>
	<CALmb6fuQLHKfWEmMck5k7EDh-v8nCUqwNoTGgG3E7h9sTx8OFw@mail.gmail.com>
Message-ID: <1311280446-sup-2136@dalek>

Excerpts from Tahir Hafiz's message of Thu Jul 21 16:24:22 -0400 2011:
> Cloud9 seems interesting as a browser based IDE. Do you know if there is a
> way to run Python code as well create/edit it?
> 

Not as far as I know.
-- 
Corey Richardson
  "Those who deny freedom to others, deserve it not for themselves"
     -- Abraham Lincoln
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 490 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20110721/773e1fde/attachment.pgp>

From kb1pkl at aim.com  Thu Jul 21 22:46:31 2011
From: kb1pkl at aim.com (Corey Richardson)
Date: Thu, 21 Jul 2011 16:46:31 -0400
Subject: [Tutor] Python editor for Ipad
In-Reply-To: <4E288FA1.4090109@iandouglas.com>
References: <CAE0jAbpUO8PGbQ+X3yDWxFo8Vz6c6555O=svx0hMSeDJb65=Uw@mail.gmail.com>
	<1311265193-sup-979@dalek>
	<CALmb6fuQLHKfWEmMck5k7EDh-v8nCUqwNoTGgG3E7h9sTx8OFw@mail.gmail.com>
	<4E288FA1.4090109@iandouglas.com>
Message-ID: <1311281129-sup-5971@dalek>

Excerpts from ian douglas's message of Thu Jul 21 16:44:17 -0400 2011:
> Yes, Cloud9 supports running/debugging/testing. They've also got github 
> support for pulling in your projects. It's a pretty clever tool.
> 

Could you share your secret? I didn't dig enough to figure it out. I saw the
"Run" button and its configuration, but it looks like it wants a JS file and
args? Or...maybe not?
-- 
Corey Richardson
  "Those who deny freedom to others, deserve it not for themselves"
     -- Abraham Lincoln
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 490 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20110721/c90164be/attachment.pgp>

From ryan.strunk at gmail.com  Thu Jul 21 22:48:45 2011
From: ryan.strunk at gmail.com (Ryan Strunk)
Date: Thu, 21 Jul 2011 15:48:45 -0500
Subject: [Tutor] (no subject)
Message-ID: <CADQNYGsS2ELu0v8KeBGWXhx8BEn7SYQ_NfCyMSDPQKfLegTOGg@mail.gmail.com>



From ryan.strunk at gmail.com  Thu Jul 21 22:49:19 2011
From: ryan.strunk at gmail.com (Ryan Strunk)
Date: Thu, 21 Jul 2011 15:49:19 -0500
Subject: [Tutor] Viability of Python
Message-ID: <CADQNYGv6J8+9OS0QynMHSXs16txqpB=WS5yiNcA9mZeceW5+bw@mail.gmail.com>

Hello everyone,
I have been reading a lot of different articles recently, and I have
found a divergence of opinions on the viability of Python as a viable
language for high-end programs. At the same time, even sites that
recommend Python seem to recommend it as a good first language.
This email is not written to stir up controversy. I am a fan of Python
myself and use it for all of my programming. But therein lies the crux
of my question. If Python has limitations, what are they? What sorts
of things is Python useful for and what things is it not? And finally,
if there is code after Python, what?s a good second language, and when
should someone start learning it?
Thanks for any help you can give.
Best,
Ryan

From ian.douglas at iandouglas.com  Thu Jul 21 23:09:22 2011
From: ian.douglas at iandouglas.com (ian douglas)
Date: Thu, 21 Jul 2011 14:09:22 -0700
Subject: [Tutor] Python editor for Ipad
In-Reply-To: <1311281129-sup-5971@dalek>
References: <CAE0jAbpUO8PGbQ+X3yDWxFo8Vz6c6555O=svx0hMSeDJb65=Uw@mail.gmail.com>	<1311265193-sup-979@dalek>	<CALmb6fuQLHKfWEmMck5k7EDh-v8nCUqwNoTGgG3E7h9sTx8OFw@mail.gmail.com>	<4E288FA1.4090109@iandouglas.com>
	<1311281129-sup-5971@dalek>
Message-ID: <4E289582.4060504@iandouglas.com>

On 07/21/2011 01:46 PM, Corey Richardson wrote:
> Excerpts from ian douglas's message of Thu Jul 21 16:44:17 -0400 2011:
>> Yes, Cloud9 supports running/debugging/testing. They've also got github
>> support for pulling in your projects. It's a pretty clever tool.
>>
> Could you share your secret? I didn't dig enough to figure it out. I saw the
> "Run" button and its configuration, but it looks like it wants a JS file and
> args? Or...maybe not?

Ah, my bad. Creating files should be allowed, but running *Python* files 
seems to still be on their TODO list as of March 23rd. Sorry for the 
misinformation.

As soon as they Email me a password recovery message, (I signed up in 
May at Google IO), I can get more information to the list.

-id


From eire1130 at gmail.com  Thu Jul 21 23:12:52 2011
From: eire1130 at gmail.com (James Reynolds)
Date: Thu, 21 Jul 2011 17:12:52 -0400
Subject: [Tutor] Python editor for Ipad
In-Reply-To: <4E289582.4060504@iandouglas.com>
References: <CAE0jAbpUO8PGbQ+X3yDWxFo8Vz6c6555O=svx0hMSeDJb65=Uw@mail.gmail.com>
	<1311265193-sup-979@dalek>
	<CALmb6fuQLHKfWEmMck5k7EDh-v8nCUqwNoTGgG3E7h9sTx8OFw@mail.gmail.com>
	<4E288FA1.4090109@iandouglas.com> <1311281129-sup-5971@dalek>
	<4E289582.4060504@iandouglas.com>
Message-ID: <CAE0jAbqfj0f83PUxtGqV9eyE=uRLbpqtucXyjuwoqUU22n-PJA@mail.gmail.com>

Thanks for the input.

I received another email off list and I think i'm going to look into "
Textastic".

The Cloud9 seems interesting, but I'm not assured to have internet access
all the time (even if I do live in NYC).

Thanks for all the replies!


On Thu, Jul 21, 2011 at 5:09 PM, ian douglas <ian.douglas at iandouglas.com>wrote:

> On 07/21/2011 01:46 PM, Corey Richardson wrote:
>
>> Excerpts from ian douglas's message of Thu Jul 21 16:44:17 -0400 2011:
>>
>>> Yes, Cloud9 supports running/debugging/testing. They've also got github
>>> support for pulling in your projects. It's a pretty clever tool.
>>>
>>>  Could you share your secret? I didn't dig enough to figure it out. I saw
>> the
>> "Run" button and its configuration, but it looks like it wants a JS file
>> and
>> args? Or...maybe not?
>>
>
> Ah, my bad. Creating files should be allowed, but running *Python* files
> seems to still be on their TODO list as of March 23rd. Sorry for the
> misinformation.
>
> As soon as they Email me a password recovery message, (I signed up in May
> at Google IO), I can get more information to the list.
>
> -id
>
>
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110721/b4f15ad2/attachment.html>

From merrickdav at gmail.com  Thu Jul 21 23:16:16 2011
From: merrickdav at gmail.com (David Merrick)
Date: Fri, 22 Jul 2011 09:16:16 +1200
Subject: [Tutor] Stack problem usind Python2.6
Message-ID: <CA+=McKa-xHDJin+X146+yqbuhoN+1UiJz-u2jcU9J68qaHMikg@mail.gmail.com>

##from stack import Stack

class Stack:
    def __init__(self):
        self.items =[]

    def isEmpty(self):
        return self.items ==[]

    def push(self,item):
        self.items.append(item)

    def pop(self,item):
        self.items.pop()

    def peek(self):
        return  self.items[len(self.items)-1]

    def size(self):
        return len(self.items)

def parChecker(symbolString):
    s = Stack()

    balanced = True
    index = 0
    while index < len(symbolString) and balanced:
        symbol = symbolString[index]
        if symbol in "([{":
            s.push(symbol)
        else:
            if s.isEmpty():
                balanced = False
            else:
                top = s.pop()
                if not matches(top,symbol):
                    balanced = False
        index+=1
        if balanced and  s.isEmpty():
            return True
        else:
            return False

def matches(open,close):
    opens = "([{"
    closers = ")]}"

    opens.index(open) == closers.index(close)

symbolString = "()"
print(parChecker(symbolString))

*Output*

() returns False should be true
(() returns False which is correct

I can't find the error please help me

-- 
Dave Merrick

merrickdav at gmail.com

Ph   03 3423 121
Cell 027 3089 169
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110722/c6a55a68/attachment-0001.html>

From bgailer at gmail.com  Thu Jul 21 23:21:01 2011
From: bgailer at gmail.com (bob gailer)
Date: Thu, 21 Jul 2011 17:21:01 -0400
Subject: [Tutor] Python editor for Ipad
In-Reply-To: <1311265193-sup-979@dalek>
References: <CAE0jAbpUO8PGbQ+X3yDWxFo8Vz6c6555O=svx0hMSeDJb65=Uw@mail.gmail.com>
	<1311265193-sup-979@dalek>
Message-ID: <4E28983D.7050402@gmail.com>

On 7/21/2011 12:30 PM, Corey Richardson wrote:
> If you have a browser, Cloud9 IDE might be able to do it.
I just tried Cloud9 and gave up in frustration.

Unintuitive interfacre. No help. Finally edited a program. Tried to run 
it. No results. Sigh.

Also appears to be a free TRIAL only.

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


From bgailer at gmail.com  Thu Jul 21 23:33:40 2011
From: bgailer at gmail.com (bob gailer)
Date: Thu, 21 Jul 2011 17:33:40 -0400
Subject: [Tutor] Stack problem usind Python2.6
In-Reply-To: <CA+=McKa-xHDJin+X146+yqbuhoN+1UiJz-u2jcU9J68qaHMikg@mail.gmail.com>
References: <CA+=McKa-xHDJin+X146+yqbuhoN+1UiJz-u2jcU9J68qaHMikg@mail.gmail.com>
Message-ID: <4E289B34.2090909@gmail.com>

On 7/21/2011 5:16 PM, David Merrick wrote:
> ##from stack import Stack
>
> class Stack:
>     def __init__(self):
>         self.items =[]
>
>     def isEmpty(self):
>         return self.items ==[]
>
>     def push(self,item):
>         self.items.append(item)
>
>     def pop(self,item):
>         self.items.pop()
>
>     def peek(self):
>         return  self.items[len(self.items)-1]
>
>     def size(self):
>         return len(self.items)
>
> def parChecker(symbolString):
>     s = Stack()
>
>     balanced = True
>     index = 0
>     while index < len(symbolString) and balanced:
>         symbol = symbolString[index]
>         if symbol in "([{":
>             s.push(symbol)
>         else:
>             if s.isEmpty():
>                 balanced = False
>             else:
>                 top = s.pop()
>                 if not matches(top,symbol):
>                     balanced = False
>         index+=1
>         if balanced and  s.isEmpty():
>             return True
>         else:
>             return False
>
> def matches(open,close):
>     opens = "([{"
>     closers = ")]}"
>
>     opens.index(open) == closers.index(close)
>
> symbolString = "()"
> print(parChecker(symbolString))
>
> _*Output*_
>
> () returns False should be true
> (() returns False which is correct
>
> I can't find the error please help me

What do you tkink matches returns, and why?

Therein is the problem.

Also FWIW you import Stack them redefine it. Why?


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

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110721/fd42f7dc/attachment.html>

From eire1130 at gmail.com  Thu Jul 21 23:52:42 2011
From: eire1130 at gmail.com (James Reynolds)
Date: Thu, 21 Jul 2011 17:52:42 -0400
Subject: [Tutor] Stack problem usind Python2.6
In-Reply-To: <CA+=McKa-xHDJin+X146+yqbuhoN+1UiJz-u2jcU9J68qaHMikg@mail.gmail.com>
References: <CA+=McKa-xHDJin+X146+yqbuhoN+1UiJz-u2jcU9J68qaHMikg@mail.gmail.com>
Message-ID: <CAE0jAbo+WBr4g6kEtWx+E5M5B4G2LH2wj=HNyg3VxGk-C6Syyg@mail.gmail.com>

On Thu, Jul 21, 2011 at 5:16 PM, David Merrick <merrickdav at gmail.com> wrote:

> ##from stack import Stack
>
> class Stack:
>     def __init__(self):
>         self.items =[]
>
>     def isEmpty(self):
>         return self.items ==[]
>
>     def push(self,item):
>         self.items.append(item)
>
>     def pop(self,item):
>         self.items.pop()
>
>     def peek(self):
>         return  self.items[len(self.items)-1]
>
>     def size(self):
>         return len(self.items)
>
> def parChecker(symbolString):
>     s = Stack()
>
>     balanced = True
>     index = 0
>     while index < len(symbolString) and balanced:
>         symbol = symbolString[index]
>         if symbol in "([{":
>             s.push(symbol)
>         else:
>             if s.isEmpty():
>                 balanced = False
>             else:
>                 top = s.pop()
>                 if not matches(top,symbol):
>                     balanced = False
>         index+=1
>         if balanced and  s.isEmpty():
>             return True
>         else:
>             return False
>
> def matches(open,close):
>     opens = "([{"
>     closers = ")]}"
>
>     opens.index(open) == closers.index(close)
>
> symbolString = "()"
> print(parChecker(symbolString))
>
> *Output*
>
> () returns False should be true
> (() returns False which is correct
>
> I can't find the error please help me
>
> --
> Dave Merrick
>
> merrickdav at gmail.com
>
> Ph   03 3423 121
> Cell 027 3089 169
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
























The class stack seems to basically be a list. Why not just use a list (which
is already an object) to do the things that you want it to do? All of the
methods of the class are already methods of a list, so it seems like your
creating code that is already in python (unless there is more to it than I'm
missing)


In your ParChecker function, instead of setting a variable to false, why not
add a "break" statement? This will allow you to do things like "if
s.isEmpty():" instead of "if balanced and  s.isEmpty():"



Basically, what's going on here,

        if balanced and  s.isEmpty():
            return True
        else:
            return False

so long as this s.isEmpty() evaluates to false (which it is in the first few
loops) you will get the "else" part, which is "return false".

If you throw in some print statements, like dummy prints (print index, or
print "a" or whatever) you will see how many loops it's making.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110721/98fb3f61/attachment.html>

From kb1pkl at aim.com  Fri Jul 22 00:03:30 2011
From: kb1pkl at aim.com (Corey Richardson)
Date: Thu, 21 Jul 2011 18:03:30 -0400
Subject: [Tutor] Python editor for Ipad
In-Reply-To: <4E28983D.7050402@gmail.com>
References: <CAE0jAbpUO8PGbQ+X3yDWxFo8Vz6c6555O=svx0hMSeDJb65=Uw@mail.gmail.com>
	<1311265193-sup-979@dalek> <4E28983D.7050402@gmail.com>
Message-ID: <1311284776-sup-2585@dalek>

Excerpts from bob gailer's message of Thu Jul 21 17:21:01 -0400 2011:
> On 7/21/2011 12:30 PM, Corey Richardson wrote:
> > If you have a browser, Cloud9 IDE might be able to do it.
> I just tried Cloud9 and gave up in frustration.
> 
> Unintuitive interfacre. No help. Finally edited a program. Tried to run 
> it. No results. Sigh.
> 
> Also appears to be a free TRIAL only.
> 

It says "Free for open source" on the homepage. I agree that the interface
is not intuitive. You cannot run any programs, to my knowledge, but I don't
hold that against them (I don't want my browser to become an operating 
environment/system, any more than I want my emacs to be one). It's certainly
not enough to replace my own setup but maybe someone likes this sort of
thing. It's also in Beta, I'd be willing to be that more stuff will happen
to it.
-- 
Corey Richardson
  "Those who deny freedom to others, deserve it not for themselves"
     -- Abraham Lincoln
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 490 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20110721/47fbc0c5/attachment-0001.pgp>

From eire1130 at gmail.com  Fri Jul 22 00:04:30 2011
From: eire1130 at gmail.com (James Reynolds)
Date: Thu, 21 Jul 2011 18:04:30 -0400
Subject: [Tutor] Stack problem usind Python2.6
In-Reply-To: <CA+=McKa-xHDJin+X146+yqbuhoN+1UiJz-u2jcU9J68qaHMikg@mail.gmail.com>
References: <CA+=McKa-xHDJin+X146+yqbuhoN+1UiJz-u2jcU9J68qaHMikg@mail.gmail.com>
Message-ID: <CAE0jAbqewuYK7sC30bA+zXvb2ZB-pM9kBQ7dQFOHK8TiXPiwTw@mail.gmail.com>

On Thu, Jul 21, 2011 at 5:16 PM, David Merrick <merrickdav at gmail.com> wrote:

> ##from stack import Stack
>
> class Stack:
>     def __init__(self):
>         self.items =[]
>
>     def isEmpty(self):
>         return self.items ==[]
>
>     def push(self,item):
>         self.items.append(item)
>
>     def pop(self,item):
>         self.items.pop()
>
>     def peek(self):
>         return  self.items[len(self.items)-1]
>
>     def size(self):
>         return len(self.items)
>
> def parChecker(symbolString):
>     s = Stack()
>
>     balanced = True
>     index = 0
>     while index < len(symbolString) and balanced:
>         symbol = symbolString[index]
>         if symbol in "([{":
>             s.push(symbol)
>         else:
>             if s.isEmpty():
>                 balanced = False
>             else:
>                 top = s.pop()
>                 if not matches(top,symbol):
>                     balanced = False
>         index+=1
>         if balanced and  s.isEmpty():
>             return True
>         else:
>             return False
>
> def matches(open,close):
>     opens = "([{"
>     closers = ")]}"
>
>     opens.index(open) == closers.index(close)
>
> symbolString = "()"
> print(parChecker(symbolString))
>
> *Output*
>
> () returns False should be true
> (() returns False which is correct
>
> I can't find the error please help me
>
> --
> Dave Merrick
>
> merrickdav at gmail.com
>
> Ph   03 3423 121
> Cell 027 3089 169
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>




A couple more points:

* I did just run it with the break statements where you have 'balanced =
False'
* the method Stack needs a return statement (otherwise, it will return
None), as all functions without a return statement do.
* you should either get rid of the argument for pop in Stack or make it an
optional argument (item = None) if you intended to do something with item.
* You of course need to tab in this block if you decide to go the 'break'
route:

    if s.isEmpty():
        return True
    else:
        return False
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110721/4bb11230/attachment.html>

From ranceh at gmail.com  Fri Jul 22 00:17:22 2011
From: ranceh at gmail.com (Rance Hall)
Date: Thu, 21 Jul 2011 17:17:22 -0500
Subject: [Tutor] OT: Drag and Drop GUI IDE ideas
Message-ID: <CANWBxgaPVmgyjWGCtcFHuHCa0Gx_g-yD-wHmh5zzWde1xYBT3w@mail.gmail.com>

I know this is OT and I am sorry, but the readers of the list are some
of the best to judge my problem.  And it is about learning to code,
just not python specifically.


The MIS department at UNK is looking to create a course in business
app development.

The course will be about the app life cycle and discuss problem
statement, testing, maintenance and disposal/decommissioning, etc.

We want the students to develop a small app in the process, It could
be a firefox extension, mobile phone app, or any other type simple
structure.

The catch is that the class is for non-programmers to try to get them
introduced to the field.  We would like to use a gui ide that can
essentially hide the code from the programmer and connect widgets with
the gui.

We want them to be able to look at the code and analyze it.

We would prefer open source (read: free as in beer) tools.

Does anyone have any ideas of tools that can do this?

we are open to any idea, android sdk and gui, ipad sdk and some gui tool, etc.

Thanks for your time.

Rance

From emile at fenx.com  Fri Jul 22 00:18:55 2011
From: emile at fenx.com (Emile van Sebille)
Date: Thu, 21 Jul 2011 15:18:55 -0700
Subject: [Tutor] Viability of Python
In-Reply-To: <CADQNYGv6J8+9OS0QynMHSXs16txqpB=WS5yiNcA9mZeceW5+bw@mail.gmail.com>
References: <CADQNYGv6J8+9OS0QynMHSXs16txqpB=WS5yiNcA9mZeceW5+bw@mail.gmail.com>
Message-ID: <j0a8ki$ojr$1@dough.gmane.org>

On 7/21/2011 1:49 PM Ryan Strunk said...
> Hello everyone,
> I have been reading a lot of different articles recently, and I have
> found a divergence of opinions on the viability of Python as a viable
> language for high-end programs. At the same time, even sites that
> recommend Python seem to recommend it as a good first language.
> This email is not written to stir up controversy. I am a fan of Python
> myself and use it for all of my programming. But therein lies the crux
> of my question. If Python has limitations, what are they?

Programming is a big field.  If so far you've used python for all your 
programming, then it's good enough for you so far.  If you need real 
time responsiveness, want to write OSs or device drivers, or inherit a 
legacy environment it's probably not the right tool.  But everyone who 
programs will have a different take on this.  I use it unless there's a 
better answer I can deploy quicker.

> What sorts
> of things is Python useful for and what things is it not? And finally,
> if there is code after Python, what?s a good second language, and when
> should someone start learning it?

I'd say C, and I'd start by browsing the python code base.


Emile


From d.e.h.schouten at gmail.com  Fri Jul 22 00:36:42 2011
From: d.e.h.schouten at gmail.com (David Schouten)
Date: Fri, 22 Jul 2011 00:36:42 +0200
Subject: [Tutor] Viability of Python
In-Reply-To: <j0a8ki$ojr$1@dough.gmane.org>
References: <CADQNYGv6J8+9OS0QynMHSXs16txqpB=WS5yiNcA9mZeceW5+bw@mail.gmail.com>
	<j0a8ki$ojr$1@dough.gmane.org>
Message-ID: <E2B32C1A-8D8A-45A1-A037-F5F70673D6DF@gmail.com>


Op 22 jul. 2011 om 00:18 heeft Emile van Sebille <emile at fenx.com> het volgende geschreven:

> On 7/21/2011 1:49 PM Ryan Strunk said...
>> Hello everyone,
>> I have been reading a lot of different articles recently, and I have
>> found a divergence of opinions on the viability of Python as a viable
>> language for high-end programs. At the same time, even sites that
>> recommend Python seem to recommend it as a good first language.
>> This email is not written to stir up controversy. I am a fan of Python
>> myself and use it for all of my programming. But therein lies the crux
>> of my question. If Python has limitations, what are they?
> 
> Programming is a big field.  If so far you've used python for all your programming, then it's good enough for you so far.  If you need real time responsiveness, want to write OSs or device drivers, or inherit a legacy environment it's probably not the right tool.  But everyone who programs will have a different take on this.  I use it unless there's a better answer I can deploy quicker.
> 
>> What sorts
>> of things is Python useful for and what things is it not? And finally,
>> if there is code after Python, what?s a good second language, and when
>> should someone start learning it?
> 
> I'd say C, and I'd start by browsing the python code base.
> 
> 
> Emile
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

How would one acces the code base? Some time ago, someone responded to a question on this list by reccomending to study the built-in modules, where are those stored?

I'm using Mac OS X 10.7 with python 3, in case this is relevant. 

David Schouten. 

From ramit.prasad at jpmchase.com  Fri Jul 22 00:46:59 2011
From: ramit.prasad at jpmchase.com (Prasad, Ramit)
Date: Thu, 21 Jul 2011 18:46:59 -0400
Subject: [Tutor] Viability of Python
In-Reply-To: <E2B32C1A-8D8A-45A1-A037-F5F70673D6DF@gmail.com>
References: <CADQNYGv6J8+9OS0QynMHSXs16txqpB=WS5yiNcA9mZeceW5+bw@mail.gmail.com>
	<j0a8ki$ojr$1@dough.gmane.org>
	<E2B32C1A-8D8A-45A1-A037-F5F70673D6DF@gmail.com>
Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2E5F565CA9@EMARC112VS01.exchad.jpmchase.net>

>How would one acces the code base? Some time ago, someone responded to a question on this list by reccomending to study the built-in modules, where are those stored?
>I'm using Mac OS X 10.7 with python 3, in case this is relevant. 

General documentation is located http://docs.python.org/py3k/ , but I think you want http://docs.python.org/py3k/library/index.html . The full list of modules is located http://docs.python.org/py3k/py-modindex.html .  


Ramit


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


This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase &
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.

From eire1130 at gmail.com  Fri Jul 22 01:00:47 2011
From: eire1130 at gmail.com (James Reynolds)
Date: Thu, 21 Jul 2011 19:00:47 -0400
Subject: [Tutor] Viability of Python
In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2E5F565CA9@EMARC112VS01.exchad.jpmchase.net>
References: <CADQNYGv6J8+9OS0QynMHSXs16txqpB=WS5yiNcA9mZeceW5+bw@mail.gmail.com>
	<j0a8ki$ojr$1@dough.gmane.org>
	<E2B32C1A-8D8A-45A1-A037-F5F70673D6DF@gmail.com>
	<0604E20B5F6F2F4784C9C8C71C5DD4DD2E5F565CA9@EMARC112VS01.exchad.jpmchase.net>
Message-ID: <CAE0jAbqJBCsd4UDsbgfLRN3jUSb9bEU0Q3M=VwC-7GDfxGKYeA@mail.gmail.com>

Source files for the 3.2 branch are located here:

http://hg.python.org/cpython/file/f0475f78d45c

the modules and objects directory has a lot of c files. there some
elsewhere. In modules theres some that start with XX. those are
demonstration i believe.

On Thu, Jul 21, 2011 at 6:46 PM, Prasad, Ramit <ramit.prasad at jpmchase.com>wrote:

> >How would one acces the code base? Some time ago, someone responded to a
> question on this list by reccomending to study the built-in modules, where
> are those stored?
> >I'm using Mac OS X 10.7 with python 3, in case this is relevant.
>
> General documentation is located http://docs.python.org/py3k/ , but I
> think you want http://docs.python.org/py3k/library/index.html . The full
> list of modules is located http://docs.python.org/py3k/py-modindex.html .
>
>
> Ramit
>
>
> Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
> 712 Main Street | Houston, TX 77002
> work phone: 713 - 216 - 5423
>
>
> This communication is for informational purposes only. It is not
> intended as an offer or solicitation for the purchase or sale of
> any financial instrument or as an official confirmation of any
> transaction. All market prices, data and other information are not
> warranted as to completeness or accuracy and are subject to change
> without notice. Any comments or statements made herein do not
> necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
> and affiliates.
>
> This transmission may contain information that is privileged,
> confidential, legally privileged, and/or exempt from disclosure
> under applicable law. If you are not the intended recipient, you
> are hereby notified that any disclosure, copying, distribution, or
> use of the information contained herein (including any reliance
> thereon) is STRICTLY PROHIBITED. Although this transmission and any
> attachments are believed to be free of any virus or other defect
> that might affect any computer system into which it is received and
> opened, it is the responsibility of the recipient to ensure that it
> is virus free and no responsibility is accepted by JPMorgan Chase &
> Co., its subsidiaries and affiliates, as applicable, for any loss
> or damage arising in any way from its use. If you received this
> transmission in error, please immediately contact the sender and
> destroy the material in its entirety, whether in electronic or hard
> copy format. Thank you.
>
> Please refer to http://www.jpmorgan.com/pages/disclosures for
> disclosures relating to European legal entities.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110721/03a7549a/attachment.html>

From websterhamster at felton4h.net  Fri Jul 22 01:10:37 2011
From: websterhamster at felton4h.net (Ryan Porter)
Date: Thu, 21 Jul 2011 16:10:37 -0700
Subject: [Tutor] Removing characters in a string using format()
In-Reply-To: <CAE0jAbrxrVA0OQX8ea-c-9J-AwCkXzFvMULH-hzCijV4PaX8EA@mail.gmail.com>
References: <4E2867A9.6070509@felton4h.net>
	<CAE0jAbrxrVA0OQX8ea-c-9J-AwCkXzFvMULH-hzCijV4PaX8EA@mail.gmail.com>
Message-ID: <4E28B1ED.80202@felton4h.net>

Thanks for help, James! It works perfectly.

Ryan

On 7/21/2011 11:13 AM, James Reynolds wrote:
> Since you're using python 3, you can just use a star to unpack the list
>
> like so:
>
> >>> print(*x)
> a b
> >>> print(*x, sep = ', ')
> a, b
>
> You can use sep to change the separator if you want the commas still.
>
>
> On Thu, Jul 21, 2011 at 1:53 PM, Ryan Porter 
> <websterhamster at felton4h.net <mailto:websterhamster at felton4h.net>> wrote:
>
>     Hi there,
>
>     In one part of a program I'm writing, I want a list to be printed
>     to the string. Here's my code:
>
>     # Begin snippet
>     listString = input('Please enter a single item: >').strip();
>
>     /        print();
>            itemList.append(listString);
>     /
>
>     /...
>     /
>
>     /print('And here it is in alphabetical order:', itemList)
>     # End Snippet
>     /
>
>     However, when I print the list, I get something like this:
>     ['Python', 'best', 'ever', 'is', 'language', 'programming', 'the']
>     with brackets. Is there a way to use format() to remove the
>     brackets before the list is printed?
>
>     Thanks for the help!
>     //
>
>     _______________________________________________
>     Tutor maillist  - Tutor at python.org <mailto:Tutor at python.org>
>     To unsubscribe or change subscription options:
>     http://mail.python.org/mailman/listinfo/tutor
>
>


-- 

Ryan Porter Web Design & Piano Lessons

/"For my soul delighteth in the song of the heart; yea, the song of the 
righteous is a prayer unto me, and it shall be answered with a blessing 
upon their heads." ~D&C 25:12/

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110721/d16bc4e7/attachment.html>

From waynejwerner at gmail.com  Fri Jul 22 01:13:59 2011
From: waynejwerner at gmail.com (Wayne Werner)
Date: Thu, 21 Jul 2011 18:13:59 -0500
Subject: [Tutor] little/big endian was Re: what is 'doubleword
	alignment'?
In-Reply-To: <201107211521.01015.lisi.reisz@gmail.com>
References: <CAH8GtdOw66J1ddNzichvTrckFxaaDJw6kjKpk8XQmboGFKX-cw@mail.gmail.com>
	<1311189166.61425.YahooMailClassic@web110701.mail.gq1.yahoo.com>
	<4E25FA8C.10006@btinternet.com>
	<201107211521.01015.lisi.reisz@gmail.com>
Message-ID: <CAPM86NeEjxAxm1FOs+hqSVzeNEWBK3fikGEQszWqRrV8M0iw6g@mail.gmail.com>

On Jul 21, 2011 9:23 AM, "Lisi" <lisi.reisz at gmail.com> wrote:
>
> On Tuesday 19 July 2011 22:43:40 Alan Gauld wrote:
> > Growing to hate my Netbook keyboard more by the day!
>
> Attach another keyboard?  (To keep life simple it would have to be usb,
but
> you can even get a keyboard that will roll up for carrying.  I have
neither
> seen nor tried one, so it may be no good!)
>
> Lisi

Having used and owning the roll up kind, they're not very good. It's very
similar to typing on a bad keyboard with the keys off. I bought a smaller
keyboard for $10 on amazon that had full size keys and was quite nice, until
the stress of sticking it in my backpack shorted the cord. That's what I'd
recommend if you still want something portable, though it's easily the size
of my wife's netbook.

If you want a good keyboard, I'm addicted to mechanical switched keyboards,
despite the price tag.

-Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110721/023813d4/attachment.html>

From garry.bettle at gmail.com  Fri Jul 22 20:18:13 2011
From: garry.bettle at gmail.com (Garry Bettle)
Date: Fri, 22 Jul 2011 19:18:13 +0100
Subject: [Tutor] Question regarding xml.dom.minidom: How do you send an
 unsignedByte in an wsdl request
Message-ID: <CAPUo4G5ZOq3y5fG9mMXhyq+q9wznczSo82Z4Q1yXw5mN+EGmCQ@mail.gmail.com>

Howdy all,

Hope this message finds everyone well - roll on the weekend!

I'm trying some calls to an wsdl API I've subscribed to.

But I'm struggling to know what they want when sending an unsignedByte in a
request.

I'm using xml.dom.minidom so to start with I have:
from xml.dom.minidom import Document, parseString
import httplib, urlparse

And later on I create a doc with:
doc=Document()

And I have a using a little helper to add a text element:
def add_text_element(doc, parent, name, value):
    element=doc.createElement(name)
    element.appendChild(doc.createTextNode(str(value)))
    parent.appendChild(element)

Should I have a separate class for an unsignedByte? i.e. def
add_byte_element

What should it look like?

This is what their API helpdesk have said:

"In this instance, the PriceFormat is defined as an unsignedByte.



     *<xs:complexType name="GetOddsLadderRequest">*

*<xs:attribute name="PriceFormat" type="xs:unsignedByte" /> *

*</xs:complexType>*"

Many thanks!

Cheers,

Garry
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110722/4689fcea/attachment.html>

From emile at fenx.com  Fri Jul 22 20:59:59 2011
From: emile at fenx.com (Emile van Sebille)
Date: Fri, 22 Jul 2011 11:59:59 -0700
Subject: [Tutor] Question regarding xml.dom.minidom: How do you send an
 unsignedByte in an wsdl request
In-Reply-To: <CAPUo4G5ZOq3y5fG9mMXhyq+q9wznczSo82Z4Q1yXw5mN+EGmCQ@mail.gmail.com>
References: <CAPUo4G5ZOq3y5fG9mMXhyq+q9wznczSo82Z4Q1yXw5mN+EGmCQ@mail.gmail.com>
Message-ID: <j0chbd$ac5$1@dough.gmane.org>


You'll likely get more traction on this at 
http://mail.python.org/mailman/listinfo/xml-sig

Emile


On 7/22/2011 11:18 AM Garry Bettle said...
> Howdy all,
>
> Hope this message finds everyone well - roll on the weekend!
>
> I'm trying some calls to an wsdl API I've subscribed to.
>
> But I'm struggling to know what they want when sending an unsignedByte
> in a request.
>
> I'm using xml.dom.minidom so to start with I have:
> from xml.dom.minidom import Document, parseString
> import httplib, urlparse
>
> And later on I create a doc with:
> doc=Document()
>
> And I have a using a little helper to add a text element:
> def add_text_element(doc, parent, name, value):
>      element=doc.createElement(name)
>      element.appendChild(doc.createTextNode(str(value)))
>      parent.appendChild(element)
>
> Should I have a separate class for an unsignedByte? i.e. def
> add_byte_element
>
> What should it look like?
>
> This is what their API helpdesk have said:
>
> "In this instance, the PriceFormat is defined as an unsignedByte.
>
> /<xs:complexType name="GetOddsLadderRequest">/
>
> /<xs:attribute name="PriceFormat" type="xs:*unsignedByte*" /> /
>
> /</xs:complexType>/"
>
>
> Many thanks!
>
> Cheers,
>
> Garry
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



From eire1130 at gmail.com  Fri Jul 22 21:04:29 2011
From: eire1130 at gmail.com (James Reynolds)
Date: Fri, 22 Jul 2011 15:04:29 -0400
Subject: [Tutor] Question regarding xml.dom.minidom: How do you send an
 unsignedByte in an wsdl request
In-Reply-To: <CAPUo4G5ZOq3y5fG9mMXhyq+q9wznczSo82Z4Q1yXw5mN+EGmCQ@mail.gmail.com>
References: <CAPUo4G5ZOq3y5fG9mMXhyq+q9wznczSo82Z4Q1yXw5mN+EGmCQ@mail.gmail.com>
Message-ID: <CAE0jAbotzfMhAsuhVjm2O4UwmHCU3R7gzktpz6Ow9vthA1Mg+Q@mail.gmail.com>

On Fri, Jul 22, 2011 at 2:18 PM, Garry Bettle <garry.bettle at gmail.com>wrote:

> Howdy all,
>
> Hope this message finds everyone well - roll on the weekend!
>
> I'm trying some calls to an wsdl API I've subscribed to.
>
> But I'm struggling to know what they want when sending an unsignedByte in a
> request.
>
> I'm using xml.dom.minidom so to start with I have:
> from xml.dom.minidom import Document, parseString
> import httplib, urlparse
>
> And later on I create a doc with:
> doc=Document()
>
> And I have a using a little helper to add a text element:
> def add_text_element(doc, parent, name, value):
>     element=doc.createElement(name)
>     element.appendChild(doc.createTextNode(str(value)))
>     parent.appendChild(element)
>
> Should I have a separate class for an unsignedByte? i.e. def
> add_byte_element
>
> What should it look like?
>
> This is what their API helpdesk have said:
>
> "In this instance, the PriceFormat is defined as an unsignedByte.
>
>
>
>      *<xs:complexType name="GetOddsLadderRequest">*
>
> *<xs:attribute name="PriceFormat" type="xs:unsignedByte" /> *
>
> *</xs:complexType>*"
>
> Many thanks!
>
> Cheers,
>
> Garry
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

this, *type=**xs:**unsignedByte*, is an attribute. I'm assuming "doc" above
is an instance of class Document, so you can get the element by using
doc.getElementsByTagName('complexType') or whatever it is you are talking
about for the element.

That will return an Element instance, and from there you can go haywire
adding attributes. The Element class has a method called
"setAttribute('string')".

You would do this right here:

    element=doc.createElement(name)
    <-- wave <--- element.setAttribute('string') <-- your argument here
    element.appendChild(doc.createTextNode(str(value)))
    parent.appendChild(element)

The node from your example has two attributes, and not one. I'm not sure how
important this is for you.

Anyway, that's my answer. I'm a newb though, and even more of a newb with
XML.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110722/f5d8ae52/attachment.html>

From stefan_ml at behnel.de  Fri Jul 22 21:09:30 2011
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 22 Jul 2011 21:09:30 +0200
Subject: [Tutor] Question regarding xml.dom.minidom: How do you send an
 unsignedByte in an wsdl request
In-Reply-To: <j0chbd$ac5$1@dough.gmane.org>
References: <CAPUo4G5ZOq3y5fG9mMXhyq+q9wznczSo82Z4Q1yXw5mN+EGmCQ@mail.gmail.com>
	<j0chbd$ac5$1@dough.gmane.org>
Message-ID: <j0chta$csd$1@dough.gmane.org>

Emile van Sebille, 22.07.2011 20:59:
> You'll likely get more traction on this at
> http://mail.python.org/mailman/listinfo/xml-sig

Unlikely.

Stefan


From stefan_ml at behnel.de  Fri Jul 22 21:24:24 2011
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 22 Jul 2011 21:24:24 +0200
Subject: [Tutor] Question regarding xml.dom.minidom: How do you send an
 unsignedByte in an wsdl request
In-Reply-To: <CAPUo4G5ZOq3y5fG9mMXhyq+q9wznczSo82Z4Q1yXw5mN+EGmCQ@mail.gmail.com>
References: <CAPUo4G5ZOq3y5fG9mMXhyq+q9wznczSo82Z4Q1yXw5mN+EGmCQ@mail.gmail.com>
Message-ID: <j0cip9$k0c$1@dough.gmane.org>

Garry Bettle, 22.07.2011 20:18:
> I'm trying some calls to an wsdl API I've subscribed to.

You might find this interesting:

http://effbot.org/zone/element-soap.htm


> But I'm struggling to know what they want when sending an unsignedByte in a
> request.

That's just a number, plain old-fashioned decimal digits.


>       *<xs:complexType name="GetOddsLadderRequest">*
> *<xs:attribute name="PriceFormat" type="xs:unsignedByte" />  *
> *</xs:complexType>*"

In ElementTree, that's just

   request_element = Element("request_tag_name_here", PriceFormat="123")

Stefan


From emile at fenx.com  Fri Jul 22 22:39:14 2011
From: emile at fenx.com (Emile van Sebille)
Date: Fri, 22 Jul 2011 13:39:14 -0700
Subject: [Tutor] Question regarding xml.dom.minidom: How do you send an
 unsignedByte in an wsdl request
In-Reply-To: <j0chta$csd$1@dough.gmane.org>
References: <CAPUo4G5ZOq3y5fG9mMXhyq+q9wznczSo82Z4Q1yXw5mN+EGmCQ@mail.gmail.com>
	<j0chbd$ac5$1@dough.gmane.org> <j0chta$csd$1@dough.gmane.org>
Message-ID: <4E29DFF2.8040808@fenx.com>

On 7/22/2011 12:09 PM Stefan Behnel said...
> Emile van Sebille, 22.07.2011 20:59:
>> You'll likely get more traction on this at
>> http://mail.python.org/mailman/listinfo/xml-sig
>
> Unlikely.

Wow.  Agreed.  Five unanswered posts this year.

Emile


From alan.gauld at btinternet.com  Thu Jul 21 22:47:44 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 21 Jul 2011 21:47:44 +0100
Subject: [Tutor] OT: Drag and Drop GUI IDE ideas
In-Reply-To: <CANWBxgaPVmgyjWGCtcFHuHCa0Gx_g-yD-wHmh5zzWde1xYBT3w@mail.gmail.com>
References: <CANWBxgaPVmgyjWGCtcFHuHCa0Gx_g-yD-wHmh5zzWde1xYBT3w@mail.gmail.com>
Message-ID: <4E289070.2030906@btinternet.com>

Rance Hall wrote:

> We want the students to develop a small app in the process, It could
> be a firefox extension, mobile phone app, or any other type simple
> structure.

ou can develop very smpleAndoid apps witout any coding using a 
Googletoolit. I've only read an aticle aboutit so an't sy how 
cleveritgets or how easy itreallyis to use. The problermisthat building 
apps, especially GII apps is not an easy thing to do.

The easiest environment is probably, and I hate to say it
- Visual Basic!
And there is a free version but you'd need to check the usage
limits (I'm sure there will be some!) But you could use the
Microsoft office VBA environbment instead - and thats a
tool they will probably have in the real world...


> The catch is that the class is for non-programmers to try to get them
> introduced to the field.  We would like to use a gui ide that can
> essentially hide the code from the programmer and connect widgets with
> the gui.
> 
> We want them to be able to look at the code and analyze it.

VB would allow that.

Another option is The Apple Mac development tool XCode and
the Apple GUI builder - free if you have MacOS X. It uses a graphical 
representation to connect code to widgets but it is less intuitive than 
the VB approach (but much more powerful!) You can read through the short 
Cocoa tutorial on the apple developer site to see it in action.

Dabo might be an option for a Python solution but I findit a tad too 
data centric. But for business types that might not be a bad thing!

HTH,

Alan G

From alan.gauld at btinternet.com  Thu Jul 21 22:47:44 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 21 Jul 2011 21:47:44 +0100
Subject: [Tutor] OT: Drag and Drop GUI IDE ideas
In-Reply-To: <CANWBxgaPVmgyjWGCtcFHuHCa0Gx_g-yD-wHmh5zzWde1xYBT3w@mail.gmail.com>
References: <CANWBxgaPVmgyjWGCtcFHuHCa0Gx_g-yD-wHmh5zzWde1xYBT3w@mail.gmail.com>
Message-ID: <4E289070.2030906@btinternet.com>

Rance Hall wrote:

> We want the students to develop a small app in the process, It could
> be a firefox extension, mobile phone app, or any other type simple
> structure.

ou can develop very smpleAndoid apps witout any coding using a 
Googletoolit. I've only read an aticle aboutit so an't sy how 
cleveritgets or how easy itreallyis to use. The problermisthat building 
apps, especially GII apps is not an easy thing to do.

The easiest environment is probably, and I hate to say it
- Visual Basic!
And there is a free version but you'd need to check the usage
limits (I'm sure there will be some!) But you could use the
Microsoft office VBA environbment instead - and thats a
tool they will probably have in the real world...


> The catch is that the class is for non-programmers to try to get them
> introduced to the field.  We would like to use a gui ide that can
> essentially hide the code from the programmer and connect widgets with
> the gui.
> 
> We want them to be able to look at the code and analyze it.

VB would allow that.

Another option is The Apple Mac development tool XCode and
the Apple GUI builder - free if you have MacOS X. It uses a graphical 
representation to connect code to widgets but it is less intuitive than 
the VB approach (but much more powerful!) You can read through the short 
Cocoa tutorial on the apple developer site to see it in action.

Dabo might be an option for a Python solution but I findit a tad too 
data centric. But for business types that might not be a bad thing!

HTH,

Alan G


From dave at csc.lsu.edu  Sat Jul 23 00:40:08 2011
From: dave at csc.lsu.edu (dave)
Date: Fri, 22 Jul 2011 17:40:08 -0500
Subject: [Tutor] Don't understand this class/constructor call syntax
Message-ID: <20110722223458.M83643@csc.lsu.edu>

Hello,

I'm trying to work on GNU Radio and having trouble understanding some of the
Python code.  I have a C/C++ coding background.  I'm looking at the
ieee802.15.4 code found on CGRAN.  It's about 4 years old and runs but doesn't
function anymore so I'm trying to fully understand it to fix it.

In one file (a file in src/example called cc2420_txtest.py) I have the
following line from a constructor for:

class transmit_path(gr.top_block)
...
...
...
        self.packet_transmitter = ieee802_15_4_pkt.ieee802_15_4_mod_pkts(self,
spb=self._spb, msgq_limit=2)



Now in the src/python directory for this project I have ieee802_15_4pkt.py
which has the following class:



class ieee802_15_4_mod_pkts(gr.hier_block2):
    """
    IEEE 802.15.4 modulator that is a GNU Radio source.
    Send packets by calling send_pkt
    """
    def __init__(self, pad_for_usrp=True, *args, **kwargs):[/code]



What I don't understand is the call to the constructor and the constructor
definition.  Since it's using a number of advanced features, I'm having
trouble looking it all up in documentation.

What does it mean to call with spb=self._spb?  In the example file, spb is set
= to 2 and so is self._spb.  Is it a sort of pass by reference like C while
also assigning a value? Why the  ** on kwargs then? as if it is a matrix

(and does anyone have any idea what kwargs are (as opposed to args)?)

I'm uncertain about the first argument, but I guess it must be the
transmit_path object passed in place of the usually implicit self...  I'm just
not sure how Python figures out that it's not pad_for_usrp... magic I guess!


Thanks for your help,
Dave

From d at davea.name  Sat Jul 23 01:23:00 2011
From: d at davea.name (Dave Angel)
Date: Fri, 22 Jul 2011 19:23:00 -0400
Subject: [Tutor] Don't understand this class/constructor call syntax
In-Reply-To: <20110722223458.M83643@csc.lsu.edu>
References: <20110722223458.M83643@csc.lsu.edu>
Message-ID: <4E2A0654.2020209@davea.name>

On 07/22/2011 06:40 PM, dave wrote:
> Hello,
>
> I'm trying to work on GNU Radio and having trouble understanding some of the
> Python code.  I have a C/C++ coding background.  I'm looking at the
> ieee802.15.4 code found on CGRAN.  It's about 4 years old and runs but doesn't
> function anymore so I'm trying to fully understand it to fix it.
>
> In one file (a file in src/example called cc2420_txtest.py) I have the
> following line from a constructor for:
>
> class transmit_path(gr.top_block)
> ...
> ...
> ...
>          self.packet_transmitter = ieee802_15_4_pkt.ieee802_15_4_mod_pkts(self,
> spb=self._spb, msgq_limit=2)
>
>
>
> Now in the src/python directory for this project I have ieee802_15_4pkt.py
> which has the following class:
>
>
>
> class ieee802_15_4_mod_pkts(gr.hier_block2):
>      """
>      IEEE 802.15.4 modulator that is a GNU Radio source.
>      Send packets by calling send_pkt
>      """
>      def __init__(self, pad_for_usrp=True, *args, **kwargs):[/code]
>
>
>
> What I don't understand is the call to the constructor and the constructor
> definition.  Since it's using a number of advanced features, I'm having
> trouble looking it all up in documentation.
>
> What does it mean to call with spb=self._spb?  In the example file, spb is set
> = to 2 and so is self._spb.  Is it a sort of pass by reference like C while
> also assigning a value? Why the  ** on kwargs then? as if it is a matrix
>
> (and does anyone have any idea what kwargs are (as opposed to args)?)
>
> I'm uncertain about the first argument, but I guess it must be the
> transmit_path object passed in place of the usually implicit self...  I'm just
> not sure how Python figures out that it's not pad_for_usrp... magic I guess!
>
>
There are many different things in your question, and I don't know if I 
can hit them all in my reply, but I'll see what I can do.

The '=' syntax means an entirely different thing in the call from what 
it means in the definition of a function.  And the * and ** syntax are 
special, although there at least there's a relationship between what 
they mean in the two locations.  Let's just address these 4 cases 
outside of a class, and defer your class questions to when you can post 
enough code to see all the pieces (you don't show method

ieee802_15_4_mod_pkts, but it's probably got a @class decorator in front of it, which changes the 'self' convention to a 'cls' one)


When a function definition uses an "=" in it, it's setting a default argument.  So if I define a function:

def test(a, b=24):
       print a+b

it can be called with either one argument or with two, and if one argument, the value b is implicitly passed.  This is similar to C++, except that the default value is initialized at the definition site, and at the time the definition is done.  So if the value is mutable, the same value may be used for multiple calls to the same function.

If a function call is made using a similar syntax, it refers to a keyword argument.  By default arguments are positional, meaning that they have to be given in the right order, with no gaps.  A keyword argument allows you to specify parameters out of order, and by name.  It's most useful when there is a function with lots of arguments, most of which you're happy with the default values.  To make a trivial example:

def test2(a, b=2, c=3, d=4):
      print a,b,c,d

test2(12, d=99)

will print   12 2 3 99

Sometimes you want to pass a lot of arguments without spelling them out 
in your call.  So if the values are in a list, and in the right order, 
you can do something like:

myargs = [3, 99, 12, 44]
test2(*args)

You can also use a dictionary, like:
mykwargs = { "a":3, "d":44, "b":99, "c":12}
test2(**args)

And there's a lot of symmetry when defining a function with those same 
similarities:

def  test3(*args, **kwargs):
       xxxxx

here args will be a list() with the positional arguments, while kwargs 
will be a dict() with the keyword ones.

Now these features can be mixed in lots of ways, but that's way too much 
for a single message.


(All code above is untested;  please forgive any typos)

-- 

DaveA


From wprins at gmail.com  Sat Jul 23 02:01:48 2011
From: wprins at gmail.com (Walter Prins)
Date: Sat, 23 Jul 2011 01:01:48 +0100
Subject: [Tutor] OT: Drag and Drop GUI IDE ideas
In-Reply-To: <CANWBxgaPVmgyjWGCtcFHuHCa0Gx_g-yD-wHmh5zzWde1xYBT3w@mail.gmail.com>
References: <CANWBxgaPVmgyjWGCtcFHuHCa0Gx_g-yD-wHmh5zzWde1xYBT3w@mail.gmail.com>
Message-ID: <CANLXbfDyP0Kh5fV+NdLD8n+3n2cv+0UaxqMMsksGsw7XW0XorQ@mail.gmail.com>

Hi Rance,

On 21 July 2011 23:17, Rance Hall <ranceh at gmail.com> wrote:

> The MIS department at UNK is looking to create a course in business
> app development.
>
> The course will be about the app life cycle and discuss problem
> statement, testing, maintenance and disposal/decommissioning, etc.
>
> We want the students to develop a small app in the process, It could
> be a firefox extension, mobile phone app, or any other type simple
> structure.
>

Does it have to involve mobile platforms etc or can it be a more
conventional MIS PC application?  And, are you really after some sort of RAD
environment where you can build the GUI by dragging and dropping widgets,
and have it generate the tie-up of event handlers to your program code?  If
so, I'd have suggested Embarcadero Delphi (which uses Object Pascal as the
language) rather than VB, but that is commercial.  As an alternative
sticking with the Delphi/Pascalish theme, you might consider is the Lazarus
project.  It is a Free software implementation that mimics Delphi and uses
Free Pascal as the language.  It attempts to be as compatible as possible
with Delphi but unlike Delphi also has the benefit of being natively cross
platform -- applications written in Lazarus will compile unmodified on
either Windows or Linux (or any other platform it's available on, e.g. Mac)
It does have a GUI designer allowing you drag and drop controls onto the
form, attach event handlers and so on, and then view the code behind the
form (F12) etc.  The IDE has syntax highlighting and the core of the usual
things seen in IDE's these days (code completion, context sensitive help
etc.)  Continuing in this theme, a possible third option to consider would
be "Boa Constructor".  It is a RAD'ish IDE environment for Python and
WxWidgets, styled on the Delphi IDE.  It again allows you to design forms
visually while the IDE generates the boilerplate application code and wires
up widgets to events and so on.  I'm however unsure how actively maintained
the Boa project is currently -- the last update seems to be circa 2007.

Hoping that is useful,

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110723/818db0da/attachment-0001.html>

From steve at pearwood.info  Sat Jul 23 05:09:07 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 23 Jul 2011 13:09:07 +1000
Subject: [Tutor] Don't understand this class/constructor call syntax
In-Reply-To: <20110722223458.M83643@csc.lsu.edu>
References: <20110722223458.M83643@csc.lsu.edu>
Message-ID: <4E2A3B53.3000409@pearwood.info>

dave wrote:

> class transmit_path(gr.top_block)
[...]
>         self.packet_transmitter = ieee802_15_4_pkt.ieee802_15_4_mod_pkts(self,
>                                   spb=self._spb, msgq_limit=2)


This calls the ieee802_15_4_mod_pkts initializer (not a constructor -- 
see below) with one positional argument and two keyword arguments.

The positional argument is "self", that is, the transmit_path instance.

The keyword arguments are called spb and msgq_limit; spb is set to the 
value of self._spb, and msgq_limit is set to 2.

The reason I say this is an initializer and not a constructor is that 
Python treats the two as different. The constructor that creates the 
instance is called __new__ not __init__. When __init__ is called, the 
instance has already been constructed, and is now being initialized. The 
reason for this is mostly historical, although it is useful.

(Disclaimer -- so called "old style" or "classic" classes don't have a 
__new__ method, and you cannot customize the actual creation of the 
instance, only the initialization.)

Looking at the ieee802_15_4_mod_pkts initializer:


> class ieee802_15_4_mod_pkts(gr.hier_block2):
>     def __init__(self, pad_for_usrp=True, *args, **kwargs):[/code]

As a method, this takes the instance as first argument (called "self"), 
plus one named argument "pad_for_usrp", an arbitrary number of unnamed 
positional arguments collected into "args", and an arbitrary number of 
named keyword arguments collected into "kwargs".

(Note that args and kwargs are conventions. You could call them anything 
you like -- the "magic", so to speak, comes from the leading * and ** 
and not from the names.)

Given the call:

ieee802_15_4_mod_pkts(self, spb=self._spb, msgq_limit=2)

this corresponds to the initializer receiving arguments:

self = the freshly created ieee802_15_4_mod_pkts instance
pad_for_usrp = the transmit_path instance doing the calling
args = an empty tuple (no positional arguments collect)
kwargs = a dictionary of keyword arguments
          {'spb': value of _spb of the transmit_path instance,
           'msgq_limit': 2}


> What I don't understand is the call to the constructor and the constructor
> definition.  Since it's using a number of advanced features, I'm having
> trouble looking it all up in documentation.
> 
> What does it mean to call with spb=self._spb?  In the example file, spb is set
> = to 2 and so is self._spb.  Is it a sort of pass by reference like C while
> also assigning a value? Why the  ** on kwargs then? as if it is a matrix

No, this is nothing to do with pass by reference, or pass by value 
either. This often confuses people coming to Python from some other 
languages, and if it isn't a FAQ it ought to be. You can read one of my 
posts on this here:

http://www.mail-archive.com/tutor%40python.org/msg46612.html

and the Wikipedia article:

http://en.wikipedia.org/wiki/Evaluation_strategy


What it means is that the method being called (in this case, 
ieee802_15_4_mod_pkts.__init__) sees a keyword argument called "spb". 
This keyword argument has name "spb", and value whatever self._spb has 
at the time it is called.

When Python allocates arguments to the named parameters in a method or 
function, its basic process is roughly something like this:


(1) for methods, automatically assign the instance being called to the 
first named parameter (usually called "self" by convention);

(2) take each positional argument from the caller and assign it to the 
remaining positional parameters, from left to right;

(3) assign any keyword arguments, raising an error if it duplicates a 
value already seen;

(4) raise an error if any unassigned parameter doesn't have a default value;

(5) collect any left over positional arguments into the *args parameter;

(6) collect any left over keyword arguments into the **kwargs parameter.



> (and does anyone have any idea what kwargs are (as opposed to args)?)


Positional arguments: function(1, 2)
Keyword arguments: function(a=1, b=2)



> I'm uncertain about the first argument, but I guess it must be the
> transmit_path object passed in place of the usually implicit self...  I'm just
> not sure how Python figures out that it's not pad_for_usrp... magic I guess!

I don't think that it is used as the implicit self. I think it is the 
pad_for_usrp.




-- 
Steven


From 0101amt at gmail.com  Sat Jul 23 14:48:03 2011
From: 0101amt at gmail.com (amt)
Date: Sat, 23 Jul 2011 15:48:03 +0300
Subject: [Tutor] What's the difference between %s and %r?
Message-ID: <CAEQEn01bScZP1-Rh_dGdPwkt=R585q34o6tkZzK9S+0WjT9wfg@mail.gmail.com>

Hello! I'm having troubles understanding what is the difference between %s
and %r(format characters). I did google  and found something on
StackOverflow but I don't understand the explanation as it's not beginner
orientated.


Also, I have this code from learn python the hard way. Why at line 9 does he
uses %r? Why did he didn't wrote print "I said: %s." %x ?

1    x = "There are %d types of people." % 10
2    binary = "binary"
3    do_not = "don't"
4    y = "Those who know %s and those who %s." % (binary, do_not)
5
6    print x
7    print y
8
9    print "I said: %r." % x
10  print "I also said: '%s'." % y
11
12  hilarious = False
13  joke_evaluation = "Isn't that joke so funny?! %r"
14
15  print joke_evaluation % hilarious
16
17  w = "This is the left side of..."
18  e = "a string with a right side."
19
20  print w + e



Thanks in advance!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110723/84c9412c/attachment.html>

From waynejwerner at gmail.com  Sat Jul 23 15:27:27 2011
From: waynejwerner at gmail.com (Wayne Werner)
Date: Sat, 23 Jul 2011 08:27:27 -0500
Subject: [Tutor] What's the difference between %s and %r?
In-Reply-To: <CAEQEn01bScZP1-Rh_dGdPwkt=R585q34o6tkZzK9S+0WjT9wfg@mail.gmail.com>
References: <CAEQEn01bScZP1-Rh_dGdPwkt=R585q34o6tkZzK9S+0WjT9wfg@mail.gmail.com>
Message-ID: <CAPM86NeLbVUdtfPpEzFO07BfGF1pNjP7c9Y0x2gf_ivhEkwouA@mail.gmail.com>

On Sat, Jul 23, 2011 at 7:48 AM, amt <0101amt at gmail.com> wrote:

> Hello! I'm having troubles understanding what is the difference between %s
> and %r(format characters). I did google  and found something on
> StackOverflow but I don't understand the explanation as it's not beginner
> orientated.
>
>
> Also, I have this code from learn python the hard way. Why at line 9 does
> he uses %r? Why did he didn't wrote print "I said: %s." %x ?
> <snip>


As the answer here (
http://stackoverflow.com/questions/6005159/when-to-use-r-instead-of-s-in-python)
says,  it changes the method of evaluating an object. Here's a simple
example:


In [2]: class Thingy:
   ...:     def __str__(self):
   ...:         return "Hello"
   ...:     def __repr__(self):
   ...:         return "Goodbye"
   ...:
   ...:

In [3]: "%s %r" % (Thingy(), Thingy())
Out[3]: 'Hello Goodbye'

I'm not sure if there's a huge difference, and to be honest usually my
classes look like this:

class CoolGuy:
    def __str__(self):
        return "I'm a cool guy"
    def __repr__(self):
        return str(self)

so there would be no difference between the two.

In the interpreter,  the __repr__ method is called on the class when you
type it in - that's how python knows what to display:

In [5]: cool = Thingy()

In [6]: cool
Out[6]: Goodbye

Classes also start out with a default __repr__ that contains... well, this:

 In [7]: class AnotherThingy:
   ...:     pass
   ...:

In [8]: neat = AnotherThingy()

In [9]: neat
Out[9]: <__main__.AnotherThingy instance at 0x9a5a66c>


HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110723/1df6a358/attachment.html>

From lisi.reisz at gmail.com  Sat Jul 23 16:41:23 2011
From: lisi.reisz at gmail.com (Lisi)
Date: Sat, 23 Jul 2011 15:41:23 +0100
Subject: [Tutor] What's the difference between %s and %r?
In-Reply-To: <CAEQEn01bScZP1-Rh_dGdPwkt=R585q34o6tkZzK9S+0WjT9wfg@mail.gmail.com>
References: <CAEQEn01bScZP1-Rh_dGdPwkt=R585q34o6tkZzK9S+0WjT9wfg@mail.gmail.com>
Message-ID: <201107231541.24324.lisi.reisz@gmail.com>

On Saturday 23 July 2011 13:48:03 amt wrote:
> Hello! I'm having troubles understanding what is the difference between %s
> and %r(format characters). I did google  and found something on
> StackOverflow but I don't understand the explanation as it's not beginner
> orientated.
>
>
> Also, I have this code from learn python the hard way. Why at line 9 does
> he uses %r? Why did he didn't wrote print "I said: %s." %x ?
>
> 1    x = "There are %d types of people." % 10
> 2    binary = "binary"
> 3    do_not = "don't"
> 4    y = "Those who know %s and those who %s." % (binary, do_not)
> 5
> 6    print x
> 7    print y
> 8
> 9    print "I said: %r." % x
> 10  print "I also said: '%s'." % y
> 11
> 12  hilarious = False
> 13  joke_evaluation = "Isn't that joke so funny?! %r"
> 14
> 15  print joke_evaluation % hilarious
> 16
> 17  w = "This is the left side of..."
> 18  e = "a string with a right side."
> 19
> 20  print w + e
>
>
>
> Thanks in advance!

I have recently worked through that exact question myself.  And it isn't well 
explained.

So - the simplistic answer, gleaned (hopefully not erroneously) from this 
list:  s means a string, d means a number and r can be either or both.  y has 
only words, so is a string, and x has a number (specifically referred to as 
d) and words, so needs r.

Lisi

From martin at linux-ip.net  Sat Jul 23 17:08:06 2011
From: martin at linux-ip.net (Martin A. Brown)
Date: Sat, 23 Jul 2011 17:08:06 +0200
Subject: [Tutor] What's the difference between %s and %r?
In-Reply-To: <201107231541.24324.lisi.reisz@gmail.com>
References: <CAEQEn01bScZP1-Rh_dGdPwkt=R585q34o6tkZzK9S+0WjT9wfg@mail.gmail.com>
	<201107231541.24324.lisi.reisz@gmail.com>
Message-ID: <alpine.LNX.2.00.1107231701270.19174@octothorpe.wonderfrog.net>


Hello everybody,

 : > Hello! I'm having troubles understanding what is the difference between %s
 : > and %r(format characters). I did google  and found something on
 : > StackOverflow but I don't understand the explanation as it's not beginner
 : > orientated.
 : >
 : >
 : > Also, I have this code from learn python the hard way. Why at line 9 does
 : > he uses %r? Why did he didn't wrote print "I said: %s." %x ?
 : >
 : > 1    x = "There are %d types of people." % 10
 : > 2    binary = "binary"
 : > 3    do_not = "don't"
 : > 4    y = "Those who know %s and those who %s." % (binary, do_not)
 : > 5
 : > 6    print x
 : > 7    print y
 : > 8
 : > 9    print "I said: %r." % x
 : > 10  print "I also said: '%s'." % y
 : > 11
 : > 12  hilarious = False
 : > 13  joke_evaluation = "Isn't that joke so funny?! %r"
 : > 14
 : > 15  print joke_evaluation % hilarious
 : > 16
 : > 17  w = "This is the left side of..."
 : > 18  e = "a string with a right side."
 : > 19
 : > 20  print w + e
 : >
 : >
 : >
 : > Thanks in advance!
 : 
 : I have recently worked through that exact question myself.  And 
 : it isn't well explained.
 : 
 : So - the simplistic answer, gleaned (hopefully not erroneously) 
 : from this list:  s means a string, d means a number and r can be 
 : either or both.  y has only words, so is a string, and x has a 
 : number (specifically referred to as d) and words, so needs r.

I am not horrendously well-versed here, but consider the mnemonic.

  %f   float
  %d   digit
  %s   string
  %r   representation

A representation is something that (might?) allow for some sort of 
round-trip, later (re)construction of the object.  A string is 
intended for general consumption.  Do you really need to distinguish 
them?  Only if you plan on re-consuming your own output, at which 
point you should consider the representation rather than the string.

There are doubtless more experienced hands here who will suggest 
concretely what you might do, but I would suggest that you use %s 
(string) for anything that you want to show to an end user and %r 
iif* you are planning to (re-)consume your own printed output.

-Martin

 * iif = if and only if

-- 
Martin A. Brown
http://linux-ip.net/

From eire1130 at gmail.com  Sat Jul 23 17:24:32 2011
From: eire1130 at gmail.com (James Reynolds)
Date: Sat, 23 Jul 2011 11:24:32 -0400
Subject: [Tutor] What's the difference between %s and %r?
In-Reply-To: <alpine.LNX.2.00.1107231701270.19174@octothorpe.wonderfrog.net>
References: <CAEQEn01bScZP1-Rh_dGdPwkt=R585q34o6tkZzK9S+0WjT9wfg@mail.gmail.com>
	<201107231541.24324.lisi.reisz@gmail.com>
	<alpine.LNX.2.00.1107231701270.19174@octothorpe.wonderfrog.net>
Message-ID: <CAE0jAbqPVip8rdbBCW7O7c96q4bAr_XAdGOO33cRNNq_4WADTw@mail.gmail.com>

I just use string{0}.format(arg) format and that solves needing to memorize
% whatevers.

On Sat, Jul 23, 2011 at 11:08 AM, Martin A. Brown <martin at linux-ip.net>wrote:

>
> Hello everybody,
>
>  : > Hello! I'm having troubles understanding what is the difference
> between %s
>  : > and %r(format characters). I did google  and found something on
>  : > StackOverflow but I don't understand the explanation as it's not
> beginner
>  : > orientated.
>  : >
>  : >
>  : > Also, I have this code from learn python the hard way. Why at line 9
> does
>  : > he uses %r? Why did he didn't wrote print "I said: %s." %x ?
>  : >
>  : > 1    x = "There are %d types of people." % 10
>  : > 2    binary = "binary"
>  : > 3    do_not = "don't"
>  : > 4    y = "Those who know %s and those who %s." % (binary, do_not)
>  : > 5
>  : > 6    print x
>  : > 7    print y
>  : > 8
>  : > 9    print "I said: %r." % x
>  : > 10  print "I also said: '%s'." % y
>  : > 11
>  : > 12  hilarious = False
>  : > 13  joke_evaluation = "Isn't that joke so funny?! %r"
>  : > 14
>  : > 15  print joke_evaluation % hilarious
>  : > 16
>  : > 17  w = "This is the left side of..."
>  : > 18  e = "a string with a right side."
>  : > 19
>  : > 20  print w + e
>  : >
>  : >
>  : >
>  : > Thanks in advance!
>  :
>  : I have recently worked through that exact question myself.  And
>  : it isn't well explained.
>  :
>  : So - the simplistic answer, gleaned (hopefully not erroneously)
>  : from this list:  s means a string, d means a number and r can be
>  : either or both.  y has only words, so is a string, and x has a
>  : number (specifically referred to as d) and words, so needs r.
>
> I am not horrendously well-versed here, but consider the mnemonic.
>
>  %f   float
>  %d   digit
>  %s   string
>  %r   representation
>
> A representation is something that (might?) allow for some sort of
> round-trip, later (re)construction of the object.  A string is
> intended for general consumption.  Do you really need to distinguish
> them?  Only if you plan on re-consuming your own output, at which
> point you should consider the representation rather than the string.
>
> There are doubtless more experienced hands here who will suggest
> concretely what you might do, but I would suggest that you use %s
> (string) for anything that you want to show to an end user and %r
> iif* you are planning to (re-)consume your own printed output.
>
> -Martin
>
>  * iif = if and only if
>
> --
> Martin A. Brown
> http://linux-ip.net/
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110723/59fa20bc/attachment-0001.html>

From joel.goldstick at gmail.com  Sat Jul 23 17:35:39 2011
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Sat, 23 Jul 2011 11:35:39 -0400
Subject: [Tutor] What's the difference between %s and %r?
In-Reply-To: <CAEQEn01bScZP1-Rh_dGdPwkt=R585q34o6tkZzK9S+0WjT9wfg@mail.gmail.com>
References: <CAEQEn01bScZP1-Rh_dGdPwkt=R585q34o6tkZzK9S+0WjT9wfg@mail.gmail.com>
Message-ID: <CAPM-O+xo9N6PCwLs0MC9nsyTCBYZ4iGz+nmm=i=DSSmjAniSpA@mail.gmail.com>

On Sat, Jul 23, 2011 at 8:48 AM, amt <0101amt at gmail.com> wrote:

> Hello! I'm having troubles understanding what is the difference between %s
> and %r(format characters). I did google  and found something on
> StackOverflow but I don't understand the explanation as it's not beginner
> orientated.
>
>
> Also, I have this code from learn python the hard way. Why at line 9 does
> he uses %r? Why did he didn't wrote print "I said: %s." %x ?
>
> 1    x = "There are %d types of people." % 10
> 2    binary = "binary"
> 3    do_not = "don't"
> 4    y = "Those who know %s and those who %s." % (binary, do_not)
> 5
> 6    print x
> 7    print y
> 8
> 9    print "I said: %r." % x
> 10  print "I also said: '%s'." % y
> 11
> 12  hilarious = False
> 13  joke_evaluation = "Isn't that joke so funny?! %r"
> 14
> 15  print joke_evaluation % hilarious
> 16
> 17  w = "This is the left side of..."
> 18  e = "a string with a right side."
> 19
> 20  print w + e
>
>
>
> Thanks in advance!
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
r String (converts any python object using repr()). (5)

repr(*object*)? <http://docs.python.org/library/functions.html#repr>Return a
string containing a printable representation of an object. This is the same
value yielded by conversions (reverse quotes). It is sometimes useful to be
able to access this operation as an ordinary function. For many types, this
function makes an attempt to return a string that would yield an object with
the same value when passed to
eval()<http://docs.python.org/library/functions.html#eval>,
otherwise the representation is a string enclosed in angle brackets that
contains the name of the type of the object together with additional
information often including the name and address of the object. A class can
control what this function returns for its instances by defining a
__repr__() <http://docs.python.org/reference/datamodel.html#object.__repr__>method.I
did some checking.  %r runs the repr() function on the object.  In this case
x is a string that needs to be evaluated.  So print "I said: %r." % x first
evaluates x then creates the full string.


-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110723/951fea2d/attachment.html>

From dave at csc.lsu.edu  Sat Jul 23 19:26:29 2011
From: dave at csc.lsu.edu (dave)
Date: Sat, 23 Jul 2011 12:26:29 -0500
Subject: [Tutor] Don't understand this class/constructor call syntax
In-Reply-To: <4E2A3B53.3000409@pearwood.info>
References: <20110722223458.M83643@csc.lsu.edu>
	<4E2A3B53.3000409@pearwood.info>
Message-ID: <20110723171954.M52452@csc.lsu.edu>

Thank you for the two explanations.  I think I have a good idea of what is
going on now with the arguments and keyword arguments.

My only remaining question is the pad_for_usrp argument.  The default value is
True so I thought it was a boolean and couldn't have anything to do with the
"self<transmit_path>" that was passed to it.  However, I can probably puzzle
that out by looking at how it's used in the code.  

If you want to look at the full code and make any more comments, the code tree
is here: https://www.cgran.org/browser/projects/ucla_zigbee_phy/trunk/src

The example I'm looking at is (I quoted line 56):
https://www.cgran.org/browser/projects/ucla_zigbee_phy/trunk/src/examples/cc2420_txtest.py

The example relies on two files.  This one:
https://www.cgran.org/browser/projects/ucla_zigbee_phy/trunk/src/python/ieee802_15_4.py

And this one (I quoted the class at line 138):
https://www.cgran.org/browser/projects/ucla_zigbee_phy/trunk/src/python/ieee802_15_4_pkt.py

Thanks,
Dave


On Sat, 23 Jul 2011 13:09:07 +1000, Steven D'Aprano wrote
> dave wrote:
> 
> > class transmit_path(gr.top_block)
> [...]
> >         self.packet_transmitter = ieee802_15_4_pkt.ieee802_15_4_mod_pkts(self,
> >                                   spb=self._spb, msgq_limit=2)
> 
> This calls the ieee802_15_4_mod_pkts initializer (not a constructor -
> - see below) with one positional argument and two keyword arguments.
> 
> The positional argument is "self", that is, the transmit_path instance.
> 
> The keyword arguments are called spb and msgq_limit; spb is set to 
> the value of self._spb, and msgq_limit is set to 2.
> 
> The reason I say this is an initializer and not a constructor is 
> that Python treats the two as different. The constructor that 
> creates the instance is called __new__ not __init__. When __init__ 
> is called, the instance has already been constructed, and is now 
> being initialized. The reason for this is mostly historical, 
> although it is useful.
> 
> (Disclaimer -- so called "old style" or "classic" classes don't have 
> a __new__ method, and you cannot customize the actual creation of 
> the instance, only the initialization.)
> 
> Looking at the ieee802_15_4_mod_pkts initializer:
> 
> > class ieee802_15_4_mod_pkts(gr.hier_block2):
> >     def __init__(self, pad_for_usrp=True, *args, **kwargs):[/code]
> 
> As a method, this takes the instance as first argument (called 
> "self"), plus one named argument "pad_for_usrp", an arbitrary number 
> of unnamed positional arguments collected into "args", and an 
> arbitrary number of named keyword arguments collected into "kwargs".
> 
> (Note that args and kwargs are conventions. You could call them 
> anything you like -- the "magic", so to speak, comes from the 
> leading * and ** and not from the names.)
> 
> Given the call:
> 
> ieee802_15_4_mod_pkts(self, spb=self._spb, msgq_limit=2)
> 
> this corresponds to the initializer receiving arguments:
> 
> self = the freshly created ieee802_15_4_mod_pkts instance
> pad_for_usrp = the transmit_path instance doing the calling
> args = an empty tuple (no positional arguments collect)
> kwargs = a dictionary of keyword arguments
>           {'spb': value of _spb of the transmit_path instance,
>            'msgq_limit': 2}
> 
> > What I don't understand is the call to the constructor and the constructor
> > definition.  Since it's using a number of advanced features, I'm having
> > trouble looking it all up in documentation.
> > 
> > What does it mean to call with spb=self._spb?  In the example file, spb is set
> > = to 2 and so is self._spb.  Is it a sort of pass by reference like C while
> > also assigning a value? Why the  ** on kwargs then? as if it is a matrix
> 
> No, this is nothing to do with pass by reference, or pass by value 
> either. This often confuses people coming to Python from some other 
> languages, and if it isn't a FAQ it ought to be. You can read one of 
> my posts on this here:
> 
> http://www.mail-archive.com/tutor%40python.org/msg46612.html
> 
> and the Wikipedia article:
> 
> http://en.wikipedia.org/wiki/Evaluation_strategy
> 
> What it means is that the method being called (in this case, 
> ieee802_15_4_mod_pkts.__init__) sees a keyword argument called 
> "spb". This keyword argument has name "spb", and value whatever 
> self._spb has at the time it is called.
> 
> When Python allocates arguments to the named parameters in a method 
> or function, its basic process is roughly something like this:
> 
> (1) for methods, automatically assign the instance being called to 
> the first named parameter (usually called "self" by convention);
> 
> (2) take each positional argument from the caller and assign it to 
> the remaining positional parameters, from left to right;
> 
> (3) assign any keyword arguments, raising an error if it duplicates 
> a value already seen;
> 
> (4) raise an error if any unassigned parameter doesn't have a 
> default value;
> 
> (5) collect any left over positional arguments into the *args parameter;
> 
> (6) collect any left over keyword arguments into the **kwargs parameter.
> 
> > (and does anyone have any idea what kwargs are (as opposed to args)?)
> 
> Positional arguments: function(1, 2)
> Keyword arguments: function(a=1, b=2)
> 
> > I'm uncertain about the first argument, but I guess it must be the
> > transmit_path object passed in place of the usually implicit self...  I'm just
> > not sure how Python figures out that it's not pad_for_usrp... magic I guess!
> 
> I don't think that it is used as the implicit self. I think it is 
> the pad_for_usrp.
> 
> -- 
> Steven
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


--
Open WebMail Project (http://openwebmail.org)


From wescpy at gmail.com  Sat Jul 23 21:06:11 2011
From: wescpy at gmail.com (wesley chun)
Date: Sat, 23 Jul 2011 12:06:11 -0700
Subject: [Tutor] What's the difference between %s and %r?
In-Reply-To: <CAPM-O+xo9N6PCwLs0MC9nsyTCBYZ4iGz+nmm=i=DSSmjAniSpA@mail.gmail.com>
References: <CAEQEn01bScZP1-Rh_dGdPwkt=R585q34o6tkZzK9S+0WjT9wfg@mail.gmail.com>
	<CAPM-O+xo9N6PCwLs0MC9nsyTCBYZ4iGz+nmm=i=DSSmjAniSpA@mail.gmail.com>
Message-ID: <CAB6eaA71MAtnPvAYsOR=MuJD4Rfvr+fBB7OEy5V7EmSj_rUPQg@mail.gmail.com>

%s = send object to str() first then drop it into the string
%r = send object to repr() first then drop it into the string

pretty straightforward:

>>> x = 'foo'
>>> str(x)
'foo'
>>> repr(x)
"'foo'"

why do people do %r at all? to get the quotes for free: :-)

>>> x = 'Python'
>>> print "What is this '%s' language?" % x
What is this 'Python' language?
>>> print "What is this %r language?" % x
What is this 'Python' language?

cheers,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
    http://corepython.com

wesley.chun : wescpy-gmail.com : @wescpy
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110723/f0a016fa/attachment.html>

From wescpy at gmail.com  Sat Jul 23 21:13:46 2011
From: wescpy at gmail.com (wesley chun)
Date: Sat, 23 Jul 2011 12:13:46 -0700
Subject: [Tutor] What's the difference between %s and %r?
In-Reply-To: <CAB6eaA71MAtnPvAYsOR=MuJD4Rfvr+fBB7OEy5V7EmSj_rUPQg@mail.gmail.com>
References: <CAEQEn01bScZP1-Rh_dGdPwkt=R585q34o6tkZzK9S+0WjT9wfg@mail.gmail.com>
	<CAPM-O+xo9N6PCwLs0MC9nsyTCBYZ4iGz+nmm=i=DSSmjAniSpA@mail.gmail.com>
	<CAB6eaA71MAtnPvAYsOR=MuJD4Rfvr+fBB7OEy5V7EmSj_rUPQg@mail.gmail.com>
Message-ID: <CAB6eaA72SikGtrxMJ+h8JSU7F5DpiCZYw+OovD5620n_nxQ1ew@mail.gmail.com>

i forgot to define these:

str() - printable/human-readable string representation of an object
repr() - evaluatable string representation of an object (can "eval()"
it, meaning it is a string representation that evaluates to a Python
object)

in other words:

>>>> x = 'foo'
>>>> str(x)
> 'foo'
>>>> repr(x)
> "'foo'"

eval(str(x)) is not a valid Python object (you'll get a NameError)
while eval(repr(x)) *is* a valid Python object (you'll get a string
'foo'):

>>> eval('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'foo' is not defined
>>> eval("'foo'")
'foo'

-wesley


On Sat, Jul 23, 2011 at 12:06 PM, wesley chun <wescpy at gmail.com> wrote:
> %s = send object to str() first then drop it into the string
> %r = send object to repr() first then?drop it into the string
> pretty straightforward:
>>>> x = 'foo'
>>>> str(x)
> 'foo'
>>>> repr(x)
> "'foo'"
> why do people do %r at all? to get the quotes for free: :-)
>>>> x = 'Python'
>>>> print "What is this '%s' language?" % x
> What is this 'Python' language?
>>>> print "What is this %r language?" % x
> What is this 'Python' language?


-- 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Python Web Development with Django", Addison Wesley, (c) 2009
? ? http://withdjango.com

wesley.chun : wescpy-gmail.com : @wescpy
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com

From alan.gauld at btinternet.com  Sat Jul 23 01:14:18 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 23 Jul 2011 00:14:18 +0100
Subject: [Tutor] Don't understand this class/constructor call syntax
In-Reply-To: <20110723171954.M52452@csc.lsu.edu>
References: <20110722223458.M83643@csc.lsu.edu>	<4E2A3B53.3000409@pearwood.info>
	<20110723171954.M52452@csc.lsu.edu>
Message-ID: <4E2A044A.8050607@btinternet.com>

dave wrote:

> My only remaining question is the pad_for_usrp argument.  The default value is
> True so I thought it was a boolean and couldn't have anything to do with the
> "self<transmit_path>" that was passed to it.  However, I can probably puzzle
> that out by looking at how it's used in the code.  

I thought that was weird too and my first thought was that it was a bug.
The I thought that maybe it was using the fact that an object in Python 
normally evaluates to True so maybe the code tests for True and if True 
tries to determine the type and perform some operation.

If that's what its doing I don't like it and think it's a bad design but 
it is feasible.

OTOH it may still just be a bug! :-)

Alan G




From alan.gauld at btinternet.com  Sat Jul 23 01:14:18 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 23 Jul 2011 00:14:18 +0100
Subject: [Tutor] Don't understand this class/constructor call syntax
In-Reply-To: <20110723171954.M52452@csc.lsu.edu>
References: <20110722223458.M83643@csc.lsu.edu>	<4E2A3B53.3000409@pearwood.info>
	<20110723171954.M52452@csc.lsu.edu>
Message-ID: <4E2A044A.8050607@btinternet.com>

dave wrote:

> My only remaining question is the pad_for_usrp argument.  The default value is
> True so I thought it was a boolean and couldn't have anything to do with the
> "self<transmit_path>" that was passed to it.  However, I can probably puzzle
> that out by looking at how it's used in the code.  

I thought that was weird too and my first thought was that it was a bug.
The I thought that maybe it was using the fact that an object in Python 
normally evaluates to True so maybe the code tests for True and if True 
tries to determine the type and perform some operation.

If that's what its doing I don't like it and think it's a bad design but 
it is feasible.

OTOH it may still just be a bug! :-)

Alan G




From ryan.strunk at gmail.com  Sun Jul 24 06:29:44 2011
From: ryan.strunk at gmail.com (Ryan Strunk)
Date: Sat, 23 Jul 2011 23:29:44 -0500
Subject: [Tutor] Copying Variables
Message-ID: <002101cc49ba$515b89c0$f4129d40$@gmail.com>

Hello everyone,
How can I make two copies of a dictionary that don't point to the same
location in memory? My plan is to generate d1 and make d2 a copy of d1.
After the user modifies d1 I want him/her to be able to return to the
initial dictionary (d2) values. I tried:
d1 = {values}
d2 = dict(d1)
then later in the code when I want to re-initialize d1:
d1 = dict(d2)
but this won't work. Any suggestions you have as to how I can make this work
are welcome.
Best,
Ryan


From steve at pearwood.info  Sun Jul 24 06:58:58 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 24 Jul 2011 14:58:58 +1000
Subject: [Tutor] Copying Variables
In-Reply-To: <002101cc49ba$515b89c0$f4129d40$@gmail.com>
References: <002101cc49ba$515b89c0$f4129d40$@gmail.com>
Message-ID: <4E2BA692.3030601@pearwood.info>

Ryan Strunk wrote:
> Hello everyone,
> How can I make two copies of a dictionary that don't point to the same
> location in memory? My plan is to generate d1 and make d2 a copy of d1.
> After the user modifies d1 I want him/her to be able to return to the
> initial dictionary (d2) values. I tried:
> d1 = {values}

That can't work, because that makes a set, not a dict (in Python 3 at 
least). Perhaps you mean {key: value}, not just {value}?

> d2 = dict(d1)
> then later in the code when I want to re-initialize d1:
> d1 = dict(d2)
> but this won't work. Any suggestions you have as to how I can make this work
> are welcome.

Define "this won't work". What makes you think it doesn't work? This 
makes d2 a copy of d1, then makes d1 a copy of d2. They are different dicts.

My *guess* is that you're modifying the objects *inside* d1 and d2, 
which are shared. To make copies of *everything*, all the way down, use 
the copy module:

copy.copy  # makes a shallow copy, one level only
copy.deepcopy  # makes a deep copy, all the way down


-- 
Steven


From emekamicro at gmail.com  Sun Jul 24 08:56:02 2011
From: emekamicro at gmail.com (Emeka)
Date: Sun, 24 Jul 2011 07:56:02 +0100
Subject: [Tutor] Question related to Tkinker
Message-ID: <CAOypoo5AxmBBH68pK3eT11LFxE4Q1Ma5ur6E+40ucNafiz4XLQ@mail.gmail.com>

Hello All,

I am putting up a simple game .. the game is about manipulation. If the gets
through level one ... I have to change the word with another...

Am I going to destroy level window and build level 2 or is there a way to
just adjust the word (I used labels)

Regards,
Janus

-- 
*Satajanus  Nig. Ltd


*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110724/6e2f2890/attachment.html>

From kb1pkl at aim.com  Sun Jul 24 09:00:43 2011
From: kb1pkl at aim.com (Corey Richardson)
Date: Sun, 24 Jul 2011 03:00:43 -0400
Subject: [Tutor] Question related to Tkinker
In-Reply-To: <CAOypoo5AxmBBH68pK3eT11LFxE4Q1Ma5ur6E+40ucNafiz4XLQ@mail.gmail.com>
References: <CAOypoo5AxmBBH68pK3eT11LFxE4Q1Ma5ur6E+40ucNafiz4XLQ@mail.gmail.com>
Message-ID: <1311490730-sup-7325@a4cdc57da8f33135>

Excerpts from Emeka's message of Sun Jul 24 02:56:02 -0400 2011:
> Hello All,
> 
> I am putting up a simple game .. the game is about manipulation. If the gets
> through level one ... I have to change the word with another...
> 
> Am I going to destroy level window and build level 2 or is there a way to
> just adjust the word (I used labels)
> 

When working with tkinter, http://effbot.org/tkinterbook/ will likely be your
best friend. Specifically, you're going to want 

your_label1.config(text="New word!")
your_label2.config(text="Another!")
-- 
Corey Richardson
  "Those who deny freedom to others, deserve it not for themselves"
     -- Abraham Lincoln
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 490 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20110724/adb44085/attachment.pgp>

From steve at pearwood.info  Sun Jul 24 09:07:14 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 24 Jul 2011 17:07:14 +1000
Subject: [Tutor] Don't understand this class/constructor call syntax
In-Reply-To: <20110723171954.M52452@csc.lsu.edu>
References: <20110722223458.M83643@csc.lsu.edu>	<4E2A3B53.3000409@pearwood.info>
	<20110723171954.M52452@csc.lsu.edu>
Message-ID: <4E2BC4A2.3030601@pearwood.info>

dave wrote:
> Thank you for the two explanations.  I think I have a good idea of what is
> going on now with the arguments and keyword arguments.
> 
> My only remaining question is the pad_for_usrp argument.  The default value is
> True so I thought it was a boolean and couldn't have anything to do with the
> "self<transmit_path>" that was passed to it.  However, I can probably puzzle
> that out by looking at how it's used in the code.  

I don't know why a transmit_path instance is being passed as a pad_* 
flag, but you may not be aware that in Python, any object can be used as 
if it were a boolean, not just True and False.

Generally, the rule is:

"something" is considered true-valued;
"nothing" is considered false-valued.

So, among the built-ins, we have "nothings" such as:

0
0.0
''  # empty string
[]  # empty list
{}  # empty dict
()  # empty tuple
set([])  # empty set
None

are all considered to be false in a boolean context. And we have 
"somethings", such as:

42
0.125
'x'
[None, 42, '*']
{0: None}
object()

etc. all considered to be true in a boolean context.

(Note that among strings, only the empty string counts as nothing. The 
strings 'nothing', 'empty', 'false', 'not a thing', 'nada', 'not a brass 
farthing', "dry as a dingo's donger" etc. are non-empty strings and 
therefore count as true-values.)

True and False are merely the canonical flags. In general, functions and 
methods are expected to be liberal in what they accept (any object can 
be used as if it were a boolean) and conservative in what they return 
(if returning a flag, you should return True/False, or 1/0 if you need 
to support *really* ancient versions of Python).


-- 
Steven


From emekamicro at gmail.com  Sun Jul 24 09:17:26 2011
From: emekamicro at gmail.com (Emeka)
Date: Sun, 24 Jul 2011 08:17:26 +0100
Subject: [Tutor] Question related to Tkinker
In-Reply-To: <1311490730-sup-7325@a4cdc57da8f33135>
References: <CAOypoo5AxmBBH68pK3eT11LFxE4Q1Ma5ur6E+40ucNafiz4XLQ@mail.gmail.com>
	<1311490730-sup-7325@a4cdc57da8f33135>
Message-ID: <CAOypoo65NGvXOseHP07iqqeUcQgvkYw8GKWYat4zno+Jz-EX4Q@mail.gmail.com>

for i,cha in enumerate(wordi):

    label = Label(root,  image=photoimage, text = cha)
    label.grid(row=1, column=i, columnspan=1, rowspan=1,sticky=W+E+N+S,
padx=0, pady=1)
    label1 = Label(root,  image=IMAGE)

I used grid ... Though I used labels, I was dealing only on character level.
So for word like "JAVA" . I will have  a row with four cells and each filled
with the individual character so that I could manipulate them individually.

Now, if I late have "ORACLE" in level 2.. I would want to use to write it in
the same row as above however with six cells.

I will check the link you posted




On Sun, Jul 24, 2011 at 8:00 AM, Corey Richardson <kb1pkl at aim.com> wrote:

> Excerpts from Emeka's message of Sun Jul 24 02:56:02 -0400 2011:
> > Hello All,
> >
> > I am putting up a simple game .. the game is about manipulation. If the
> gets
> > through level one ... I have to change the word with another...
> >
> > Am I going to destroy level window and build level 2 or is there a way to
> > just adjust the word (I used labels)
> >
>
> When working with tkinter, http://effbot.org/tkinterbook/ will likely be
> your
> best friend. Specifically, you're going to want
>
> your_label1.config(text="New word!")
> your_label2.config(text="Another!")
> --
> Corey Richardson
>  "Those who deny freedom to others, deserve it not for themselves"
>     -- Abraham Lincoln
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
*Satajanus  Nig. Ltd


*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110724/c9d2c10a/attachment-0001.html>

From __peter__ at web.de  Sun Jul 24 10:45:41 2011
From: __peter__ at web.de (Peter Otten)
Date: Sun, 24 Jul 2011 10:45:41 +0200
Subject: [Tutor] Question related to Tkinker
References: <CAOypoo5AxmBBH68pK3eT11LFxE4Q1Ma5ur6E+40ucNafiz4XLQ@mail.gmail.com>
	<1311490730-sup-7325@a4cdc57da8f33135>
	<CAOypoo65NGvXOseHP07iqqeUcQgvkYw8GKWYat4zno+Jz-EX4Q@mail.gmail.com>
Message-ID: <j0gm3m$n19$1@dough.gmane.org>

Emeka wrote:

> for i,cha in enumerate(wordi):
> 
>     label = Label(root,  image=photoimage, text = cha)
>     label.grid(row=1, column=i, columnspan=1, rowspan=1,sticky=W+E+N+S,
> padx=0, pady=1)
>     label1 = Label(root,  image=IMAGE)
> 
> I used grid ... Though I used labels, I was dealing only on character
> level.
> So for word like "JAVA" . I will have  a row with four cells and each
> filled with the individual character so that I could manipulate them
> individually.
> 
> Now, if I late have "ORACLE" in level 2.. I would want to use to write it
> in the same row as above however with six cells.

Keep the labels in a list and ensure that there are enough labels (the list 
is long enough) before you configure them to show the characters. 

Use the grid_forget() method to hide extra labels if the current word is 
shorter than a previous one.


From waynejwerner at gmail.com  Sun Jul 24 14:34:54 2011
From: waynejwerner at gmail.com (Wayne Werner)
Date: Sun, 24 Jul 2011 07:34:54 -0500
Subject: [Tutor] Don't understand this class/constructor call syntax
In-Reply-To: <4E2BC4A2.3030601@pearwood.info>
References: <20110722223458.M83643@csc.lsu.edu>
	<4E2A3B53.3000409@pearwood.info>
	<20110723171954.M52452@csc.lsu.edu> <4E2BC4A2.3030601@pearwood.info>
Message-ID: <CAPM86NdEZ77gtV_N7zLXPaWy3aGiT8+8sQ78t7A0WsLoW9ukzQ@mail.gmail.com>

On Sun, Jul 24, 2011 at 2:07 AM, Steven D'Aprano <steve at pearwood.info>wrote:

> (Note that among strings, only the empty string counts as nothing. The
> strings 'nothing', 'empty', 'false', 'not a thing', 'nada', 'not a brass
> farthing', "dry as a dingo's donger" etc. are non-empty strings and
> therefore count as true-values.)
>

Though just for completeness sake, you could do something like:

def mytest(string):
    if string.lower() in ("nothing", "empty", "false", "not a thing",
"nada", "not a brass farthing", "dry as a dingo's donger"):
        return False
    else:
        return True

if you were really interested in using values such as those.

Personally, just for kicks and giggles, when I write personal programs and I
ask for "Y/N" input, I'm fairly liberal - so instead of N you could input N,
No, nyet, no way, no thanks... you get the picture.

My 1 cent and pocket lint,
-Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110724/bfaced0c/attachment.html>

From redacted@example.com  Sun Jul 24 22:59:38 2011
From: redacted@example.com (Alexander Quest)
Date: Sun, 24 Jul 2011 13:59:38 -0700
Subject: [Tutor] Basic program question
Message-ID: <CAHgjEe1-RwQU-3V8dP16i9LZ+qSMzpEsdZ0mfqA0hczSVziuPw@mail.gmail.com>

Hello- I am running Python v 3.1.1. As an exercise, I wrote a simple coin
flipper program, where the computer flips a coin 100 times and then prints
out the number of heads and tails. My program crashes immediately if I run
it normally through the command line, but if I go to "Run- Run Module," it
seems to work just fine. I can't seem to figure out why. I've pasted the
relevant code below- any help will be greatly appreciated. Thanks!

import random
print("\tWelcome to the 'Coin Flipper' program!")

counter = 0
heads = 0
tails = 0

while counter < 100:
    the_number = random.randint(1, 2)
    if the_number == 1:
        heads += 1
    else:
        tails += 1

    counter += 1

print("\nI flipped the coint 100 times.")
print("It came up heads", heads, "times and tails", tails, "times.")

print("\n\nPress the enter key to exit.")

_________________

-Alex
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110724/959c5d90/attachment.html>

From waynejwerner at gmail.com  Sun Jul 24 23:57:07 2011
From: waynejwerner at gmail.com (Wayne Werner)
Date: Sun, 24 Jul 2011 16:57:07 -0500
Subject: [Tutor] Basic program question
In-Reply-To: <CAHgjEe1-RwQU-3V8dP16i9LZ+qSMzpEsdZ0mfqA0hczSVziuPw@mail.gmail.com>
References: <CAHgjEe1-RwQU-3V8dP16i9LZ+qSMzpEsdZ0mfqA0hczSVziuPw@mail.gmail.com>
Message-ID: <CAPM86Neh=0zg_AQdLgwh+gc=ZBpP3uBVMH2ZJJ0SSwsfS163HA@mail.gmail.com>

On Sun, Jul 24, 2011 at 3:59 PM, Alexander Quest <redacted@example.com>wrote:

> My program crashes immediately if I run it normally through the command
> line,


Is there a traceback associated? Those usually help a lot

-Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110724/9d81a91d/attachment.html>

From thisisonlyatest at gmx.com  Mon Jul 25 01:21:58 2011
From: thisisonlyatest at gmx.com (brandon w)
Date: Sun, 24 Jul 2011 19:21:58 -0400
Subject: [Tutor] Running Python in script vs. Idle
Message-ID: <4E2CA916.9010507@gmx.com>

Python version 2.6.6

I wrote this in Idle and ran it in Idle and it worked fine.

class ExClass:
     eyes = "brown"
     age = 99
     height = '5\'11'
     def thisMethod(self):
         return 'This method works.'

This is me running it in Idle.

 >>> ExClass
*<class __main__.ExClass at 0xb5aec2fc>*
 >>> x = ExClass()
 >>> x.eyes
*'brown'*
 >>> x.age
*99*
 >>> x.height
*"5'11"*
 >>> x.thisMethod()
*'This method works.'*

Then I try to run it from a script in Gnome-terminal and it does not 
run. I do not get output. I have to add print. to get any output like this:

#!/usr/bin/python

class ExClass:
     eyes = "brown"
     age = 99
     height = '5\'11'
     def thisMethod(self):
         return 'This method works.'

x = ExClass()
x.eyes
x.age
x.height
x.thisMethod()
*print* x.thisMethod()

What is the difference? This is what was confusing me before.

Brandon


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110724/91ae698b/attachment.html>

From steve at pearwood.info  Mon Jul 25 01:23:48 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 25 Jul 2011 09:23:48 +1000
Subject: [Tutor] Basic program question
In-Reply-To: <CAHgjEe1-RwQU-3V8dP16i9LZ+qSMzpEsdZ0mfqA0hczSVziuPw@mail.gmail.com>
References: <CAHgjEe1-RwQU-3V8dP16i9LZ+qSMzpEsdZ0mfqA0hczSVziuPw@mail.gmail.com>
Message-ID: <4E2CA984.1020603@pearwood.info>

Alexander Quest wrote:
> Hello- I am running Python v 3.1.1. As an exercise, I wrote a simple coin
> flipper program, where the computer flips a coin 100 times and then prints
> out the number of heads and tails. My program crashes immediately if I run
> it normally through the command line, but if I go to "Run- Run Module," it
> seems to work just fine. I can't seem to figure out why. I've pasted the
> relevant code below- any help will be greatly appreciated. Thanks!


What do you mean, "crashes"? Do you get a segmentation error? A Python 
traceback? Computer hangs and you have to restart to recover? Something 
else?

What do you mean, "run it normally through the command line"?

What operating system are you using? What command are you using on the 
command line?

Since I love guessing games, I'm going to take a wild stab in the dark 
that you're using Linux, and you're done something like this:

[steve at sylar ~]$ echo "print('spam')" > spam.py  # make a Python script
[steve at sylar ~]$ cat spam.py
print('spam')
[steve at sylar ~]$ chmod u+x spam.py  # make it executable
[steve at sylar ~]$ ./spam.py
./spam.py: line 1: syntax error near unexpected token `'spam''
./spam.py: line 1: `print('spam')'

That's because you're trying to run it as a shell script. You need to 
add a hash-bang line to the file, or run it with Python:

[steve at sylar ~]$ python3 spam.py
spam


If that's not what you are doing, then we'll need more information to 
solve the problem.



-- 
Steven

From steve at pearwood.info  Mon Jul 25 01:28:19 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 25 Jul 2011 09:28:19 +1000
Subject: [Tutor] Running Python in script vs. Idle
In-Reply-To: <4E2CA916.9010507@gmx.com>
References: <4E2CA916.9010507@gmx.com>
Message-ID: <4E2CAA93.6070803@pearwood.info>

brandon w wrote:

> I wrote this in Idle and ran it in Idle and it worked fine.
[...]
> Then I try to run it from a script in Gnome-terminal and it does not 
> run. I do not get output. I have to add print. to get any output like this:
[...]
> What is the difference? This is what was confusing me before.


As a convenience, the Python interactive interpreter prints the output 
of any line you give it. So a line like this:

x = 1+2

doesn't print anything, because the result is stored as x. But a line 
like this:

1+2

prints 3. This is *purely* a convenience feature, and it is only 
activated in the *interactive* interpreter. When running as a script, 
you need to explicitly call print to have things printed.

IDLE emulates that behaviour.



-- 
Steven

From steve at alchemy.com  Mon Jul 25 01:29:42 2011
From: steve at alchemy.com (Steve Willoughby)
Date: Sun, 24 Jul 2011 16:29:42 -0700
Subject: [Tutor] Running Python in script vs. Idle
In-Reply-To: <4E2CA916.9010507@gmx.com>
References: <4E2CA916.9010507@gmx.com>
Message-ID: <4E2CAAE6.5080709@alchemy.com>

On 24-Jul-11 16:21, brandon w wrote:
> Then I try to run it from a script in Gnome-terminal and it does not
> run. I do not get output. I have to add print. to get any output like this:

When you type a Python expression at the interactive prompt in IDLE or 
the python command-line interpreter, it will take the extra step of 
printing the value of that expression for you.

That's not otherwise how Python works.  Normally you have to use a print 
command (or print() function in Python 3.x) to actually see the output.


-- 
Steve Willoughby / steve at alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C

From steve at pearwood.info  Mon Jul 25 01:59:35 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 25 Jul 2011 09:59:35 +1000
Subject: [Tutor] Running Python in script vs. Idle
In-Reply-To: <4E2CAE0D.7070209@gmx.com>
References: <4E2CA916.9010507@gmx.com> <4E2CAA93.6070803@pearwood.info>
	<4E2CAE0D.7070209@gmx.com>
Message-ID: <4E2CB1E7.3010808@pearwood.info>

brandon w wrote:

> Thank you. I understand that this ( x = 1+2 ) assigns a variable to "x" 
> and will not print in Idle, but how would I get the 'class' that I 
> created to run from the script like it does in Idle? Will I have to put 
> print before everything I have to print?

Yes. If you want something printed, you have to print it.

In your script, you have:


# definition of ExClass not shown
x = ExClass()
x.eyes
x.age
x.height
x.thisMethod()
print x.thisMethod()


This creates an instance of ExClass, calls it "x". Then it retrieves the 
eyes, age and height from x, but does nothing with the results except 
immediately discard them. Then it calls thisMethod, and discards the 
result. Lastly, it calls thisMethod again and prints the result. That is 
the only thing that the script will output.

I recommend you do this instead:


# definition of ExClass not shown
x = ExClass()
print x.eyes, x.age, x.height
print x.thisMethod()




-- 
Steven

From thisisonlyatest at gmx.com  Mon Jul 25 02:10:54 2011
From: thisisonlyatest at gmx.com (brandon w)
Date: Sun, 24 Jul 2011 20:10:54 -0400
Subject: [Tutor] Running Python in script vs. Idle
In-Reply-To: <4E2CB1E7.3010808@pearwood.info>
References: <4E2CA916.9010507@gmx.com>
	<4E2CAA93.6070803@pearwood.info>	<4E2CAE0D.7070209@gmx.com>
	<4E2CB1E7.3010808@pearwood.info>
Message-ID: <4E2CB48E.5010705@gmx.com>

On 07/24/2011 07:59 PM, Steven D'Aprano wrote:
> brandon w wrote:
>
>> Thank you. I understand that this ( x = 1+2 ) assigns a variable to 
>> "x" and will not print in Idle, but how would I get the 'class' that 
>> I created to run from the script like it does in Idle? Will I have to 
>> put print before everything I have to print?
>
> Yes. If you want something printed, you have to print it.
>
> In your script, you have:
>
>
> # definition of ExClass not shown
> x = ExClass()
> x.eyes
> x.age
> x.height
> x.thisMethod()
> print x.thisMethod()
>
>
> This creates an instance of ExClass, calls it "x". Then it retrieves 
> the eyes, age and height from x, but does nothing with the results 
> except immediately discard them. Then it calls thisMethod, and 
> discards the result. Lastly, it calls thisMethod again and prints the 
> result. That is the only thing that the script will output.
>
> I recommend you do this instead:
>
>
> # definition of ExClass not shown
> x = ExClass()
> print x.eyes, x.age, x.height
> print x.thisMethod()
>
>
>
>
Thanks. I understand now.

From steve at pearwood.info  Mon Jul 25 02:26:11 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 25 Jul 2011 10:26:11 +1000
Subject: [Tutor] Don't understand this class/constructor call syntax
In-Reply-To: <20110724183239.M12544@csc.lsu.edu>
References: <20110722223458.M83643@csc.lsu.edu>	<4E2A3B53.3000409@pearwood.info>
	<20110723171954.M52452@csc.lsu.edu>
	<4E2BC4A2.3030601@pearwood.info>
	<20110724183239.M12544@csc.lsu.edu>
Message-ID: <4E2CB823.9050902@pearwood.info>

dave wrote:
> I was dimly aware of the functioning of booleans, but I see now that it
> doesn't specify an actual boolean type.  Still, the code confuses me.  Is the
> usage of pad_for_usrp consistent with it being treated as a boolean?  Why
> would the entire self reference be transmitted then?

Parameter passing in Python is fast -- the object (which may be large) 
is not copied unless you explicitly make a copy. So it is no faster to 
pass a big, complex object than a lightweight object like True or False.

(Implementation note: in CPython, the main Python implementation which 
you almost certainly are using, objects live in the heap and are passed 
around as pointers.)

The code you show isn't very illuminating as far as pad_for_usrp goes. 
All that happens is that it gets stored as an attribute, then later gets 
passed on again to another function or class:


> class ieee802_15_4_mod_pkts(gr.hier_block2):
...
>         self.pad_for_usrp = pad_for_usrp

>     def send_pkt(self, seqNr, addressInfo, payload='', eof=False):
...
>             pkt = make_ieee802_15_4_packet(FCF,
>                                            seqNr,
>                                            addressInfo,
>                                            payload,
>                                            self.pad_for_usrp)

So it's *consistent* with being used as a bool, or anything else for 
that matter! I expect that make_ieee802_15_4_packet may be the thing 
that actually does something useful with pad_for_usrp.

Another thing to look for is the transmit_path class itself. If it has a 
__len__, __bool__ or __nonzero__ method, then it has customized the way 
it appears as a boolean. If it has none of those methods, then it will 
always be considered true-valued, and I can't imagine why it is being 
used as pad_for_usrp instead of just passing True.

But without looking at the rest of the code, I can't really tell for sure.




-- 
Steven


From dave at csc.lsu.edu  Mon Jul 25 02:20:49 2011
From: dave at csc.lsu.edu (dave)
Date: Sun, 24 Jul 2011 19:20:49 -0500
Subject: [Tutor] Don't understand this class/constructor call syntax
In-Reply-To: <20110724183239.M12544@csc.lsu.edu>
References: <20110722223458.M83643@csc.lsu.edu>	<4E2A3B53.3000409@pearwood.info>
	<20110723171954.M52452@csc.lsu.edu>
	<4E2BC4A2.3030601@pearwood.info>
	<20110724183239.M12544@csc.lsu.edu>
Message-ID: <20110725001951.M43879@csc.lsu.edu>

I was dimly aware of the functioning of booleans, but I see now that it
doesn't specify an actual boolean type.  Still, the code confuses me.  Is the
usage of pad_for_usrp consistent with it being treated as a boolean?  Why
would the entire self reference be transmitted then?

Example code again:

class transmit_path(gr.top_block)
[...]
    self.packet_transmitter = ieee802_15_4_pkt.ieee802_15_4_mod_pkts(self,
spb=self._spb, msgq_limit=2)

The class from the ieee802_15_4_pkt module:

class ieee802_15_4_mod_pkts(gr.hier_block2):
    """
    IEEE 802.15.4 modulator that is a GNU Radio source.

    Send packets by calling send_pkt
    """
    def __init__(self, pad_for_usrp=True, *args, **kwargs): 
        """
	Hierarchical block for the 802_15_4 O-QPSK  modulation.

        Packets to be sent are enqueued by calling send_pkt.
        The output is the complex modulated signal at baseband.

        @param msgq_limit: maximum number of messages in message queue
        @type msgq_limit: int
        @param pad_for_usrp: If true, packets are padded such that they end up
a multiple of 128 samples

        See 802_15_4_mod for remaining parameters
        """
	try:
		self.msgq_limit = kwargs.pop('msgq_limit') 
	except KeyError:
		pass

	gr.hier_block2.__init__(self, "ieee802_15_4_mod_pkts",
		gr.io_signature(0, 0, 0),                     # Input
		gr.io_signature(1, 1, gr.sizeof_gr_complex))  # Output
        self.pad_for_usrp = pad_for_usrp

        # accepts messages from the outside world
        self.pkt_input = gr.message_source(gr.sizeof_char, self.msgq_limit)
        self.ieee802_15_4_mod = ieee802_15_4.ieee802_15_4_mod(self, *args,
**kwargs)
        self.connect(self.pkt_input, self.ieee802_15_4_mod, self)

    def send_pkt(self, seqNr, addressInfo, payload='', eof=False):
        """
        Send the payload.

        @param seqNr: sequence number of packet
        @type seqNr: byte
        @param addressInfo: address information for packet
        @type addressInfo: string
        @param payload: data to send
        @type payload: string
        """

        if eof:
            msg = gr.message(1) # tell self.pkt_input we're not sending any
more packets
        else:
            FCF = make_FCF()

            pkt = make_ieee802_15_4_packet(FCF,
                                           seqNr,
                                           addressInfo,
                                           payload,
                                           self.pad_for_usrp)
             #print "pkt =", packet_utils.string_to_hex_list(pkt), len(pkt)
            msg = gr.message_from_string(pkt)

        #ERROR OCCURS HERE (a few functions in while inserting onto the msg queue)
        self.pkt_input.msgq().insert_tail(msg)
------- End of Forwarded Message -------


From merrickdav at gmail.com  Mon Jul 25 04:19:20 2011
From: merrickdav at gmail.com (David Merrick)
Date: Mon, 25 Jul 2011 14:19:20 +1200
Subject: [Tutor] List problem
Message-ID: <CA+=McKbHPg5NzfuaGEjqusp-gpdnp3uHPFdyDarQmTgTVS7aDQ@mail.gmail.com>

class Node:
    def __init__(self,initdata):
        self.data = initdata
        self.next = None

    def getData(self):
        return self.data

    def getNext(self):
        return self.next

    def setdata(self,newData):
        self.data = newData

    def setNext(self,newnext):
       self.next = newnext

class UnorderedList:

    def __init__(self):
        self.head = None

    def isEmpty(self):
        return self.head == None

## Adds next item on to the head
    def add(self,item):
        temp = Node(item)
        temp.setNext(self.head)
        self.head = temp

    def length(self):
        current = self.head
        count = 0
        while current !=None:
            count = count + 1
            current = current.getNext()
        return count

    def search(self,item):
        current = self.head
        found = False
        while current != None and not found:
            if current.getData()== item:
                found =True
            else:
                current = current.getNext()
        return found


    def remove(self,item):
        '''Removes item from the List'''

        current = self.head
        previous = None
        found = False
        while not found:
            if current.getData() == item:
                found = True
            else:
                previous = current
                current = current.getNext()
        if previous == None:
            self.head = current.getNext()
        else:
            previous.setNext(current.getNext())

    def getIndex(self,item):
        current = self.head
        index = 0
        found = False
        while current != None and not found:
            if current.getData()== item:
                found = True
            else:
                current = current.getNext()
                index = index + 1
        return index

    def append(self,item):
         '''Adds an item to the end of the List'''

         current = self.head
         previous = None
         while current.getNext() != None:
             previous = current
             current = current.getNext()
         if current.getNext() == None:
             previous  = previous.setNext(current)
             current = current.setNext(item)


myList = UnorderedList()
myList.add(31)
myList.add(77)
myList.add(17)
myList.add(93)
myList.add(26)
myList.add(54)
print(myList.length())
myList.append(24)
print(myList.length())
myList.search(24)

Output

Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)]
Type "help", "copyright", "credits" or "license" for more information.
>>> [evaluate unorderedList.py]
6
builtins.AttributeError: 'int' object has no attribute 'getNext'
>>>

What do I need to do the append method to fix it?

-- 
Dave Merrick

merrickdav at gmail.com

Ph   03 3423 121
Cell 027 3089 169
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110725/190ed97d/attachment-0001.html>

From bgailer at gmail.com  Mon Jul 25 05:35:54 2011
From: bgailer at gmail.com (bob gailer)
Date: Sun, 24 Jul 2011 23:35:54 -0400
Subject: [Tutor] List problem
In-Reply-To: <CA+=McKbHPg5NzfuaGEjqusp-gpdnp3uHPFdyDarQmTgTVS7aDQ@mail.gmail.com>
References: <CA+=McKbHPg5NzfuaGEjqusp-gpdnp3uHPFdyDarQmTgTVS7aDQ@mail.gmail.com>
Message-ID: <4E2CE49A.3010708@gmail.com>

I have no desire to wade through all that code. Please post the entire 
traceback.


On 7/24/2011 10:19 PM, David Merrick wrote:
> class Node:
>     def __init__(self,initdata):
>         self.data = initdata
>         self.next = None
>
>     def getData(self):
>         return self.data
>
>     def getNext(self):
>         return self.next
>
>     def setdata(self,newData):
>         self.data = newData
>
>     def setNext(self,newnext):
>        self.next = newnext
>
> class UnorderedList:
>
>     def __init__(self):
>         self.head = None
>
>     def isEmpty(self):
>         return self.head == None
>
> ## Adds next item on to the head
>     def add(self,item):
>         temp = Node(item)
>         temp.setNext(self.head)
>         self.head = temp
>
>     def length(self):
>         current = self.head
>         count = 0
>         while current !=None:
>             count = count + 1
>             current = current.getNext()
>         return count
>
>     def search(self,item):
>         current = self.head
>         found = False
>         while current != None and not found:
>             if current.getData()== item:
>                 found =True
>             else:
>                 current = current.getNext()
>         return found
>
>
>     def remove(self,item):
>         '''Removes item from the List'''
>
>         current = self.head
>         previous = None
>         found = False
>         while not found:
>             if current.getData() == item:
>                 found = True
>             else:
>                 previous = current
>                 current = current.getNext()
>         if previous == None:
>             self.head = current.getNext()
>         else:
>             previous.setNext(current.getNext())
>
>     def getIndex(self,item):
>         current = self.head
>         index = 0
>         found = False
>         while current != None and not found:
>             if current.getData()== item:
>                 found = True
>             else:
>                 current = current.getNext()
>                 index = index + 1
>         return index
>
>     def append(self,item):
>          '''Adds an item to the end of the List'''
>
>          current = self.head
>          previous = None
>          while current.getNext() != None:
>              previous = current
>              current = current.getNext()
>          if current.getNext() == None:
>              previous  = previous.setNext(current)
>              current = current.setNext(item)
>
>
> myList = UnorderedList()
> myList.add(31)
> myList.add(77)
> myList.add(17)
> myList.add(93)
> myList.add(26)
> myList.add(54)
> print(myList.length())
> myList.append(24)
> print(myList.length())
> myList.search(24)
>
> Output
>
> Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)]
> Type "help", "copyright", "credits" or "license" for more information.
> >>> [evaluate unorderedList.py]
> 6
> builtins.AttributeError: 'int' object has no attribute 'getNext'
> >>>
>
> What do I need to do the append method to fix it?
>
> -- 
> Dave Merrick
>
> merrickdav at gmail.com <mailto:merrickdav at gmail.com>
>
> Ph   03 3423 121
> Cell 027 3089 169
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


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

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110724/4a15460a/attachment.html>

From andreengels at gmail.com  Mon Jul 25 07:57:19 2011
From: andreengels at gmail.com (Andre Engels)
Date: Mon, 25 Jul 2011 07:57:19 +0200
Subject: [Tutor] List problem
In-Reply-To: <CA+=McKbHPg5NzfuaGEjqusp-gpdnp3uHPFdyDarQmTgTVS7aDQ@mail.gmail.com>
References: <CA+=McKbHPg5NzfuaGEjqusp-gpdnp3uHPFdyDarQmTgTVS7aDQ@mail.gmail.com>
Message-ID: <CAGzCZ0o+2AYh_NdvfTpT6JxFhB1enJmzLQq=qQJNhKZBLu7SyA@mail.gmail.com>

On Mon, Jul 25, 2011 at 4:19 AM, David Merrick <merrickdav at gmail.com> wrote:


>     def append(self,item):
>          '''Adds an item to the end of the List'''
>
>          current = self.head
>          previous = None
>          while current.getNext() != None:
>              previous = current
>              current = current.getNext()
>          if current.getNext() == None:
>              previous  = previous.setNext(current)
>              current = current.setNext(item)
>

current is here the first element of your list. This element does not have a
getNext() method. Instead, if you want to use this system, you'll have to
use a (probably re-defined) getNext() method of your list class itself.

-- 
Andr? Engels, andreengels at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110725/51123049/attachment.html>

From __peter__ at web.de  Mon Jul 25 10:07:13 2011
From: __peter__ at web.de (Peter Otten)
Date: Mon, 25 Jul 2011 10:07:13 +0200
Subject: [Tutor] List problem
References: <CA+=McKbHPg5NzfuaGEjqusp-gpdnp3uHPFdyDarQmTgTVS7aDQ@mail.gmail.com>
Message-ID: <j0j87d$1rf$1@dough.gmane.org>

David Merrick wrote:

>     def append(self,item):
>          '''Adds an item to the end of the List'''
> 
>          current = self.head
>          previous = None
>          while current.getNext() != None:
>              previous = current
>              current = current.getNext()
>          if current.getNext() == None:
>              previous  = previous.setNext(current)
>              current = current.setNext(item)

> myList.append(24)

Your append() method expects item to be a Node instance, so you have to wrap 
your data (24 in the example) into a Node

myList.append(Node(24))

or modify append() accordingly. Note that there is at least one other 
problem with your append() implementation: you cannot append to an empty 
UnorderedList because you don't handle the case where self.head is None.

Stylistically your code looks like a literal translation from Java; in 
Python it is good practice to avoid getter/setter methods and use attributes 
(or properties) instead. Also, we have a cool way to implement iteration: 
generators.

#untested
class UnorderedList(object):
    def __iter__(self):
        current = self.head
        while current is not None:
            yield current.data

You can then write

print 24 in myList

instead of

print myList.search(24)

In idiomatic Python you'd call the length() method __len__() and invoke it 
as

print len(myList)


From timomlists at gmail.com  Mon Jul 25 10:30:04 2011
From: timomlists at gmail.com (Timo)
Date: Mon, 25 Jul 2011 10:30:04 +0200
Subject: [Tutor] Basic program question
In-Reply-To: <CAHgjEe1-RwQU-3V8dP16i9LZ+qSMzpEsdZ0mfqA0hczSVziuPw@mail.gmail.com>
References: <CAHgjEe1-RwQU-3V8dP16i9LZ+qSMzpEsdZ0mfqA0hczSVziuPw@mail.gmail.com>
Message-ID: <4E2D298C.4040402@gmail.com>

On 24-07-11 22:59, Alexander Quest wrote:
> Hello- I am running Python v 3.1.1. As an exercise, I wrote a simple 
> coin flipper program, where the computer flips a coin 100 times and 
> then prints out the number of heads and tails. My program crashes 
> immediately if I run it normally through the command line, but if I go 
> to "Run- Run Module," it seems to work just fine. I can't seem to 
> figure out why. I've pasted the relevant code below- any help will be 
> greatly appreciated. Thanks!
If I read it correctly, you probably *think* it crashes because when you 
run this script from the terminal, it will close right after it finishes 
so you can't see any output.
See the last line for the solution.

>
> import random
> print("\tWelcome to the 'Coin Flipper' program!")
>
> counter = 0
> heads = 0
> tails = 0
>
> while counter < 100:
>     the_number = random.randint(1, 2)
>     if the_number == 1:
>         heads += 1
>     else:
>         tails += 1
>
>     counter += 1
>
> print("\nI flipped the coint 100 times.")
> print("It came up heads", heads, "times and tails", tails, "times.")
>
> print("\n\nPress the enter key to exit.")
Change this line to:
input("\n\nPress any key to exit.")

Cheers,
Timo

>
> _________________
>
> -Alex
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From naheedcse at gmail.com  Mon Jul 25 17:17:19 2011
From: naheedcse at gmail.com (naheed arafat)
Date: Mon, 25 Jul 2011 21:17:19 +0600
Subject: [Tutor] Copying Variables
In-Reply-To: <4E2BA692.3030601@pearwood.info>
References: <002101cc49ba$515b89c0$f4129d40$@gmail.com>
	<4E2BA692.3030601@pearwood.info>
Message-ID: <CA+Tz84=E6i0To3veV_BQwdqMm9d4ZLZkK=BdktY2-fv20WaY7A@mail.gmail.com>

I got a question in this context.
suppose
a={'a': 3, 'b': [1, 2], 5: 100}
------------------b=a --------------    vs----------
b=copy.copy(a)------------
----------------------------------------------------
b[5]=6   ----------------------------------------      b[5]=6
output: -----------------------------------------      output:
b={'a': 3, 'b': [1, 2], 5: 6}-------------------     b={'a': 3, 'b': [1, 2],
5: 6}
a={'a': 3, 'b': [1, 2], 5: 6} -------------------    a={'a': 3, 'b': [1, 2],
5: 100}
that means b=a & b=copy.copy(a) aren't the same.
but
b['b'].append(3)
output:
b={'a': 3, 'b': [1, 2, 3], 5: 100}--------------b={'a': 3, 'b': [1, 2, 3],
5: 100}
a={'a': 3, 'b': [1, 2, 3], 5: 100}--------------a={'a': 3, 'b': [1, 2, 3],
5: 100}
now doesn't it mean that b=a & b=copy.copy(a) both are same?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110725/7702794b/attachment.html>

From sander.sweers at gmail.com  Mon Jul 25 17:43:30 2011
From: sander.sweers at gmail.com (Sander Sweers)
Date: Mon, 25 Jul 2011 17:43:30 +0200
Subject: [Tutor] Copying Variables
In-Reply-To: <CA+Tz84=E6i0To3veV_BQwdqMm9d4ZLZkK=BdktY2-fv20WaY7A@mail.gmail.com>
References: <002101cc49ba$515b89c0$f4129d40$@gmail.com>
	<4E2BA692.3030601@pearwood.info>
	<CA+Tz84=E6i0To3veV_BQwdqMm9d4ZLZkK=BdktY2-fv20WaY7A@mail.gmail.com>
Message-ID: <CACipEsh5t4GKefjsghSRXt1ZLXWdVtZMZojwpFVcGodKoM7UeA@mail.gmail.com>

On 25 July 2011 17:17, naheed arafat <naheedcse at gmail.com> wrote:
> I got a question in this context.
> suppose
> a={'a': 3, 'b': [1, 2], 5: 100}
> ------------------b=a --------------??? vs----------
> b=copy.copy(a)------------
> ----------------------------------------------------
> b[5]=6?? ----------------------------------------????? b[5]=6
> output: -----------------------------------------????? output:
> b={'a': 3, 'b': [1, 2], 5: 6}-------------------???? b={'a': 3, 'b': [1, 2],
> 5: 6}
> a={'a': 3, 'b': [1, 2], 5: 6} -------------------??? a={'a': 3, 'b': [1, 2],
> 5: 100}
> that means b=a & b=copy.copy(a) aren't the same.
> but
> b['b'].append(3)
> output:
> b={'a': 3, 'b': [1, 2, 3], 5: 100}--------------b={'a': 3, 'b': [1, 2, 3],
> 5: 100}
> a={'a': 3, 'b': [1, 2, 3], 5: 100}--------------a={'a': 3, 'b': [1, 2, 3],
> 5: 100}
> now doesn't it mean that b=a & b=copy.copy(a) both are same?

No, b=a makes a new reference to the _same_ dict object.
b=copy.copy(a) creates a new dict object b. However it does not make a
copy of the *contents* of the dict object. To make a copy of the
contents of the dict use cop.deepcopy(). Play around with id() on the
a, b and their contents.

But do note that cpython caches small integers so the integer 3 will
have the same id (thus it is the same object).

greets
Sander

From ramit.prasad at jpmchase.com  Mon Jul 25 17:45:29 2011
From: ramit.prasad at jpmchase.com (Prasad, Ramit)
Date: Mon, 25 Jul 2011 11:45:29 -0400
Subject: [Tutor] Copying Variables
In-Reply-To: <CA+Tz84=E6i0To3veV_BQwdqMm9d4ZLZkK=BdktY2-fv20WaY7A@mail.gmail.com>
References: <002101cc49ba$515b89c0$f4129d40$@gmail.com>
	<4E2BA692.3030601@pearwood.info>
	<CA+Tz84=E6i0To3veV_BQwdqMm9d4ZLZkK=BdktY2-fv20WaY7A@mail.gmail.com>
Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA67BD0E4@EMARC112VS01.exchad.jpmchase.net>

From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of naheed arafat
Sent: Monday, July 25, 2011 10:17 AM
To: Steven D'Aprano
Cc: Tutor at python.org
Subject: Re: [Tutor] Copying Variables

I got a question in this context.
suppose
a={'a': 3, 'b': [1, 2], 5: 100}
------------------b=a --------------    vs----------   b=copy.copy(a)------------
----------------------------------------------------
b[5]=6   ----------------------------------------      b[5]=6
output: -----------------------------------------      output:
b={'a': 3, 'b': [1, 2], 5: 6}-------------------     b={'a': 3, 'b': [1, 2], 5: 6}
a={'a': 3, 'b': [1, 2], 5: 6} -------------------    a={'a': 3, 'b': [1, 2], 5: 100}
that means b=a & b=copy.copy(a) aren't the same.
but
b['b'].append(3)
output:
b={'a': 3, 'b': [1, 2, 3], 5: 100}--------------b={'a': 3, 'b': [1, 2, 3], 5: 100}
a={'a': 3, 'b': [1, 2, 3], 5: 100}--------------a={'a': 3, 'b': [1, 2, 3], 5: 100}
now doesn't it mean that b=a & b=copy.copy(a) both are same?
=========================================================================

Copy.copy is copies only a single level (shallow); it creates a new dictionary object but the key/values of the new dictionary object are the same as the source. In this case, the anonymous list with [1,2] is shared between both instances and a modification to one will modify it for any object containing a reference to that list. On the other hand, if you use copy.deepcopy you will get a different result because it will create a copy of the anonymous, internal list as well as the dictionary containing it.

>>> a={'a': 3, 'b': [1, 2], 5: 100}
>>> import copy
>>> b = copy.copy(a)
>>> b['b'].append(3)
>>> b
{'a': 3, 'b': [1, 2, 3], 5: 100}
>>> a
{'a': 3, 'b': [1, 2, 3], 5: 100}
>>> b = copy.deepcopy(a)
>>> a
{'a': 3, 'b': [1, 2, 3], 5: 100}
>>> b
{'a': 3, 'b': [1, 2, 3], 5: 100}
>>> b['b'].append(3)
>>> a
{'a': 3, 'b': [1, 2, 3], 5: 100}
>>> b
{'a': 3, 'b': [1, 2, 3, 3], 5: 100}






Ramit


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




This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase &
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110725/d6e0b824/attachment-0001.html>

From wallenpb at gmail.com  Tue Jul 26 02:27:23 2011
From: wallenpb at gmail.com (Bill Allen)
Date: Mon, 25 Jul 2011 19:27:23 -0500
Subject: [Tutor] [python-win32] Good Book
In-Reply-To: <4E2425E0.1020702@gmail.com>
References: <CAFZKqUBgyCLvD5WcDSAgm00oOSnBiny09R7z7_cEG7uex2HspA@mail.gmail.com>
	<4E2425E0.1020702@gmail.com>
Message-ID: <CACrcdXuNoMSicGB57Pohdc+u+S8UvA0sPxVSzuvuLkzZj9gDsA@mail.gmail.com>

>
> Dear All Pythonist,
>
>  I'm strarting learn python programming and I have been found many
> resources on it but I have a problem. I don't know, what is the best
> complete book for new learner like me.
>
>  I need your recommendation, thanks before . . .
>
>  Ryan,

Here some more good free book resources for Python programming,  by the same
author.  The website provides both HTML and PDF versions.

Book 1:  Intended for beginners and non-programmers (I think it is good,
even for programmers even if some material might be a little bit
elementary.  Certainly good if one has not programmed in a while, for
review.):
http://homepage.mac.com/s_lott/books/nonprogrammer.html#book-nonprogrammer

Book 2:  Intended for more experienced programmers:
http://homepage.mac.com/s_lott/books/python.html#book-python

Book 3:  Specifically focuses on OOP design, two editions of this book for
Python and Java:
http://homepage.mac.com/s_lott/books/oodesign.html#book-oodesign

--Bill Allen
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110725/66c9d560/attachment.html>

From mark at curphey.com  Tue Jul 26 02:34:29 2011
From: mark at curphey.com (Mark Curphey)
Date: Mon, 25 Jul 2011 17:34:29 -0700
Subject: [Tutor] [python-win32] Good Book
In-Reply-To: <CACrcdXuNoMSicGB57Pohdc+u+S8UvA0sPxVSzuvuLkzZj9gDsA@mail.gmail.com>
References: <CAFZKqUBgyCLvD5WcDSAgm00oOSnBiny09R7z7_cEG7uex2HspA@mail.gmail.com>
	<4E2425E0.1020702@gmail.com>
	<CACrcdXuNoMSicGB57Pohdc+u+S8UvA0sPxVSzuvuLkzZj9gDsA@mail.gmail.com>
Message-ID: <DB22ADA4-99A1-42C9-8371-24DC20C6A05B@curphey.com>

I strongly recommend Thinking in Python - http://www.greenteapress.com/thinkpython/thinkpython.html

I recently wrote a blog about my experiences learning - http://www.curphey.com/2011/07/learn-core-python-in-a-week-my-way/

Sent from my iPhone

On Jul 25, 2011, at 5:27 PM, Bill Allen <wallenpb at gmail.com> wrote:

>> Dear All Pythonist,
>> 
>> I'm strarting learn python programming and I have been found many resources on it but I have a problem. I don't know, what is the best complete book for new learner like me.
>> 
>> I need your recommendation, thanks before . . .
>> 
> Ryan,
> 
> Here some more good free book resources for Python programming,  by the same author.  The website provides both HTML and PDF versions.
> 
> Book 1:  Intended for beginners and non-programmers (I think it is good, even for programmers even if some material might be a little bit elementary.  Certainly good if one has not programmed in a while, for review.):
> http://homepage.mac.com/s_lott/books/nonprogrammer.html#book-nonprogrammer
> 
> Book 2:  Intended for more experienced programmers:
> http://homepage.mac.com/s_lott/books/python.html#book-python
> 
> Book 3:  Specifically focuses on OOP design, two editions of this book for Python and Java:
> http://homepage.mac.com/s_lott/books/oodesign.html#book-oodesign
> 
> --Bill Allen
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110725/bc2fcebd/attachment.html>

From dave at csc.lsu.edu  Tue Jul 26 03:18:02 2011
From: dave at csc.lsu.edu (dave)
Date: Mon, 25 Jul 2011 20:18:02 -0500
Subject: [Tutor] Don't understand this class/constructor call syntax
In-Reply-To: <4E2CB823.9050902@pearwood.info>
References: <20110722223458.M83643@csc.lsu.edu>	<4E2A3B53.3000409@pearwood.info>
	<20110723171954.M52452@csc.lsu.edu>
	<4E2BC4A2.3030601@pearwood.info>
	<20110724183239.M12544@csc.lsu.edu>
	<4E2CB823.9050902@pearwood.info>
Message-ID: <20110726011305.M72864@csc.lsu.edu>

Is it even possible to replace the implicit self argument of the initializer
by passing something else?  If so, what would be the syntax.

If you want to look at the code its all here:

https://www.cgran.org/browser/projects/ucla_zigbee_phy/trunk/src

The cc2420_txtest.py is in ./examples and the corresponding ieee802_15_4*.py
files are in ./python (lib contains C++ code accessed via SWIG).

I can probably puzzle it out with this info eventually, but if you want to
comment further feel free.

Thanks for your help

Dave



On Mon, 25 Jul 2011 10:26:11 +1000, Steven D'Aprano wrote
> dave wrote:
> > I was dimly aware of the functioning of booleans, but I see now that it
> > doesn't specify an actual boolean type.  Still, the code confuses me.  Is the
> > usage of pad_for_usrp consistent with it being treated as a boolean?  Why
> > would the entire self reference be transmitted then?
> 
> Parameter passing in Python is fast -- the object (which may be 
> large) is not copied unless you explicitly make a copy. So it is no 
> faster to pass a big, complex object than a lightweight object like 
> True or False.
> 
> (Implementation note: in CPython, the main Python implementation 
> which you almost certainly are using, objects live in the heap and 
> are passed around as pointers.)
> 
> The code you show isn't very illuminating as far as pad_for_usrp 
> goes. All that happens is that it gets stored as an attribute, then 
> later gets passed on again to another function or class:
> 
> > class ieee802_15_4_mod_pkts(gr.hier_block2):
> ...
> >         self.pad_for_usrp = pad_for_usrp
> 
> >     def send_pkt(self, seqNr, addressInfo, payload='', eof=False):
> ...
> >             pkt = make_ieee802_15_4_packet(FCF,
> >                                            seqNr,
> >                                            addressInfo,
> >                                            payload,
> >                                            self.pad_for_usrp)
> 
> So it's *consistent* with being used as a bool, or anything else for 
> that matter! I expect that make_ieee802_15_4_packet may be the thing 
> that actually does something useful with pad_for_usrp.
> 
> Another thing to look for is the transmit_path class itself. If it 
> has a __len__, __bool__ or __nonzero__ method, then it has 
> customized the way it appears as a boolean. If it has none of those 
> methods, then it will always be considered true-valued, and I can't 
> imagine why it is being used as pad_for_usrp instead of just passing 
> True.
> 
> But without looking at the rest of the code, I can't really tell for 
> sure.
> 
> -- 
> Steven
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From lmergner at gmail.com  Tue Jul 26 07:58:18 2011
From: lmergner at gmail.com (Luke Thomas Mergner)
Date: Tue, 26 Jul 2011 01:58:18 -0400
Subject: [Tutor] Logger object not passed between modules
Message-ID: <E7CA0C06-D229-4941-BD8A-2ED559179713@gmail.com>

Hi,

Python 2.7.2
wxPython 2.9.1.1
OS X 10.7

I am very new to Python and programming, basically just a curious hobbyist.  I am building a learning app that hopefully will include a wxPython GUI.  Right now I am trying to understand my code better by including print statements.  Now I know that I could just print to the terminal, but I thought 'why not try this nice little logger class.'  And it works perfectly in the main class App(wx.App), but I can't seem to pass the same logger object to the imported modules.  I'm verifying this by printing the logger object to terminal (stdout?).  I've spent close to 6 hours trying to figure this out, and I need some help.

The logger object is created within a function in the main app class.  Is this wrong? I thought that logger ensured the same object is used by both classes.  The logger.getLogger(__name__) doesn't set anything other than the name used to describe the source of the message, so how do I make sure I'm using the same log object?  I assume the problem is either scope (the log has to be in the module, not the class) or passing the object properly, neither of which I"m very comfortable with obviously.

Thanks in advance.  Code snippets and prints follow.
Luke



# File / module one.
import FrameMaker # instantiates the subclassed wx.Frame object and fills it.
class App(wx.App):
	def __init__(self)
		self.logger = self.Log()

	def Log(self):
		appName = 'wxNew'  # I thought this line would make it easier to 'refactor' I hear people care about that.
		logfile = ''.join([appName, '.log']) #Look, I learned to use the .join() function!
		if not os.path.exists(log file):  # some examples I saw suggest logger handles this file check.
			f = open(logfile, 'w')
			f.close()
		logger = logging.getLogger('Main')
		logger.setLevel(logging.DEBUG)
		fh = logging.FileHandler(logfile)
		fh.setLevel(logging.DEBUG) # If I only want one log, do I need to create a special handler 'fh'?
		format = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
		fh.setFormatter(format)
		logger.addHandler(fh)
		logger.info('Starting log... ')
		return logger


# File / Module two
class myFrame(wx.Frame):
    def __init__(self, parent, id=-1, label="", size=(300, 500)):
    	#set the name of the logger.
    	self.logger = logging.getLogger('Frame') # The argument shouldn't matter, as I follow the examples.
    	print self.logger
    	self.logger.info('In frame __init__, the size is : ', self.GetSize) 

$ python app.py
<logging.Logger object at 0x105a1a110>
<logging.Logger object at 0x105a1a450>

--The log prints --
2011-07-26 01:39:07,642 - Main - INFO - Starting log... 
2011-07-26 01:39:11,078 - Main - INFO - Shutting down main app.


Luke Thomas Mergner
Mechanicsville, MD
lmergner.blogspot.com
lmergner at gmail.com


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110726/db82ba94/attachment-0001.html>

From alan.gauld at btinternet.com  Mon Jul 25 09:08:54 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 25 Jul 2011 08:08:54 +0100
Subject: [Tutor] Don't understand this class/constructor call syntax
In-Reply-To: <20110726011305.M72864@csc.lsu.edu>
References: <20110722223458.M83643@csc.lsu.edu>	<4E2A3B53.3000409@pearwood.info>	<20110723171954.M52452@csc.lsu.edu>	<4E2BC4A2.3030601@pearwood.info>	<20110724183239.M12544@csc.lsu.edu>	<4E2CB823.9050902@pearwood.info>
	<20110726011305.M72864@csc.lsu.edu>
Message-ID: <4E2D1686.8090109@btinternet.com>

dave wrote:
> Is it even possible to replace the implicit self argument of the initializer
> by passing something else?  If so, what would be the syntax.

Im not sure  this is what you mean but...

When you call a method on an object like:

class MyClass:
    def aMethod(self,spam): pass

anObject= MyClass()
anObject.aMethod(42)

You could replace the last line with:

MyClass.aMethod(anObject, 42)

This explicitly specifies the value of self in aMethod()

So you could in theory pass any object into the method,
although in most cases it would result in an error.


Is that what you mean?

Alan G.

From alan.gauld at btinternet.com  Mon Jul 25 09:08:54 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 25 Jul 2011 08:08:54 +0100
Subject: [Tutor] Don't understand this class/constructor call syntax
In-Reply-To: <20110726011305.M72864@csc.lsu.edu>
References: <20110722223458.M83643@csc.lsu.edu>	<4E2A3B53.3000409@pearwood.info>	<20110723171954.M52452@csc.lsu.edu>	<4E2BC4A2.3030601@pearwood.info>	<20110724183239.M12544@csc.lsu.edu>	<4E2CB823.9050902@pearwood.info>
	<20110726011305.M72864@csc.lsu.edu>
Message-ID: <4E2D1686.8090109@btinternet.com>

dave wrote:
> Is it even possible to replace the implicit self argument of the initializer
> by passing something else?  If so, what would be the syntax.

Im not sure  this is what you mean but...

When you call a method on an object like:

class MyClass:
    def aMethod(self,spam): pass

anObject= MyClass()
anObject.aMethod(42)

You could replace the last line with:

MyClass.aMethod(anObject, 42)

This explicitly specifies the value of self in aMethod()

So you could in theory pass any object into the method,
although in most cases it would result in an error.


Is that what you mean?

Alan G.


From wprins at gmail.com  Tue Jul 26 13:12:51 2011
From: wprins at gmail.com (Walter Prins)
Date: Tue, 26 Jul 2011 12:12:51 +0100
Subject: [Tutor] Logger object not passed between modules
In-Reply-To: <E7CA0C06-D229-4941-BD8A-2ED559179713@gmail.com>
References: <E7CA0C06-D229-4941-BD8A-2ED559179713@gmail.com>
Message-ID: <CANLXbfD75LT_e4G3gAB0EjqVoSx=LCq-+FgieFb=gTm0S8PfiQ@mail.gmail.com>

Hi Luke,

On 26 July 2011 06:58, Luke Thomas Mergner <lmergner at gmail.com> wrote:

> The logger object is created within a function in the main app class.  Is
> this wrong? I thought that logger ensured the same object is used by both
> classes.  The logger.getLogger(__name__) doesn't set anything other than the
> name used to describe the source of the message, so how do I make sure I'm
> using the same log object?  I assume the problem is either scope (the log
> has to be in the module, not the class) or passing the object properly,
> neither of which I"m very comfortable with obviously.
>


With the caveat that I'm not exactly a logging expert in Python, let me
submit the following observations:
1) You should generally only create logger objects inside modules (whether
main or otherwise) for module specific logging.  Such a created logger
should not be shared with other modules. So yes your current approach at the
very least doesn't go by the the logging module's normal usage pattern(s).

2) If you don't care about module specific logging (and I suggest you do
not, at this stage of your learning), then you should ignore creating your
own logger objects and instead, simply directly log using the logging
*module* (which contains a share loggger object already.)

3) See the section entitled "Logging from multiple modules" here:
http://docs.python.org/howto/logging.html for an example of this.
It demonstrates how you can do some basic configuration of your log in the
main application module and also log from other modules, all without having
to explicitly create your own (module specific) logger objects.

HTH,

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110726/18a45e8d/attachment.html>

From __peter__ at web.de  Tue Jul 26 13:40:03 2011
From: __peter__ at web.de (Peter Otten)
Date: Tue, 26 Jul 2011 13:40:03 +0200
Subject: [Tutor] Logger object not passed between modules
References: <E7CA0C06-D229-4941-BD8A-2ED559179713@gmail.com>
Message-ID: <j0m92b$8tn$1@dough.gmane.org>

Luke Thomas Mergner wrote:

> I am very new to Python and programming, basically just a curious
> hobbyist.  I am building a learning app that hopefully will include a
> wxPython GUI.  Right now I am trying to understand my code better by
> including print statements.  Now I know that I could just print to the
> terminal, but I thought 'why not try this nice little logger class.'  And
> it works perfectly in the main class App(wx.App), but I can't seem to pass
> the same logger object to the imported modules.  I'm verifying this by
> printing the logger object to terminal (stdout?).  I've spent close to 6
> hours trying to figure this out, and I need some help.
> 
> The logger object is created within a function in the main app class.  Is
> this wrong? I thought that logger ensured the same object is used by both
> classes.  The logger.getLogger(__name__) doesn't set anything other than
> the name used to describe the source of the message, so how do I make sure
> I'm using the same log object?  

No, the name is used to identify a logger; different names mean different 
loggers.

> I assume the problem is either scope (the
> log has to be in the module, not the class) or passing the object
> properly, neither of which I"m very comfortable with obviously.

Loggers are put into a hierarchy similar to a directory tree with the root 
logger at the top. By default the other loggers pass logging messages up to 
their parent so that all messages (or LogRecords) are eventually seen by the 
root logger. In most cases it is sufficient to handle them there, and the 
easiest way to add a suitable formatter and handler is 
logging.basicConfig():

>>> import logging
>>> class App:
...     def __init__(self):
...             self.logger = logging.getLogger("main")
...
>>> class Frame:
...     def __init__(self):
...             self.logger = logging.getLogger("frame")
...
>>> logging.basicConfig(level=logging.DEBUG, filename="tmp.log")
>>> app = App()
>>> frame = Frame()
>>> frame.logger.info("hello from frame")
>>> app.logger.info("hello from app")
>>> with open("tmp.log") as f: print f.read()
...
INFO:frame:hello from frame
INFO:main:hello from app



From 0101amt at gmail.com  Tue Jul 26 20:03:50 2011
From: 0101amt at gmail.com (amt)
Date: Tue, 26 Jul 2011 21:03:50 +0300
Subject: [Tutor] What's the difference between %s and %r?
In-Reply-To: <CAB6eaA72SikGtrxMJ+h8JSU7F5DpiCZYw+OovD5620n_nxQ1ew@mail.gmail.com>
References: <CAEQEn01bScZP1-Rh_dGdPwkt=R585q34o6tkZzK9S+0WjT9wfg@mail.gmail.com>
	<CAPM-O+xo9N6PCwLs0MC9nsyTCBYZ4iGz+nmm=i=DSSmjAniSpA@mail.gmail.com>
	<CAB6eaA71MAtnPvAYsOR=MuJD4Rfvr+fBB7OEy5V7EmSj_rUPQg@mail.gmail.com>
	<CAB6eaA72SikGtrxMJ+h8JSU7F5DpiCZYw+OovD5620n_nxQ1ew@mail.gmail.com>
Message-ID: <CAEQEn025+absdPw-k+OCs7iAfcTi4R=4Kq8o3r=5Q_x4NqzLQA@mail.gmail.com>

Hello! Thank you all for writing and helping me out. I now understand the
difference between the two format characters.




-amt
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110726/ff5a3d52/attachment.html>

From steve at pearwood.info  Wed Jul 27 01:18:00 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 27 Jul 2011 09:18:00 +1000
Subject: [Tutor] Don't understand this class/constructor call syntax
In-Reply-To: <20110726011305.M72864@csc.lsu.edu>
References: <20110722223458.M83643@csc.lsu.edu>	<4E2A3B53.3000409@pearwood.info>	<20110723171954.M52452@csc.lsu.edu>	<4E2BC4A2.3030601@pearwood.info>	<20110724183239.M12544@csc.lsu.edu>	<4E2CB823.9050902@pearwood.info>
	<20110726011305.M72864@csc.lsu.edu>
Message-ID: <4E2F4B28.5080802@pearwood.info>

dave wrote:
> Is it even possible to replace the implicit self argument of the initializer
> by passing something else?  If so, what would be the syntax.

Yes, by calling an "unbound method".


Consider this class:


class MyClass:
     def func(self, x):
         return x+1


When you run this code, Python creates a class object MyClass, 
containing one method object, "func". Notice that the syntax for 
defining a method is the same as defining a function, except that it is 
inside a class. In fact they are the same things, except that methods 
are a lightweight wrapper around the real function object. We can see 
this by inspecting the method:

 >>> instance = MyClass()
 >>> instance.func
<bound method MyClass.func of <__main__.MyClass instance at 0xb7f6a08c>>


The method wrapper is responsible for automatically providing the "self" 
argument when you call the function on the instance. The terminology is 
that the method is "bound" to the instance, so the wrapper knows what to 
give as self. When you call the method instance.func(42), the wrapper 
calls the underlying function func(instance, 42).

(Aside: Python also provides two other kinds of methods, classmethod and 
staticmethod, which do something different. And of course the machinery 
that makes this work is available for you to write your own custom 
method types, if you can think of a need.)


But you can also access the method directly from the class object:


 >>> MyClass.func
<unbound method MyClass.func>


In this case, the method wrapper doesn't have access to an instance to 
use as "self" -- it is "unbound".

(Note for Python 3, it was determined that there is no need to provide 
unbound methods anymore, and the underlying function object is returned 
instead.)

Before you can actually call the function, you need to provide an 
argument for "self". You can do that by hand:

 >>> MyClass.func(instance, 42)
43


In Python 2, the unbound method wrapper enforces that the first argument 
is actually an instance of MyClass. But in Python 3 unbound methods are 
gone, and so you can pass anything you like.



-- 
Steven

From lina.lastname at gmail.com  Wed Jul 27 06:46:38 2011
From: lina.lastname at gmail.com (lina)
Date: Wed, 27 Jul 2011 12:46:38 +0800
Subject: [Tutor] output sequentially
Message-ID: <CAG9cJmmsezgfh8qF8uAmyprgU4=eJmAgPmYAcjtp+dmWLGec2Q@mail.gmail.com>

Hi,

I have below file,

I wish the output following:

The first field 169 -170 sequential, and then the filed 2 from 1-29,
ignore the rest 4 fields,

thanks for any suggestions,

  169CHOL   H29 1611   6.963   6.155   6.395
  169CHOL   O28 1612   6.966   6.060   6.429
  169CHOL    C3 1613   7.005   6.073   6.566
  169CHOL    C4 1614   6.940   5.950   6.629
  169CHOL    C5 1615   7.006   5.934   6.766
  169CHOL   C10 1616   6.980   6.060   6.849
  169CHOL    C1 1617   7.040   6.182   6.781
  169CHOL    C2 1618   6.973   6.201   6.645
  169CHOL    C6 1619   7.055   5.819   6.816
  169CHOL    C7 1620   7.089   5.824   6.965
  169CHOL    C8 1621   7.000   5.916   7.048
  169CHOL    C9 1622   7.031   6.056   6.993
  169CHOL   C11 1623   7.000   6.169   7.092
  169CHOL   C12 1624   7.050   6.144   7.235
  169CHOL   C13 1625   6.993   6.009   7.281
  169CHOL   C14 1626   7.048   5.897   7.193
  169CHOL   C15 1627   6.982   5.781   7.266
  169CHOL   C16 1628   7.008   5.803   7.414
  169CHOL   C17 1629   7.038   5.952   7.414
  169CHOL   C19 1630   6.830   6.092   6.846
  169CHOL   C18 1631   6.841   6.000   7.265
  169CHOL   C20 1632   6.983   6.033   7.532
  169CHOL   C21 1633   7.094   6.057   7.635
  169CHOL   C22 1634   6.862   5.976   7.605
  169CHOL   C23 1635   6.838   6.050   7.737
  169CHOL   C24 1636   6.753   5.958   7.824
  169CHOL   C25 1637   6.609   6.008   7.837
  169CHOL   C26 1638   6.537   5.895   7.911
  169CHOL   C27 1639   6.620   6.116   7.945
  170CHOL   H29 1640   5.603   6.375   6.159
  170CHOL   O28 1641   5.625   6.472   6.165
  170CHOL    C3 1642   5.604   6.501   6.303
  170CHOL    C4 1643   5.560   6.645   6.330
  170CHOL    C5 1644   5.539   6.683   6.477
  170CHOL   C10 1645   5.670   6.664   6.552
  170CHOL    C1 1646   5.716   6.520   6.531
  170CHOL    C2 1647   5.732   6.480   6.384
  170CHOL    C6 1648   5.427   6.733   6.530
  170CHOL    C7 1649   5.430   6.768   6.679
  170CHOL    C8 1650   5.569   6.795   6.736
  170CHOL    C9 1651   5.661   6.676   6.704
  170CHOL   C11 1652   5.792   6.713   6.775
  170CHOL   C12 1653   5.781   6.703   6.927
  170CHOL   C13 1654   5.695   6.824   6.964
  170CHOL   C14 1655   5.564   6.799   6.889
  170CHOL   C15 1656   5.462   6.893   6.952
  170CHOL   C16 1657   5.506   6.897   7.097
  170CHOL   C17 1658   5.637   6.821   7.105
  170CHOL   C19 1659   5.765   6.766   6.489
  170CHOL   C18 1660   5.769   6.948   6.913
  170CHOL   C20 1661   5.727   6.885   7.211
  170CHOL   C21 1662   5.832   6.780   7.247
  170CHOL   C22 1663   5.655   6.910   7.343
  170CHOL   C23 1664   5.749   6.980   7.441
  170CHOL   C24 1665   5.667   6.987   7.570
  170CHOL   C25 1666   5.745   7.071   7.672
  170CHOL   C26 1667   5.674   7.205   7.695
  170CHOL   C27 1668   5.760   6.998   7.805

-- 
Best Regards,

lina

From __peter__ at web.de  Wed Jul 27 08:35:07 2011
From: __peter__ at web.de (Peter Otten)
Date: Wed, 27 Jul 2011 08:35:07 +0200
Subject: [Tutor] output sequentially
References: <CAG9cJmmsezgfh8qF8uAmyprgU4=eJmAgPmYAcjtp+dmWLGec2Q@mail.gmail.com>
Message-ID: <j0obis$eo9$1@dough.gmane.org>

lina wrote:

> I have below file,
> 
> I wish the output following:
> 
> The first field 169 -170 sequential, and then the filed 2 from 1-29,
> ignore the rest 4 fields,
 
>   
>   169CHOL   O28 1612   6.966   6.060   6.429

Read the lines from the file, sort them with a proper key function, write 
the sorted lines to a new file:

with open("source.txt") as instream:
   lines = sorted(instream, key=mykey)

with open("dest.txt", "w") as outstream:
    outstream.writelines(lines)

Now for the mykey() function: what should it look like?
You want to sort by the integer value of the first two columns, so you have 
to split the lines into fields and then remove the non-digits from the 
fields you are interested in. Here's an outline:

def extract_int(field):
   only_digits = ...
   return int(only_digits)

assert extract_int("169CHOL") == 169
assert extract_int("H28") == 28

def mykey(line):
    fields = ...
    # example: ['169CHOL', 'H29', '1611', '6.963', '6.155', '6.395']
    return extract_int(fields[0]), extract_int(fields[1])

assert mykey("169CHOL   H29 1611   6.963   6.155   6.395\n") == (169, 28)

Can you fill in the blanks?



From emekamicro at gmail.com  Wed Jul 27 09:14:32 2011
From: emekamicro at gmail.com (Emeka)
Date: Wed, 27 Jul 2011 08:14:32 +0100
Subject: [Tutor] Python Tkinter event activated with time
Message-ID: <CAOypoo7PBT7qutG4h+8-0QwBMJ09FCNQYoy0VJJ0ztP+18eauQ@mail.gmail.com>

Hello All,

I am putting together a small game, and I would want to enable my callback
function using time passed.

How to do something like this with Tkinter event.

from time import time

ftime  = time()
   if ftime - time() > 2000:
        dosomething



-- 
*Satajanus  Nig. Ltd


*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110727/1b690896/attachment.html>

From __peter__ at web.de  Wed Jul 27 09:46:55 2011
From: __peter__ at web.de (Peter Otten)
Date: Wed, 27 Jul 2011 09:46:55 +0200
Subject: [Tutor] Python Tkinter event activated with time
References: <CAOypoo7PBT7qutG4h+8-0QwBMJ09FCNQYoy0VJJ0ztP+18eauQ@mail.gmail.com>
Message-ID: <j0ofpg$4h6$1@dough.gmane.org>

Emeka wrote:

> I am putting together a small game, and I would want to enable my callback
> function using time passed.
> 
> How to do something like this with Tkinter event.
> 
> from time import time
> 
> ftime  = time()
>    if ftime - time() > 2000:
>         dosomething

You can schedule a function call with the after() method:

import Tkinter as tk

def scroll(s):
    while True:
        yield s
        s = s[-1] + s[:-1]

hello = scroll("Hello world! *** ")

def do_something():
    label["text"] = next(hello)
    # play it again, after 100 msecs
    label.after(100, do_something) 

root = tk.Tk()
label = tk.Label(root, font=("Times", 36))
label.pack()
do_something()
root.mainloop()



From rhettnaxel at gmail.com  Wed Jul 27 15:51:08 2011
From: rhettnaxel at gmail.com (Alexander)
Date: Wed, 27 Jul 2011 09:51:08 -0400
Subject: [Tutor] Object Management
Message-ID: <CANS6qmCH4YCW9GdgL0R11rE7Ln9f0FyeeYH+_PO=gX+fWEpOTQ@mail.gmail.com>

Hello everyone. I'm having trouble wrapping my mind around a project I'm
working on. My goal is to create a program that manages (allows its users to
manipulate, search by criteria and edit) objects. There is one type of
object, for example I'll say it's a car.

There will be a central data file containing all of the cars and multiple
users will have access to it at once. I'm having trouble here, I've done
some research on MOO and twisted but I'm not sure where to turn.

Additionally I'll need a GUI! tkinter? Does anyone have any suggestions on
how to get started with tkinter? I'm overwhelmed with the amount of
documentation I've had to read and think I have to read to accomplish my
goal.

Thanks for reading, Alex.ander

-- 
Alexander
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110727/cafcecb2/attachment.html>

From eire1130 at gmail.com  Wed Jul 27 16:05:41 2011
From: eire1130 at gmail.com (James Reynolds)
Date: Wed, 27 Jul 2011 10:05:41 -0400
Subject: [Tutor] Object Management
In-Reply-To: <CANS6qmCH4YCW9GdgL0R11rE7Ln9f0FyeeYH+_PO=gX+fWEpOTQ@mail.gmail.com>
References: <CANS6qmCH4YCW9GdgL0R11rE7Ln9f0FyeeYH+_PO=gX+fWEpOTQ@mail.gmail.com>
Message-ID: <CAE0jAbqh8pC0v-io8wwFh_Zm0YGb4EnEy+jODqnw=bLvnqGY=g@mail.gmail.com>

On Wed, Jul 27, 2011 at 9:51 AM, Alexander <rhettnaxel at gmail.com> wrote:

> Hello everyone. I'm having trouble wrapping my mind around a project I'm
> working on. My goal is to create a program that manages (allows its users to
> manipulate, search by criteria and edit) objects. There is one type of
> object, for example I'll say it's a car.
>
> There will be a central data file containing all of the cars and multiple
> users will have access to it at once. I'm having trouble here, I've done
> some research on MOO and twisted but I'm not sure where to turn.
>
> Additionally I'll need a GUI! tkinter? Does anyone have any suggestions on
> how to get started with tkinter? I'm overwhelmed with the amount of
> documentation I've had to read and think I have to read to accomplish my
> goal.
>
> Thanks for reading, Alex.ander
>
> --
> Alexander
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>





It sounds like your learning a lot of this as you go. Honestly, I would
scrap the GUI idea and just use Django. This will solve your mulit-user,
front end, and back end problems in one go.

Of course, that's an entire skillset onto itself and it may not be worth the
time investment. But if you already know some HTML, it would be an asset for
years to come, if you picked it up.

In which case, simply use SQlite as your backend (it comes with Python) and
then chose a GUI toolkit from there. Designing a GUI is not for the feint of
heart. Tkinter is an option, but you may want to use Wx or GTK.

A third option is to use Django to manage your backend (by creating models
and such) and then designing a gui on top of that.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110727/5516a5b9/attachment.html>

From knacktus at googlemail.com  Wed Jul 27 17:15:58 2011
From: knacktus at googlemail.com (Knacktus)
Date: Wed, 27 Jul 2011 17:15:58 +0200
Subject: [Tutor] Object Management
In-Reply-To: <CANS6qmCH4YCW9GdgL0R11rE7Ln9f0FyeeYH+_PO=gX+fWEpOTQ@mail.gmail.com>
References: <CANS6qmCH4YCW9GdgL0R11rE7Ln9f0FyeeYH+_PO=gX+fWEpOTQ@mail.gmail.com>
Message-ID: <4E302BAE.6010400@googlemail.com>

Am 27.07.2011 15:51, schrieb Alexander:
> Hello everyone. I'm having trouble wrapping my mind around a project I'm
> working on. My goal is to create a program that manages (allows its
> users to manipulate, search by criteria and edit) objects. There is one
> type of object, for example I'll say it's a car.
>
> There will be a central data file containing all of the cars and
> multiple users will have access to it at once. I'm having trouble here,
> I've done some research on MOO and twisted but I'm not sure where to turn.

Sounds familiar ;-) ... on the way a lot of question are likely to 
arise. Like, "OK, I've got a database. Do I load all the data at once to 
the client or only on request? What about concurrent usage by different 
clients (users)? How about authentification and authorisition? If I 
build a rich client (a python programm with GUI and network connection 
to the database), how do I manage the objects on the client?"

As James already hinted, there're fantastic python web frameworks. They 
have solutions for almost all the questions that will cross your path. 
There're some relgious wars about which is the best. In my opinion 
Django is the best for starters. Do some tutorials, read the Django book 
and you'll get an idea about the overall architcture, models, views, 
templates, etc.

>
> Additionally I'll need a GUI! tkinter? Does anyone have any suggestions
> on how to get started with tkinter? I'm overwhelmed with the amount of
> documentation I've had to read and think I have to read to accomplish my
> goal.

I've written a rich client with PyQt which talks via web services to a 
web server. It's a lot of work! You have a lot of options, performance 
is amazing, but due to the complexity I would recommend to start with a 
web interface.

If you really need or want a rich client, you should look into Dabo:

http://dabodev.com/about

There's also another rich application framework which uses PyQt and 
looks very good, but I forgot the name. I'm not sure about wether this 
is free or commercial.


>
> Thanks for reading, Alex.ander
>
> --
> Alexander
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From karim.liateni at free.fr  Wed Jul 27 21:30:57 2011
From: karim.liateni at free.fr (Karim)
Date: Wed, 27 Jul 2011 21:30:57 +0200
Subject: [Tutor] shlex parsing
Message-ID: <4E306771.8070408@free.fr>


Hello All,

I would like to parse this TCL command line with shlex:

'-option1 [get_rule A1 B2] -option2 $VAR -option3 TAG'

And I want to get the splitted list:

['-option1', '[get_rule A1 B2]', '-option2',  '$VAR', '-option3',  'TAG']

Then I will gather in tuple 2 by 2 the arguments.

I tried to the shlec properties attributes 'quotes', 'whitespace', etc...

But I make 'choux blanc'.

If somebody has complex experiences with  this module I am in.

Cheers
Karim

From karim.liateni at free.fr  Wed Jul 27 23:08:38 2011
From: karim.liateni at free.fr (Karim)
Date: Wed, 27 Jul 2011 23:08:38 +0200
Subject: [Tutor] shlex parsing
In-Reply-To: <CAGGBd_ry0sOMyh5EFrYftwNAtoVrOybwo-ctx6BXQUERaPnRTg@mail.gmail.com>
References: <4E306771.8070408@free.fr>
	<CAGGBd_ry0sOMyh5EFrYftwNAtoVrOybwo-ctx6BXQUERaPnRTg@mail.gmail.com>
Message-ID: <4E307E56.2050608@free.fr>


Thank you Dan for answering.

I ended with this and gave up with shlex:

split = ['-option1', '[get_rule', 'A1', 'B2]', '-option2', '$VAR', 
'-option3', 'TAG']

procedure_found = False
result          = []

for token in split:
     if not token.startswith('[') and not token.endswith(']') and not 
procedure_found:
         result.append(token)
     elif token.startswith('['):
         procedure_found = True
         _token = token
     elif token.endswith(']'):
         procedure_found = False
         _token += ' ' + token
         result.append(_token)
     else:
         _token += ' ' + token

print split
print result

which gives the desired values:

['-option1', '[get_rule', 'A1', 'B2]', '-option2', '$VAR', '-option3', 
'TAG']
['-option1', '[get_rule A1 B2]', '-option2', '$VAR', '-option3', 'TAG']


Sure pyParsing seems to be pretty simple but my constraint is to use
standard lib (at maximum). To bad it is not part of python standard libs.
On the other hand, I will have to regroup expression like '-option1 $VAL 
== $CONSTRAINT'
in ['-option1', '$VAL == $CONSTRAINT'].

So it seems that I have no others choicse and have to use a parser like 
pyParsing.

Regards
Karim

On 07/27/2011 10:44 PM, Dan Stromberg wrote:
>
> I've not used the shlex module, but this feels more like an issue to 
> address with a parser than for a lexical analyzer - or perhaps even 
> both, since you're splitting on whitespace sometimes, and matching 
> square brackets sometimes.
>
> I've used pyparsing for stuff a bit similar to this.
>
> Or here's a list:
> http://wiki.python.org/moin/LanguageParsing
>
> On Wed, Jul 27, 2011 at 12:30 PM, Karim <karim.liateni at free.fr 
> <mailto:karim.liateni at free.fr>> wrote:
>
>
>     Hello All,
>
>     I would like to parse this TCL command line with shlex:
>
>     '-option1 [get_rule A1 B2] -option2 $VAR -option3 TAG'
>
>     And I want to get the splitted list:
>
>     ['-option1', '[get_rule A1 B2]', '-option2',  '$VAR', '-option3',
>      'TAG']
>
>     Then I will gather in tuple 2 by 2 the arguments.
>
>     I tried to the shlec properties attributes 'quotes', 'whitespace',
>     etc...
>
>     But I make 'choux blanc'.
>
>     If somebody has complex experiences with  this module I am in.
>
>     Cheers
>     Karim
>     -- 
>     http://mail.python.org/mailman/listinfo/python-list
>
>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110727/68c9286f/attachment-0001.html>

From sierra_mtnview at sbcglobal.net  Wed Jul 27 23:07:24 2011
From: sierra_mtnview at sbcglobal.net (Wayne Watson)
Date: Wed, 27 Jul 2011 14:07:24 -0700
Subject: [Tutor] Getting Idle to work in Win7
Message-ID: <4E307E0C.2040801@sbcglobal.net>

It's been many months since I played with Python, and have forgotten how 
to bring up IDLE. If I simply click on a py file, I see what may be a 
dos window appear and quickly disappear. If I right-click on the file, 
and select IDLE, the same thing happens. If I go directly to All 
Programs, the same thing happens when I select IDLE.

-- 
            Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

              (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
               Obz Site:  39? 15' 7" N, 121? 2' 32" W, 2700 feet

                   "The physicist uses ordinary words
                   in a peculiar manner." -- Richard Feynma in
                         The Character of Physical Law


                     Web Page:<www.speckledwithstars.net/>



From wprins at gmail.com  Wed Jul 27 23:38:39 2011
From: wprins at gmail.com (Walter Prins)
Date: Wed, 27 Jul 2011 22:38:39 +0100
Subject: [Tutor] Getting Idle to work in Win7
In-Reply-To: <4E307E0C.2040801@sbcglobal.net>
References: <4E307E0C.2040801@sbcglobal.net>
Message-ID: <CANLXbfCFzfzDnqOmvovrQqN79Pjk0=cY-e4AsSYCm=+28GTnVg@mail.gmail.com>

Hi

On 27 July 2011 22:07, Wayne Watson <sierra_mtnview at sbcglobal.net> wrote:

> It's been many months since I played with Python, and have forgotten how to
> bring up IDLE. If I simply click on a py file, I see what may be a dos
> window appear and quickly disappear. If I right-click on the file, and
> select IDLE, the same thing happens. If I go directly to All Programs, the
> same thing happens when I select IDLE.
>

There must be something wrong with your Python installation.
Right-click->"Edit with Idle" and starting IDLE from All Programs works fine
for me. (Win 7 64-bit, with both Python 2.7 and 3.2 installed.)  I suggest
you reinstall Python as a start.  It might also be worthwhile to try to run
your Python script from the command line, as well as starting Idle from the
command line so you can see what error message might be printed.

Cheers

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110727/0343f348/attachment.html>

From karim.liateni at free.fr  Wed Jul 27 23:45:02 2011
From: karim.liateni at free.fr (Karim)
Date: Wed, 27 Jul 2011 23:45:02 +0200
Subject: [Tutor] Fall in love with bpython
Message-ID: <4E3086DE.4020903@free.fr>



Hello,

I use bpython interpreter. This is a very good interactive CLI.
I want to create a CLI with the same features than bpython.
But the cmd std module seems no to be used in this project...

Is there a tool where I can plug all my grammary commands line
a sort of generic box with completion, highlights, etc...

Cheers
Karim

From karim.liateni at free.fr  Thu Jul 28 00:15:57 2011
From: karim.liateni at free.fr (Karim)
Date: Thu, 28 Jul 2011 00:15:57 +0200
Subject: [Tutor] shlex parsing
In-Reply-To: <CAGGBd_qXDTKK9hkv-VteS+=d6Rnxa0M+qvL3rRHY56AAOPd44g@mail.gmail.com>
References: <4E306771.8070408@free.fr>	<CAGGBd_ry0sOMyh5EFrYftwNAtoVrOybwo-ctx6BXQUERaPnRTg@mail.gmail.com>	<4E307E56.2050608@free.fr>
	<CAGGBd_qXDTKK9hkv-VteS+=d6Rnxa0M+qvL3rRHY56AAOPd44g@mail.gmail.com>
Message-ID: <4E308E1D.7030107@free.fr>

On 07/28/2011 12:11 AM, Dan Stromberg wrote:
>
> You could probably use a recursive descent parser with the standard 
> library.
>
> But if your management is OK with pyparsing, that might be easier, and 
> a bit more clear as well.

Yes, I thought to use str method partition in a recursive way but using 
pyParsing still be easer.

Thanks
Cheers

>
> On Wed, Jul 27, 2011 at 2:08 PM, Karim <karim.liateni at free.fr 
> <mailto:karim.liateni at free.fr>> wrote:
>
>
>     Thank you Dan for answering.
>
>     I ended with this and gave up with shlex:
>
>     split = ['-option1', '[get_rule', 'A1', 'B2]', '-option2', '$VAR',
>     '-option3', 'TAG']
>
>     procedure_found = False
>     result          = []
>
>     for token in split:
>         if not token.startswith('[') and not token.endswith(']') and
>     not procedure_found:
>             result.append(token)
>         elif token.startswith('['):
>             procedure_found = True
>             _token = token
>         elif token.endswith(']'):
>             procedure_found = False
>             _token += ' ' + token
>             result.append(_token)
>         else:
>             _token += ' ' + token
>
>     print split
>     print result
>
>     which gives the desired values:
>
>     ['-option1', '[get_rule', 'A1', 'B2]', '-option2', '$VAR',
>     '-option3', 'TAG']
>     ['-option1', '[get_rule A1 B2]', '-option2', '$VAR', '-option3',
>     'TAG']
>
>
>     Sure pyParsing seems to be pretty simple but my constraint is to use
>     standard lib (at maximum). To bad it is not part of python
>     standard libs.
>     On the other hand, I will have to regroup expression like
>     '-option1 $VAL == $CONSTRAINT'
>     in ['-option1', '$VAL == $CONSTRAINT'].
>
>     So it seems that I have no others choicse and have to use a parser
>     like pyParsing.
>
>     Regards
>     Karim
>
>
>     On 07/27/2011 10:44 PM, Dan Stromberg wrote:
>>
>>     I've not used the shlex module, but this feels more like an issue
>>     to address with a parser than for a lexical analyzer - or perhaps
>>     even both, since you're splitting on whitespace sometimes, and
>>     matching square brackets sometimes.
>>
>>     I've used pyparsing for stuff a bit similar to this.
>>
>>     Or here's a list:
>>     http://wiki.python.org/moin/LanguageParsing
>>
>>     On Wed, Jul 27, 2011 at 12:30 PM, Karim <karim.liateni at free.fr
>>     <mailto:karim.liateni at free.fr>> wrote:
>>
>>
>>         Hello All,
>>
>>         I would like to parse this TCL command line with shlex:
>>
>>         '-option1 [get_rule A1 B2] -option2 $VAR -option3 TAG'
>>
>>         And I want to get the splitted list:
>>
>>         ['-option1', '[get_rule A1 B2]', '-option2',  '$VAR',
>>         '-option3',  'TAG']
>>
>>         Then I will gather in tuple 2 by 2 the arguments.
>>
>>         I tried to the shlec properties attributes 'quotes',
>>         'whitespace', etc...
>>
>>         But I make 'choux blanc'.
>>
>>         If somebody has complex experiences with  this module I am in.
>>
>>         Cheers
>>         Karim
>>         -- 
>>         http://mail.python.org/mailman/listinfo/python-list
>>
>>
>
>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110728/2fd6c8c8/attachment.html>

From alan.gauld at btinternet.com  Wed Jul 27 00:25:00 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 26 Jul 2011 23:25:00 +0100
Subject: [Tutor] Object Management
In-Reply-To: <CANS6qmCH4YCW9GdgL0R11rE7Ln9f0FyeeYH+_PO=gX+fWEpOTQ@mail.gmail.com>
References: <CANS6qmCH4YCW9GdgL0R11rE7Ln9f0FyeeYH+_PO=gX+fWEpOTQ@mail.gmail.com>
Message-ID: <4E2F3EBC.70304@btinternet.com>

Alexander wrote:
> Hello everyone. I'm having trouble wrapping my mind around a project I'm
> working on. My goal is to create a program that manages (allows its users to
> manipulate, search by criteria and edit) objects. There is one type of
> object, for example I'll say it's a car.
> 
> There will be a central data file containing all of the cars and multiple
> users will have access to it at once. I'm having trouble here, I've done
> some research on MOO and twisted but I'm not sure where to turn.

I'd forget twisted etc for this, it sounds more like a traditional 
database is whats needed.


> Additionally I'll need a GUI! tkinter? Does anyone have any suggestions on
> how to get started with tkinter? I'm overwhelmed with the amount of
> documentation I've had to read and think I have to read to accomplish my
> goal.

Learning any GUI is a painful leaning curve. If you really need a 
desktop client rather than a web based solution I'd look at Dabo.
It has a GUI builder (based on wxPython rather than Tkinter) and is 
focused on data oriented applications.

But if you can go down the web root then most python web frameworks will 
provide both the UI and database elements for you and you get a lot of 
standard functionality (login etc) for free...


HTH,

Alan G.



From alan.gauld at btinternet.com  Wed Jul 27 00:25:00 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 26 Jul 2011 23:25:00 +0100
Subject: [Tutor] Object Management
In-Reply-To: <CANS6qmCH4YCW9GdgL0R11rE7Ln9f0FyeeYH+_PO=gX+fWEpOTQ@mail.gmail.com>
References: <CANS6qmCH4YCW9GdgL0R11rE7Ln9f0FyeeYH+_PO=gX+fWEpOTQ@mail.gmail.com>
Message-ID: <4E2F3EBC.70304@btinternet.com>

Alexander wrote:
> Hello everyone. I'm having trouble wrapping my mind around a project I'm
> working on. My goal is to create a program that manages (allows its users to
> manipulate, search by criteria and edit) objects. There is one type of
> object, for example I'll say it's a car.
> 
> There will be a central data file containing all of the cars and multiple
> users will have access to it at once. I'm having trouble here, I've done
> some research on MOO and twisted but I'm not sure where to turn.

I'd forget twisted etc for this, it sounds more like a traditional 
database is whats needed.


> Additionally I'll need a GUI! tkinter? Does anyone have any suggestions on
> how to get started with tkinter? I'm overwhelmed with the amount of
> documentation I've had to read and think I have to read to accomplish my
> goal.

Learning any GUI is a painful leaning curve. If you really need a 
desktop client rather than a web based solution I'd look at Dabo.
It has a GUI builder (based on wxPython rather than Tkinter) and is 
focused on data oriented applications.

But if you can go down the web root then most python web frameworks will 
provide both the UI and database elements for you and you get a lot of 
standard functionality (login etc) for free...


HTH,

Alan G.



From alan.gauld at btinternet.com  Wed Jul 27 00:34:56 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 26 Jul 2011 23:34:56 +0100
Subject: [Tutor] Fall in love with bpython
In-Reply-To: <4E3086DE.4020903@free.fr>
References: <4E3086DE.4020903@free.fr>
Message-ID: <4E2F4110.8080200@btinternet.com>

Karim wrote:

> I use bpython interpreter. This is a very good interactive CLI.

I had never heard of it and had to google for it.
It appears to be a curses based CLI for *nix and MacOS


> I want to create a CLI with the same features than bpython.
> But the cmd std module seems no to be used in this project...

Why not read the bpython source to see what they used?
Thats the big advantage of open source - its open!
(Although they don't make the source explicitly available,
I'm assuming the tar file contains the source- it might
even be in Python!)

They use pygments to parse the source as you type.
That would be worth investigating too...


HTH,

Alan G.

From rhettnaxel at gmail.com  Thu Jul 28 00:45:11 2011
From: rhettnaxel at gmail.com (Alexander)
Date: Wed, 27 Jul 2011 18:45:11 -0400
Subject: [Tutor] Object Management
In-Reply-To: <4E2F3EBC.70304@btinternet.com>
References: <CANS6qmCH4YCW9GdgL0R11rE7Ln9f0FyeeYH+_PO=gX+fWEpOTQ@mail.gmail.com>
	<4E2F3EBC.70304@btinternet.com>
Message-ID: <CANS6qmB0NrSfC8SGNun+dFNZaYHv9xKTOX+2vQHhFYJAFg54Zg@mail.gmail.com>

On Tue, Jul 26, 2011 at 6:25 PM, Alan Gauld <alan.gauld at btinternet.com>wrote:

> Alexander wrote:
>
>> Hello everyone. I'm having trouble wrapping my mind around a project I'm
>> working on. My goal is to create a program that manages (allows its users
>> to
>> manipulate, search by criteria and edit) objects. There is one type of
>> object, for example I'll say it's a car.
>>
>> There will be a central data file containing all of the cars and multiple
>> users will have access to it at once. I'm having trouble here, I've done
>> some research on MOO and twisted but I'm not sure where to turn.
>>
>
> I'd forget twisted etc for this, it sounds more like a traditional database
> is whats needed.
>
>
>
>  Additionally I'll need a GUI! tkinter? Does anyone have any suggestions on
>> how to get started with tkinter? I'm overwhelmed with the amount of
>> documentation I've had to read and think I have to read to accomplish my
>> goal.
>>
>
> Learning any GUI is a painful leaning curve. If you really need a desktop
> client rather than a web based solution I'd look at Dabo.
> It has a GUI builder (based on wxPython rather than Tkinter) and is focused
> on data oriented applications.
>
> But if you can go down the web root then most python web frameworks will
> provide both the UI and database elements for you and you get a lot of
> standard functionality (login etc) for free...
>
>
> HTH,
>
> Alan G.
>
>
>


-- 
Thanks for the replies Alan, James, and Knacktus. I'll research Django. I've
been trying to work on this project for a few months and just came across
the mailing list today. I appreciate your help, thanks!
Alexander
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110727/d641a648/attachment.html>

From ramit.prasad at jpmchase.com  Thu Jul 28 00:49:56 2011
From: ramit.prasad at jpmchase.com (Prasad, Ramit)
Date: Wed, 27 Jul 2011 18:49:56 -0400
Subject: [Tutor] Getting Idle to work in Win7
In-Reply-To: <CANLXbfCFzfzDnqOmvovrQqN79Pjk0=cY-e4AsSYCm=+28GTnVg@mail.gmail.com>
References: <4E307E0C.2040801@sbcglobal.net>
	<CANLXbfCFzfzDnqOmvovrQqN79Pjk0=cY-e4AsSYCm=+28GTnVg@mail.gmail.com>
Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA6F1C8BC@EMARC112VS01.exchad.jpmchase.net>

From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of Walter Prins
Sent: Wednesday, July 27, 2011 4:39 PM
To: tutor at python.org
Subject: Re: [Tutor] Getting Idle to work in Win7

Hi
On 27 July 2011 22:07, Wayne Watson <sierra_mtnview at sbcglobal.net<mailto:sierra_mtnview at sbcglobal.net>> wrote:
It's been many months since I played with Python, and have forgotten how to bring up IDLE. If I simply click on a py file, I see what may be a dos window appear and quickly disappear. If I right-click on the file, and select IDLE, the same thing happens. If I go directly to All Programs, the same thing happens when I select IDLE.

There must be something wrong with your Python installation.  Right-click->"Edit with Idle" and starting IDLE from All Programs works fine for me. (Win 7 64-bit, with both Python 2.7 and 3.2 installed.)  I suggest you reinstall Python as a start.  It might also be worthwhile to try to run your Python script from the command line, as well as starting Idle from the command line so you can see what error message might be printed.

Cheers

Walter

Open cmd.exe and then navigate to the directory where Python is installed (C:\Python27) for me and then cd into the Lib\idlelib directory and run idle.bat. Hopefully there should be some errors that show in the window. If not you can try running it "..\..\pythonw.exe idle.pyw" and hopefully that will show the problem.


Ramit


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







This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase &
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110727/f7772185/attachment-0001.html>

From karim.liateni at free.fr  Thu Jul 28 01:04:00 2011
From: karim.liateni at free.fr (Karim)
Date: Thu, 28 Jul 2011 01:04:00 +0200
Subject: [Tutor] Fall in love with bpython
In-Reply-To: <4E2F4110.8080200@btinternet.com>
References: <4E3086DE.4020903@free.fr> <4E2F4110.8080200@btinternet.com>
Message-ID: <4E309960.6080408@free.fr>

On 07/27/2011 12:34 AM, Alan Gauld wrote:
> Karim wrote:
>
>> I use bpython interpreter. This is a very good interactive CLI.
>
> I had never heard of it and had to google for it.
> It appears to be a curses based CLI for *nix and MacOS

Ah Windows user.

>
>> I want to create a CLI with the same features than bpython.
>> But the cmd std module seems no to be used in this project...
>
> Why not read the bpython source to see what they used?
> Thats the big advantage of open source - its open!
> (Although they don't make the source explicitly available,
> I'm assuming the tar file contains the source- it might
> even be in Python!)
>
> They use pygments to parse the source as you type.
> That would be worth investigating too...
>

Yes I saw mainly pygments which is an OpenSource project...
But, I must admit. I will spend 6 months before understanding this.
Rhahaaa... This level is high! I saw too cmd2 which is fully compatible 
and inherit from cmd.
But not quite as fun!

The main module cli.py is 1700 lignes and the architecture is not very 
well documented.
We will see If I can make any progress during the next month.

Thanks Alan

PS: Are you still making some hiking in the higlands. Beautiful photos I 
have seen on your web site!

Cheers
Alan

>
> HTH,
>
> Alan G.


From karim.liateni at free.fr  Thu Jul 28 01:09:36 2011
From: karim.liateni at free.fr (Karim)
Date: Thu, 28 Jul 2011 01:09:36 +0200
Subject: [Tutor] Fall in love with bpython
In-Reply-To: <20110727223154.GF29550@horus.cms.at>
References: <4E3086DE.4020903@free.fr> <20110727223154.GF29550@horus.cms.at>
Message-ID: <4E309AB0.10601@free.fr>

On 07/28/2011 12:31 AM, Michael Poeltl wrote:
> hi,
>
> have you heard abut ipython? maybe that's helpful for you?
> http://ipython.scipy.org/moin/python

Hello Michael,

Yes I saw some article where Ipython and Bpython CLI integrations was 
made in Django.

Thanks for the link I will evaluate it as well.

Cheers
Karim

> Michael
> * Karim<karim.liateni at free.fr>  [2011-07-27 23:46]:
>>
>> Hello,
>>
>> I use bpython interpreter. This is a very good interactive CLI.
>> I want to create a CLI with the same features than bpython.
>> But the cmd std module seems no to be used in this project...
>>
>> Is there a tool where I can plug all my grammary commands line
>> a sort of generic box with completion, highlights, etc...
>>
>> Cheers
>> Karim
>> -- 
>> http://mail.python.org/mailman/listinfo/python-list
>>


From wprins at gmail.com  Thu Jul 28 01:32:48 2011
From: wprins at gmail.com (Walter Prins)
Date: Thu, 28 Jul 2011 00:32:48 +0100
Subject: [Tutor] Fall in love with bpython
In-Reply-To: <4E309960.6080408@free.fr>
References: <4E3086DE.4020903@free.fr> <4E2F4110.8080200@btinternet.com>
	<4E309960.6080408@free.fr>
Message-ID: <CANLXbfBz9G_HBLPR8aJ=8vbZDPbQpuuOsWPhhpc8YjF-vOZSDA@mail.gmail.com>

Hi Karim

On 28 July 2011 00:04, Karim <karim.liateni at free.fr> wrote:

> On 07/27/2011 12:34 AM, Alan Gauld wrote:
>
>> Karim wrote:
>>
>>  I use bpython interpreter. This is a very good interactive CLI.
>>>
>>
>> I had never heard of it and had to google for it.
>> It appears to be a curses based CLI for *nix and MacOS
>>
>
> Ah Windows user.


Thanks for mentioning bpython -- I had also not heard of it but it duly
installed on my ubuntu box from the repositories!  I've browsed the code --
it uses ncurses to do the screen IO.  You can always read the code, but, as
you intimated, unless you're pretty familiar with somewhat large codebases
and ncurses it might not be that much use to you just yet. ... Still, it
might be worth having a look at the source... :)

http://hg.bpython-interpreter.org/bpython/src/bcd836c859aa/bpython/

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110728/6bea829e/attachment.html>

From karim.liateni at free.fr  Thu Jul 28 02:03:48 2011
From: karim.liateni at free.fr (Karim)
Date: Thu, 28 Jul 2011 02:03:48 +0200
Subject: [Tutor] Fall in love with bpython
In-Reply-To: <CANLXbfBz9G_HBLPR8aJ=8vbZDPbQpuuOsWPhhpc8YjF-vOZSDA@mail.gmail.com>
References: <4E3086DE.4020903@free.fr>	<4E2F4110.8080200@btinternet.com>	<4E309960.6080408@free.fr>
	<CANLXbfBz9G_HBLPR8aJ=8vbZDPbQpuuOsWPhhpc8YjF-vOZSDA@mail.gmail.com>
Message-ID: <4E30A764.3010800@free.fr>

On 07/28/2011 01:32 AM, Walter Prins wrote:
> Hi Karim
>
> On 28 July 2011 00:04, Karim <karim.liateni at free.fr 
> <mailto:karim.liateni at free.fr>> wrote:
>
>     On 07/27/2011 12:34 AM, Alan Gauld wrote:
>
>         Karim wrote:
>
>             I use bpython interpreter. This is a very good interactive
>             CLI.
>
>
>         I had never heard of it and had to google for it.
>         It appears to be a curses based CLI for *nix and MacOS
>
>
>     Ah Windows user.
>
>
> Thanks for mentioning bpython -- I had also not heard of it but it 
> duly installed on my ubuntu box from the repositories!  I've browsed 
> the code -- it uses ncurses to do the screen IO.  You can always read 
> the code, but, as you intimated, unless you're pretty familiar with 
> somewhat large codebases and ncurses it might not be that much use to 
> you just yet. ... Still, it might be worth having a look at the 
> source... :)
>
> http://hg.bpython-interpreter.org/bpython/src/bcd836c859aa/bpython/
>
> Walter

Hi,

I am using ubuntu too.
I used to write large API but in fact I did not know curses and I wanted 
to see in the code
where the keywords are 'injected' to try with my own grammar. I still 
have to study the details.
But it seems that the keywords are imported dynamically from 
__builtins__ module. Don't know yet
how to configure or modify it.

Thanks for your advice
Regards
Karim



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110728/ac2ceecd/attachment.html>

From steve at pearwood.info  Thu Jul 28 02:13:03 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 28 Jul 2011 10:13:03 +1000
Subject: [Tutor] Object Management
In-Reply-To: <CANS6qmCH4YCW9GdgL0R11rE7Ln9f0FyeeYH+_PO=gX+fWEpOTQ@mail.gmail.com>
References: <CANS6qmCH4YCW9GdgL0R11rE7Ln9f0FyeeYH+_PO=gX+fWEpOTQ@mail.gmail.com>
Message-ID: <4E30A98F.7020301@pearwood.info>

Alexander wrote:
> Hello everyone. I'm having trouble wrapping my mind around a project I'm
> working on. My goal is to create a program that manages (allows its users to
> manipulate, search by criteria and edit) objects. There is one type of
> object, for example I'll say it's a car.


This is called a database. Implementing databases correctly is a HUGE 
job: more work than writing an operating system.

Take my advice and choose an existing database. If your needs are light, 
use SQLite. If your needs are heavy, MySQL or Postgres. If you need to 
impress corporate buyers with more money than sense, and you have a 
large budget, Oracle. Then concentrate on building the user-friendly 
front-end to the database. That alone will be a big job.


If you are happy with a web-interface, rather than a desktop GUI, I 
recommend you look at CherryPy. It's a nice, lightweight web framework 
without the learning curve of Django and similar.


-- 
Steven

From redacted@example.com  Thu Jul 28 02:16:31 2011
From: redacted@example.com (Alexander Quest)
Date: Wed, 27 Jul 2011 17:16:31 -0700
Subject: [Tutor] Assigning range
Message-ID: <CAHgjEe1uowv9NkJwG12iCa5yr=Yg4PWCTdRAtsSYchd+R1w2jQ@mail.gmail.com>

Does anyone know how to assign a certain numerical range to a variable, and
then choose the number that is the middle of that range? For example, I want
to assign the variable "X" a range between 1 and 50, and then I want to have
the middle of that range (25) return with some command when I call it
(perhaps rangemid or something like that?). In pseudocode, I am trying to
say X = range [1,50], return middle of range (which should return 25) but I
don't know how to code it. This is for a basic program I'm trying to write
where the player thinks of a number and the computer tries to guess the
number in as few tries as possible. Thanks for any help!

-Alex
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110727/40d2a8d9/attachment-0001.html>

From steve at pearwood.info  Thu Jul 28 02:27:52 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 28 Jul 2011 10:27:52 +1000
Subject: [Tutor] shlex parsing
In-Reply-To: <4E306771.8070408@free.fr>
References: <4E306771.8070408@free.fr>
Message-ID: <4E30AD08.6080600@pearwood.info>

Karim wrote:
> 
> Hello All,
> 
> I would like to parse this TCL command line with shlex:
> 
> '-option1 [get_rule A1 B2] -option2 $VAR -option3 TAG'
> 
> And I want to get the splitted list:
> 
> ['-option1', '[get_rule A1 B2]', '-option2',  '$VAR', '-option3',  'TAG']
> 
> Then I will gather in tuple 2 by 2 the arguments.
> 
> I tried to the shlec properties attributes 'quotes', 'whitespace', etc...

I don't understand what you are doing here. Please show the code you use.

The shlex module doesn't support bracketed expressions. I recommend you 
write a post-processor. Start with doing this:

 >>> import shlex
 >>> text = '-option1 [get_rule A1 B2] -option2 $VAR -option3 TAG'
 >>> shlex.split(text)
['-option1', '[get_rule', 'A1', 'B2]', '-option2', '$VAR', '-option3', 
'TAG']

then take that list and reassemble the pieces starting with '[' until 
']' Something like this, untested:


def reassemble(items):
     result = []
     bracketed = False
     current = ''
     for item in items:
         if item.startswith('['):
             bracketed = True
         if bracketed:
             current += item
             if item.endswith(']'):
                 bracketed = False
                 result.append(current)
                 current = ''
         else:
              result.append(item)
     return result



> But I make 'choux blanc'.

I don't know what that means.




-- 
Steven


From steve at pearwood.info  Thu Jul 28 02:40:13 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 28 Jul 2011 10:40:13 +1000
Subject: [Tutor] Assigning range
In-Reply-To: <CAHgjEe1uowv9NkJwG12iCa5yr=Yg4PWCTdRAtsSYchd+R1w2jQ@mail.gmail.com>
References: <CAHgjEe1uowv9NkJwG12iCa5yr=Yg4PWCTdRAtsSYchd+R1w2jQ@mail.gmail.com>
Message-ID: <4E30AFED.6000706@pearwood.info>

Alexander Quest wrote:
> Does anyone know how to assign a certain numerical range to a variable, and
> then choose the number that is the middle of that range? For example, I want
> to assign the variable "X" a range between 1 and 50, and then I want to have
> the middle of that range (25) return with some command when I call it
> (perhaps rangemid or something like that?). In pseudocode, I am trying to
> say X = range [1,50], return middle of range (which should return 25) but I
> don't know how to code it. This is for a basic program I'm trying to write
> where the player thinks of a number and the computer tries to guess the
> number in as few tries as possible. Thanks for any help!


Forget about using range, that just adds meaningless complexity.

What is important is that you have a lower bound, and a higher bound: 
two numbers, instead of how ever many (possible thousands, or millions!) 
in range(low, high).

middle = (low+high)//2



-- 
Steven


From karim.liateni at free.fr  Thu Jul 28 02:43:27 2011
From: karim.liateni at free.fr (Karim)
Date: Thu, 28 Jul 2011 02:43:27 +0200
Subject: [Tutor] shlex parsing
In-Reply-To: <4E30AD08.6080600@pearwood.info>
References: <4E306771.8070408@free.fr> <4E30AD08.6080600@pearwood.info>
Message-ID: <4E30B0AF.3020903@free.fr>

On 07/28/2011 02:27 AM, Steven D'Aprano wrote:
> Karim wrote:
>>
>> Hello All,
>>
>> I would like to parse this TCL command line with shlex:
>>
>> '-option1 [get_rule A1 B2] -option2 $VAR -option3 TAG'
>>
>> And I want to get the splitted list:
>>
>> ['-option1', '[get_rule A1 B2]', '-option2',  '$VAR', '-option3',  
>> 'TAG']
>>
>> Then I will gather in tuple 2 by 2 the arguments.
>>
>> I tried to the shlec properties attributes 'quotes', 'whitespace', 
>> etc...
>
> I don't understand what you are doing here. Please show the code you use.
>
> The shlex module doesn't support bracketed expressions. I recommend 
> you write a post-processor. Start with doing this:
>
> >>> import shlex
> >>> text = '-option1 [get_rule A1 B2] -option2 $VAR -option3 TAG'
> >>> shlex.split(text)
> ['-option1', '[get_rule', 'A1', 'B2]', '-option2', '$VAR', '-option3', 
> 'TAG']
>
> then take that list and reassemble the pieces starting with '[' until 
> ']' Something like this, untested:
>
>
> def reassemble(items):
>     result = []
>     bracketed = False
>     current = ''
>     for item in items:
>         if item.startswith('['):
>             bracketed = True
>         if bracketed:
>             current += item
>             if item.endswith(']'):
>                 bracketed = False
>                 result.append(current)
>                 current = ''
>         else:
>              result.append(item)
>     return result
>
>
>

Yes Steven this is the kind of code I wrote in a post earlier, but I 
forget to reinit as you did current equal to _token in my code, thanks 
for that for showing me to simply if/elif/elif/else levels:

Previous code was:

"I ended up with this and gave up with shlex:"

split = ['-option1', '[get_rule', 'A1', 'B2]', '-option2', '$VAR', 
'-option3', 'TAG']

procedure_found = False
result          = []

for token in split:
     if not token.startswith('[') and not token.endswith(']') and not 
procedure_found:
         result.append(token)
     elif token.startswith('['):
         procedure_found = True
         _token = token
     elif token.endswith(']'):
         procedure_found = False
         _token += ' ' + token
         result.append(_token)
     else:
         _token += ' ' + token

print split
print result

>> But I make 'choux blanc'.
>
> I don't know what that means.
This means 'white cabbage' in french = 'unsuccessful try'

Cheers
Karim

From redacted@example.com  Thu Jul 28 02:45:50 2011
From: redacted@example.com (Alexander Quest)
Date: Wed, 27 Jul 2011 17:45:50 -0700
Subject: [Tutor] Assigning range
In-Reply-To: <4E30AFED.6000706@pearwood.info>
References: <CAHgjEe1uowv9NkJwG12iCa5yr=Yg4PWCTdRAtsSYchd+R1w2jQ@mail.gmail.com>
	<4E30AFED.6000706@pearwood.info>
Message-ID: <CAHgjEe3bVXXkX5shX2+8f=GDga13zDBdEXEjXAHLxZDQY5av-w@mail.gmail.com>

Thanks Steven- I'll try that out.

-Alex

On Wed, Jul 27, 2011 at 5:40 PM, Steven D'Aprano <steve at pearwood.info>wrote:

> Alexander Quest wrote:
>
>> Does anyone know how to assign a certain numerical range to a variable,
>> and
>> then choose the number that is the middle of that range? For example, I
>> want
>> to assign the variable "X" a range between 1 and 50, and then I want to
>> have
>> the middle of that range (25) return with some command when I call it
>> (perhaps rangemid or something like that?). In pseudocode, I am trying to
>> say X = range [1,50], return middle of range (which should return 25) but
>> I
>> don't know how to code it. This is for a basic program I'm trying to write
>> where the player thinks of a number and the computer tries to guess the
>> number in as few tries as possible. Thanks for any help!
>>
>
>
> Forget about using range, that just adds meaningless complexity.
>
> What is important is that you have a lower bound, and a higher bound: two
> numbers, instead of how ever many (possible thousands, or millions!) in
> range(low, high).
>
> middle = (low+high)//2
>
>
>
> --
> Steven
>
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110727/840d70a1/attachment.html>

From paradox at pobox.com  Thu Jul 28 03:11:56 2011
From: paradox at pobox.com (Thomas C. Hicks)
Date: Thu, 28 Jul 2011 09:11:56 +0800
Subject: [Tutor] Assigning range :p:
In-Reply-To: <CAHgjEe1uowv9NkJwG12iCa5yr=Yg4PWCTdRAtsSYchd+R1w2jQ@mail.gmail.com>
References: <CAHgjEe1uowv9NkJwG12iCa5yr=Yg4PWCTdRAtsSYchd+R1w2jQ@mail.gmail.com>
Message-ID: <20110728091156.53e68a5f@midgel>

On Wed, 27 Jul 2011 20:16:31 -0400
Alexander Quest <redacted@example.com> wrote:

> Does anyone know how to assign a certain numerical range to a
> variable, and then choose the number that is the middle of that
> range? For example, I want to assign the variable "X" a range between
> 1 and 50, and then I want to have the middle of that range (25)
> return with some command when I call it (perhaps rangemid or
> something like that?). In pseudocode, I am trying to say X = range
> [1,50], return middle of range (which should return 25) but I don't
> know how to code it. This is for a basic program I'm trying to write
> where the player thinks of a number and the computer tries to guess
> the number in as few tries as possible. Thanks for any help!
> 
> -Alex

There are probably better ways but this worked for me:

x=range(1,50)
mid=x[len(x)/2]

You do have to keep in mind the way python counts list indices for a
range call - i.e. x=range(1,50) will give you a list with all numbers 1
to 49 in it.

Hope that helps!

tom

From pedrooconnell at gmail.com  Thu Jul 28 03:58:01 2011
From: pedrooconnell at gmail.com (Pete O'Connell)
Date: Thu, 28 Jul 2011 11:28:01 +0930
Subject: [Tutor] how to temporarily disable a function
Message-ID: <CAF9PEE6qSC=d4Jzh2hiEdYcbjRX8m2TBR-+4VdA5Gij3zqexEQ@mail.gmail.com>

Hi I was wondering if there is a way to disable a function.
Hi have a GUI grid snapping function that I use in a program called Nuke
(the film compositing software)

Here is the function (which loads when Nuke loads):
#######################
def theAutoplaceSnap():
    try:
        nuke.thisNode().autoplace()
        n = nuke.allNodes();
        for i in n:
          nuke.autoplaceSnap(i)
    except:
        pass

nuke.addOnUserCreate(theAutoplaceSnap)
###################################

I have many functions which get loaded, but this particular one needs to be
disabled when I am viewing another compositors script in the gui.

I have a python script editor in Nuke in which I can run code if need be to
run code on the fly.

Help
-- 
Pete
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110728/15df0685/attachment-0001.html>

From donald.ww at me.com  Thu Jul 28 05:16:05 2011
From: donald.ww at me.com (Donald Wilson)
Date: Wed, 27 Jul 2011 23:16:05 -0400
Subject: [Tutor] Assigning range
In-Reply-To: <CAHgjEe1uowv9NkJwG12iCa5yr=Yg4PWCTdRAtsSYchd+R1w2jQ@mail.gmail.com>
References: <CAHgjEe1uowv9NkJwG12iCa5yr=Yg4PWCTdRAtsSYchd+R1w2jQ@mail.gmail.com>
Message-ID: <CFEC17CA-10CF-45C9-A0FE-DB410DA71FA8@me.com>

You could start with an anonymous function using the lambda operator, such as:

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

mid_range = lambda x: x[len(x) // 2]

Note: If you use len(x) / 2 in python 3.x you will get a TypeError because the division operator / returns a float. Floor // returns an int in 2.x and 3.x.

Then use either:

x = range(1000, 4001)
mid_x = mid_range(x) # mid_x == 2500

or?

mid_x = mid_range(range(500, 751)) # mid_x == 625

etc. to retrieve the middle element.

You can extract the mid point of any sequence type, such as a string, using this function.

mid_x = mid_range(?12345678987654321?) # mid_x == ?9?

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

middle_number = lambda lo, hi: abs(lo - hi) // 2

will work if you just need the mid point of two numbers; either ints or floats.

mid_x = middle_number(0, 1000) # mid_x = 500

DW

On Jul 27, 2011, at 8:16 PM, Alexander Quest wrote:

> Does anyone know how to assign a certain numerical range to a variable, and then choose the number that is the middle of that range? For example, I want to assign the variable "X" a range between 1 and 50, and then I want to have the middle of that range (25) return with some command when I call it (perhaps rangemid or something like that?). In pseudocode, I am trying to say X = range [1,50], return middle of range (which should return 25) but I don't know how to code it. This is for a basic program I'm trying to write where the player thinks of a number and the computer tries to guess the number in as few tries as possible. Thanks for any help!
> 
> -Alex
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From redacted@example.com  Thu Jul 28 07:38:19 2011
From: redacted@example.com (Alexander Quest)
Date: Wed, 27 Jul 2011 22:38:19 -0700
Subject: [Tutor] Assigning range
In-Reply-To: <CFEC17CA-10CF-45C9-A0FE-DB410DA71FA8@me.com>
References: <CAHgjEe1uowv9NkJwG12iCa5yr=Yg4PWCTdRAtsSYchd+R1w2jQ@mail.gmail.com>
	<CFEC17CA-10CF-45C9-A0FE-DB410DA71FA8@me.com>
Message-ID: <CAHgjEe2Vz5Te+sC8SSy3DJq7ZjiJBN0+_H7nMiq119atHV9XtA@mail.gmail.com>

Thanks for that Donald!

-Alex

On Wed, Jul 27, 2011 at 8:16 PM, Donald Wilson <donald.ww at me.com> wrote:

> You could start with an anonymous function using the lambda operator, such
> as:
>
> ------------------------------------------------------------
>
> mid_range = lambda x: x[len(x) // 2]
>
> Note: If you use len(x) / 2 in python 3.x you will get a TypeError because
> the division operator / returns a float. Floor // returns an int in 2.x and
> 3.x.
>
> Then use either:
>
> x = range(1000, 4001)
> mid_x = mid_range(x) # mid_x == 2500
>
> or?
>
> mid_x = mid_range(range(500, 751)) # mid_x == 625
>
> etc. to retrieve the middle element.
>
> You can extract the mid point of any sequence type, such as a string, using
> this function.
>
> mid_x = mid_range(?12345678987654321?) # mid_x == ?9?
>
> ------------------------------------------------------------
>
> middle_number = lambda lo, hi: abs(lo - hi) // 2
>
> will work if you just need the mid point of two numbers; either ints or
> floats.
>
> mid_x = middle_number(0, 1000) # mid_x = 500
>
> DW
>
> On Jul 27, 2011, at 8:16 PM, Alexander Quest wrote:
>
> > Does anyone know how to assign a certain numerical range to a variable,
> and then choose the number that is the middle of that range? For example, I
> want to assign the variable "X" a range between 1 and 50, and then I want to
> have the middle of that range (25) return with some command when I call it
> (perhaps rangemid or something like that?). In pseudocode, I am trying to
> say X = range [1,50], return middle of range (which should return 25) but I
> don't know how to code it. This is for a basic program I'm trying to write
> where the player thinks of a number and the computer tries to guess the
> number in as few tries as possible. Thanks for any help!
> >
> > -Alex
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110727/35a81a1f/attachment.html>

From qbits143 at gmail.com  Thu Jul 28 08:28:02 2011
From: qbits143 at gmail.com (qbits143 at gmail.com)
Date: Thu, 28 Jul 2011 09:28:02 +0300
Subject: [Tutor] python Module for Windows Active Directory
Message-ID: <067dbba75d8eba4cbfb7563a7cbcdd86@win-w8>

An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110728/6de7c89c/attachment.html>

From alan.gauld at btinternet.com  Thu Jul 28 09:52:47 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 28 Jul 2011 08:52:47 +0100
Subject: [Tutor] how to temporarily disable a function
In-Reply-To: <CAF9PEE6qSC=d4Jzh2hiEdYcbjRX8m2TBR-+4VdA5Gij3zqexEQ@mail.gmail.com>
References: <CAF9PEE6qSC=d4Jzh2hiEdYcbjRX8m2TBR-+4VdA5Gij3zqexEQ@mail.gmail.com>
Message-ID: <4E31154F.8020805@btinternet.com>

Pete O'Connell wrote:
> Hi I was wondering if there is a way to disable a function.
> Hi have a GUI grid snapping function that I use in a program called Nuke
> (the film compositing software)

simply change the binding of widget to function.
Then change it back to re-enable it.

You don't say which GUI framework you are using so we can't give sample 
code but most GUIs offer a way to dynamically modify event bindings.

HTH,

Alan G.

From d at davea.name  Thu Jul 28 10:44:22 2011
From: d at davea.name (Dave Angel)
Date: Thu, 28 Jul 2011 04:44:22 -0400
Subject: [Tutor] how to temporarily disable a function
In-Reply-To: <CAF9PEE6qSC=d4Jzh2hiEdYcbjRX8m2TBR-+4VdA5Gij3zqexEQ@mail.gmail.com>
References: <CAF9PEE6qSC=d4Jzh2hiEdYcbjRX8m2TBR-+4VdA5Gij3zqexEQ@mail.gmail.com>
Message-ID: <4E312166.2030807@davea.name>

On 07/27/2011 09:58 PM, Pete O'Connell wrote:
> Hi I was wondering if there is a way to disable a function.
> Hi have a GUI grid snapping function that I use in a program called Nuke
> (the film compositing software)
>
> Here is the function (which loads when Nuke loads):
> #######################
> def theAutoplaceSnap():
>      try:
>          nuke.thisNode().autoplace()
>          n = nuke.allNodes();
>          for i in n:
>            nuke.autoplaceSnap(i)
>      except:
>          pass
>
> nuke.addOnUserCreate(theAutoplaceSnap)
> ###################################
>
> I have many functions which get loaded, but this particular one needs to be
> disabled when I am viewing another compositors script in the gui.
>
> I have a python script editor in Nuke in which I can run code if need be to
> run code on the fly.
>
> Help
>
>
Presumably that function is defined in a different module than the one 
you're going to "disable" it from.  So, what you're attempting is 
commonly called "monkeypatching."

Let's say the module is   snapper  (in a file snapper.py).

All you probably need is to substitute another do-nothing function in 
its place.

import snapper

def donothing():
     return

snapper.theAutoplaceSnap = donothing

If it will need to be restored later, you can copy it to a variable in 
your own module, and then copy it back later.

-- 

DaveA

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110728/cb86d7f6/attachment.html>

From __peter__ at web.de  Thu Jul 28 11:08:42 2011
From: __peter__ at web.de (Peter Otten)
Date: Thu, 28 Jul 2011 11:08:42 +0200
Subject: [Tutor] how to temporarily disable a function
References: <CAF9PEE6qSC=d4Jzh2hiEdYcbjRX8m2TBR-+4VdA5Gij3zqexEQ@mail.gmail.com>
Message-ID: <j0r8ul$j7s$1@dough.gmane.org>

Pete O'Connell wrote:

> Hi I was wondering if there is a way to disable a function.
> Hi have a GUI grid snapping function that I use in a program called Nuke
> (the film compositing software)
> 
> Here is the function (which loads when Nuke loads):
> #######################
> def theAutoplaceSnap():
>     try:
>         nuke.thisNode().autoplace()
>         n = nuke.allNodes();
>         for i in n:
>           nuke.autoplaceSnap(i)
>     except:
>         pass
> 
> nuke.addOnUserCreate(theAutoplaceSnap)
> ###################################
> 
> I have many functions which get loaded, but this particular one needs to
> be disabled when I am viewing another compositors script in the gui.
> 
> I have a python script editor in Nuke in which I can run code if need be
> to run code on the fly.

http://docs.thefoundry.co.uk/nuke/63/pythondevguide/callbacks.html#onusercreate

suggests that you can remove the callback with

nuke.removeOnUserCreate(theAutoplaceSnap)

You can later add it back with

nuke.addOnUserCreate(theAutoplaceSnap)

like in the code snippet you provided. If the add/removeOnUserCreate() calls 
occur in another module than the one theAutplaceSnap() is defined in you 
need to import that first and use qualified names (e. g. 
some_module.theAutoplaceSnap).



From karim.liateni at free.fr  Thu Jul 28 13:32:12 2011
From: karim.liateni at free.fr (Karim)
Date: Thu, 28 Jul 2011 13:32:12 +0200
Subject: [Tutor] Is it bad practise to write __all__ like that
Message-ID: <4E3148BC.5080001@free.fr>


Hello,

__all__ = 'api db input output tcl'.split()

or

__all__ = """
                api
                db
                input
                output
                tcl
                """.split()

for lazy boy ;o). It is readable as well.
What do you think?

Cheers
Karim

From steve at pearwood.info  Thu Jul 28 15:00:33 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 28 Jul 2011 23:00:33 +1000
Subject: [Tutor] Is it bad practise to write __all__ like that
In-Reply-To: <4E3148BC.5080001@free.fr>
References: <4E3148BC.5080001@free.fr>
Message-ID: <4E315D71.7000705@pearwood.info>

Karim wrote:
> 
> Hello,
> 
> __all__ = 'api db input output tcl'.split()

Yes, it's lazy, no it is not bad practice. I wouldn't do it myself, but 
I wouldn't object if somebody else did it.



-- 
Steven


From mail at timgolden.me.uk  Thu Jul 28 17:02:47 2011
From: mail at timgolden.me.uk (Tim Golden)
Date: Thu, 28 Jul 2011 16:02:47 +0100
Subject: [Tutor] python Module for Windows Active Directory
In-Reply-To: <067dbba75d8eba4cbfb7563a7cbcdd86@win-w8>
References: <067dbba75d8eba4cbfb7563a7cbcdd86@win-w8>
Message-ID: <4E317A17.7060400@timgolden.me.uk>

On 28/07/2011 07:28, qbits143 at gmail.com wrote:
> Hi,
>
> Which is the best package/module in Python to work with Windows Active
> Directory?
>
> I may need to create multiple OUs, set different users and computers and
> fill their individual attributes. Later i may need to modify/delete and
> then may need to check them for its availability.

You could try my active_directory module:

   http://timgolden.me.uk/python/active_directory.html

although there's a much-improved version in development
(and actively used here at work). If you're interested,
look at:

   http://svn.timgolden.me.uk/active_directory/branches/rework/

TJG

From armvrt at gmail.com  Thu Jul 28 17:50:54 2011
From: armvrt at gmail.com (Shwinn Ricci)
Date: Thu, 28 Jul 2011 11:50:54 -0400
Subject: [Tutor] KeyError?
Message-ID: <CAM-hM0WUsf8U_ixiEQB=OO0UfoTuPhCMsFXoS0Xg3k487mORyA@mail.gmail.com>

I have an excel file that I am reading cell values from and putting them
into a dictionary. the dictionary looks like this:

scafPositions = {position[j]: direction[j]}

where position[j] is exclusively floating/numerical values and direction[j]
is exclusively strings.

When I try to find whether a test value val is in the array of positions,
and then try to look its direction up with ScafPositions[val], I get a
KeyError. Is this because my data isn't standalone numbers, but numbers that
are calculated based off other cells? Or can I not test for val?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110728/dc5445dc/attachment.html>

From eire1130 at gmail.com  Thu Jul 28 17:59:28 2011
From: eire1130 at gmail.com (James Reynolds)
Date: Thu, 28 Jul 2011 11:59:28 -0400
Subject: [Tutor] KeyError?
In-Reply-To: <CAM-hM0WUsf8U_ixiEQB=OO0UfoTuPhCMsFXoS0Xg3k487mORyA@mail.gmail.com>
References: <CAM-hM0WUsf8U_ixiEQB=OO0UfoTuPhCMsFXoS0Xg3k487mORyA@mail.gmail.com>
Message-ID: <CAE0jAbqKN+7fuZLnijCtF=1kkxJfOzLpaVrE9RxMxEy_hi97CQ@mail.gmail.com>

On Thu, Jul 28, 2011 at 11:50 AM, Shwinn Ricci <armvrt at gmail.com> wrote:

> I have an excel file that I am reading cell values from and putting them
> into a dictionary. the dictionary looks like this:
>
> scafPositions = {position[j]: direction[j]}
>
> where position[j] is exclusively floating/numerical values and direction[j]
> is exclusively strings.
>
> When I try to find whether a test value val is in the array of positions,
> and then try to look its direction up with ScafPositions[val], I get a
> KeyError. Is this because my data isn't standalone numbers, but numbers that
> are calculated based off other cells? Or can I not test for val?
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

Did you try printing the contents of scafPositions to see what it contains,
first?

Also, a traceback is helpful.

As far as introspection, which module are you using to read the excel files?
There's at least two that I know of.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110728/3c7820fb/attachment.html>

From wprins at gmail.com  Thu Jul 28 18:00:11 2011
From: wprins at gmail.com (Walter Prins)
Date: Thu, 28 Jul 2011 17:00:11 +0100
Subject: [Tutor] KeyError?
In-Reply-To: <CAM-hM0WUsf8U_ixiEQB=OO0UfoTuPhCMsFXoS0Xg3k487mORyA@mail.gmail.com>
References: <CAM-hM0WUsf8U_ixiEQB=OO0UfoTuPhCMsFXoS0Xg3k487mORyA@mail.gmail.com>
Message-ID: <CANLXbfACMXFCJskF2T=DSAfYT7y=t7do7RC7titmsW1s0iBkpQ@mail.gmail.com>

On 28 July 2011 16:50, Shwinn Ricci <armvrt at gmail.com> wrote:

> I have an excel file that I am reading cell values from and putting them
> into a dictionary. the dictionary looks like this:
>
> scafPositions = {position[j]: direction[j]}
>
> where position[j] is exclusively floating/numerical values and direction[j]
> is exclusively strings.
>
> When I try to find whether a test value val is in the array of positions,
> and then try to look its direction up with ScafPositions[val], I get a
> KeyError. Is this because my data isn't standalone numbers, but numbers that
> are calculated based off other cells? Or can I not test for val?
>

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

I quote:
"Python raises a *KeyError* whenever a dict() object is requested (using the
format a = adict[key]) and the key is not in the dictionary. If you don't
want to have an exception but would rather a default value used instead, you
can use the get() method: "

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110728/de96e5e0/attachment.html>

From ramit.prasad at jpmchase.com  Thu Jul 28 18:11:27 2011
From: ramit.prasad at jpmchase.com (Prasad, Ramit)
Date: Thu, 28 Jul 2011 12:11:27 -0400
Subject: [Tutor] KeyError?
In-Reply-To: <CAM-hM0WUsf8U_ixiEQB=OO0UfoTuPhCMsFXoS0Xg3k487mORyA@mail.gmail.com>
References: <CAM-hM0WUsf8U_ixiEQB=OO0UfoTuPhCMsFXoS0Xg3k487mORyA@mail.gmail.com>
Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA6F1D0B5@EMARC112VS01.exchad.jpmchase.net>

From: tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org] On Behalf Of Shwinn Ricci
Sent: Thursday, July 28, 2011 10:51 AM
To: tutor at python.org
Subject: [Tutor] KeyError?

I have an excel file that I am reading cell values from and putting them into a dictionary. the dictionary looks like this:

scafPositions = {position[j]: direction[j]}

where position[j] is exclusively floating/numerical values and direction[j] is exclusively strings.

When I try to find whether a test value val is in the array of positions, and then try to look its direction up with ScafPositions[val], I get a KeyError. Is this because my data isn't standalone numbers, but numbers that are calculated based off other cells? Or can I not test for val?
======================================

Your problem is probably that you are reassigning a new dictionary to the name scafPositions each time instead of updating it. You should have something like the following.

scafPositions = {}

#loop structure here:
    #do stuff
    scafPositions[ position[j] ] = direction[j]



Ramit


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





This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase &
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110728/ef2c4828/attachment-0001.html>

From eire1130 at gmail.com  Thu Jul 28 18:42:44 2011
From: eire1130 at gmail.com (James Reynolds)
Date: Thu, 28 Jul 2011 12:42:44 -0400
Subject: [Tutor] KeyError?
In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA6F1D0B5@EMARC112VS01.exchad.jpmchase.net>
References: <CAM-hM0WUsf8U_ixiEQB=OO0UfoTuPhCMsFXoS0Xg3k487mORyA@mail.gmail.com>
	<0604E20B5F6F2F4784C9C8C71C5DD4DD2EA6F1D0B5@EMARC112VS01.exchad.jpmchase.net>
Message-ID: <CAE0jAbpHL2oKN8xCFOqNGbLWyRMTBhBzFGnXSXd=OjOFzXkmWw@mail.gmail.com>

On Thu, Jul 28, 2011 at 12:11 PM, Prasad, Ramit
<ramit.prasad at jpmchase.com>wrote:

> *From:* tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:
> tutor-bounces+ramit.prasad=jpmchase.com at python.org] *On Behalf Of *Shwinn
> Ricci
> *Sent:* Thursday, July 28, 2011 10:51 AM
> *To:* tutor at python.org
> *Subject:* [Tutor] KeyError?****
>
> ** **
>
> I have an excel file that I am reading cell values from and putting them
> into a dictionary. the dictionary looks like this:
>
> scafPositions = {position[j]: direction[j]}
>
> where position[j] is exclusively floating/numerical values and direction[j]
> is exclusively strings.
>
> When I try to find whether a test value val is in the array of positions,
> and then try to look its direction up with ScafPositions[val], I get a
> KeyError. Is this because my data isn't standalone numbers, but numbers that
> are calculated based off other cells? Or can I not test for val?****
>
> ======================================****
>
> ** **
>
> Your problem is probably that you are reassigning a new dictionary to the
> name scafPositions each time instead of updating it. You should have
> something like the following.****
>
> ** **
>
> scafPositions = {}****
>
> ** **
>
> #loop structure here:****
>
>     #do stuff****
>
>     scafPositions[ position[j] ] = direction[j]****
>
>
>



Or it could be it's not introspecting the formula within excel and his key
is the string "=A1*sheet2!$B$1"or it could be he's looking for a float / int
when in reality it's a string (because it must be converted explicitly).

Without a traceback and the code, it's hard to know for sure.

My guess is leading towards introspection.

As far as printing the contents, once you create your dict with all the data
just use the print statement / function depending on your version of python

print scafPositions or print(scafPositions)

You could loop through it as well

for key, value in scafPositions.items():
    print key, value

This will give you an idea of what is in the dict.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110728/929bd87e/attachment.html>

From g.nius.ck at gmail.com  Thu Jul 28 19:02:12 2011
From: g.nius.ck at gmail.com (Christopher King)
Date: Thu, 28 Jul 2011 13:02:12 -0400
Subject: [Tutor] how to temporarily disable a function
In-Reply-To: <j0r8ul$j7s$1@dough.gmane.org>
References: <CAF9PEE6qSC=d4Jzh2hiEdYcbjRX8m2TBR-+4VdA5Gij3zqexEQ@mail.gmail.com>
	<j0r8ul$j7s$1@dough.gmane.org>
Message-ID: <CAKBg9Z0pBEjNRJmFjyW4EDZ_+yL+KoLSPDaHw5SWJOPSArGoGw@mail.gmail.com>

On Thu, Jul 28, 2011 at 5:08 AM, Peter Otten <__peter__ at web.de> wrote:

> Pete O'Connell wrote:
>
> > Hi I was wondering if there is a way to disable a function.
>
>
You could use this decorator:
class Disabler(object):
    def __init__(self, old_function):
        self.__old = old_function
        self.enabled=True
    def __call__(self, *arg, **kwd):
        if enabled: return self.__old(*arg, **kwd)
    def enable(self): self.enabled = True
    def disable(self): self.enabled=False


> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110728/01b4e86e/attachment.html>

From g.nius.ck at gmail.com  Thu Jul 28 19:12:07 2011
From: g.nius.ck at gmail.com (Christopher King)
Date: Thu, 28 Jul 2011 13:12:07 -0400
Subject: [Tutor] Assigning range :p:
In-Reply-To: <20110728091156.53e68a5f@midgel>
References: <CAHgjEe1uowv9NkJwG12iCa5yr=Yg4PWCTdRAtsSYchd+R1w2jQ@mail.gmail.com>
	<20110728091156.53e68a5f@midgel>
Message-ID: <CAKBg9Z3-ieQY62QrQasHO_Uk3r1+HnktbJZ0H9D9KvhJ=f2+fw@mail.gmail.com>

On Wed, Jul 27, 2011 at 9:11 PM, Thomas C. Hicks <paradox at pobox.com> wrote:

> On Wed, 27 Jul 2011 20:16:31 -0400
> Alexander Quest <redacted@example.com> wrote:

 x=range(1,50)
> mid=x[len(x)/2]
>
> You would have to make sure there is a way to work around decimal points in
the division. Also, I would try it in practice. (remember range(1, 50) does
not include 50.)

> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110728/5efb946b/attachment.html>

From adam.jtm30 at gmail.com  Thu Jul 28 19:11:41 2011
From: adam.jtm30 at gmail.com (Adam Bark)
Date: Thu, 28 Jul 2011 17:11:41 +0000 (UTC)
Subject: [Tutor] OT: Drag and Drop GUI IDE ideas
References: <CANWBxgaPVmgyjWGCtcFHuHCa0Gx_g-yD-wHmh5zzWde1xYBT3w@mail.gmail.com>
Message-ID: <loom.20110728T190833-145@post.gmane.org>

Rance Hall <ranceh <at> gmail.com> writes:
> We want the students to develop a small app in the process, It could
> be a firefox extension, mobile phone app, or any other type simple
> structure.
> 
> The catch is that the class is for non-programmers to try to get them
> introduced to the field.  We would like to use a gui ide that can
> essentially hide the code from the programmer and connect widgets with
> the gui.
> 
> We want them to be able to look at the code and analyze it.
> 
> We would prefer open source (read: free as in beer) tools.
> 
> Does anyone have any ideas of tools that can do this?
> 
> we are open to any idea, android sdk and gui, ipad sdk and some gui tool, etc.
> 
> Thanks for your time.
> 
> Rance

Hi, this isn't free but seems to tick all your other boxes
http://radicalbreeze.com/ It gives a graphical representation of your program as
well as access to the source code of your application. It creates code for many
different platforms including mobile ones and it's DRM free.
HTH,
Adam.



From susana.delgado_s at utzmg.edu.mx  Thu Jul 28 19:23:29 2011
From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez)
Date: Thu, 28 Jul 2011 12:23:29 -0500
Subject: [Tutor] Sum files' size
Message-ID: <CAFEP6HvS2vdEhT+vDE-dwZhvXXDw0FFPz4vXRe6nsBQQKxBSdA@mail.gmail.com>

I want to get the size of  3 files. I already completed this step. Then I
need to sum the 3 results I got. In order to do it I have the next code:

import os
file_list = []
folders = None
for root, folders, files in os.walk('C:\\'):
            file_list.extend(os.path.join(root,fi) for fi in files if
(fi.endswith.shp))
for row, filepath in enumerate(file_list, start=1):
            n = os.path.splitext(filepath)
            p = n[0]+'.prj'
            shx = n[0]+'.shx'
            s = os.path.getsize(filepath)

#Function to get size in humam readable terms:
            def sizeof_fmt(num):
                 for x in ['bytes','KB','MB','GB','TB']:
                      if num < 1024.0:
                           return "%3.1f%s" % (num, x)
                      num /= 1024.0

            kb = sizeof_fmt(s)
            shx1 = os.path.getsize(shx)
            kb2 = sizeof_fmt(shx1)

#Finally I want to sum the 3 terms:
total = kb+kb2+kb3
But the output I got is : 15.5KB108.0bytes169.0bytes

Does anyone have an idea how to fix it?
Thank you!!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110728/a9dde906/attachment-0001.html>

From alan.gauld at btinternet.com  Thu Jul 28 19:48:14 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 28 Jul 2011 18:48:14 +0100
Subject: [Tutor] Sum files' size
In-Reply-To: <CAFEP6HvS2vdEhT+vDE-dwZhvXXDw0FFPz4vXRe6nsBQQKxBSdA@mail.gmail.com>
References: <CAFEP6HvS2vdEhT+vDE-dwZhvXXDw0FFPz4vXRe6nsBQQKxBSdA@mail.gmail.com>
Message-ID: <4E31A0DE.1030605@btinternet.com>

Susana Iraiis Delgado Rodriguez wrote:
> I want to get the size of  3 files. I already completed this step. Then I
> need to sum the 3 results I got. In order to do it I have the next code:
> 
> import os
> file_list = []
> folders = None
> for root, folders, files in os.walk('C:\\'):
>             file_list.extend(os.path.join(root,fi) for fi in files if
> (fi.endswith.shp))
> for row, filepath in enumerate(file_list, start=1):
>             n = os.path.splitext(filepath)
>             p = n[0]+'.prj'
>             shx = n[0]+'.shx'
>             s = os.path.getsize(filepath)
> 
> #Function to get size in humam readable terms:
>             def sizeof_fmt(num):
>                  for x in ['bytes','KB','MB','GB','TB']:
>                       if num < 1024.0:
>                            return "%3.1f%s" % (num, x)

This returns a string value

>                       num /= 1024.0
> 
>             kb = sizeof_fmt(s)

So kb1 will be astring

>             shx1 = os.path.getsize(shx)
>             kb2 = sizeof_fmt(shx1)

And so will kb2

> #Finally I want to sum the 3 terms:
> total = kb+kb2+kb3

Where does kb3 come from?

> But the output I got is : 15.5KB108.0bytes169.0bytes
> 
> Does anyone have an idea how to fix it?
> Thank you!!

Looks like you are adding the strings. You need to get the
sum then call your format function on the total.

HTH,

Alan G.

From alan.gauld at btinternet.com  Thu Jul 28 19:48:14 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 28 Jul 2011 18:48:14 +0100
Subject: [Tutor] Sum files' size
In-Reply-To: <CAFEP6HvS2vdEhT+vDE-dwZhvXXDw0FFPz4vXRe6nsBQQKxBSdA@mail.gmail.com>
References: <CAFEP6HvS2vdEhT+vDE-dwZhvXXDw0FFPz4vXRe6nsBQQKxBSdA@mail.gmail.com>
Message-ID: <4E31A0DE.1030605@btinternet.com>

Susana Iraiis Delgado Rodriguez wrote:
> I want to get the size of  3 files. I already completed this step. Then I
> need to sum the 3 results I got. In order to do it I have the next code:
> 
> import os
> file_list = []
> folders = None
> for root, folders, files in os.walk('C:\\'):
>             file_list.extend(os.path.join(root,fi) for fi in files if
> (fi.endswith.shp))
> for row, filepath in enumerate(file_list, start=1):
>             n = os.path.splitext(filepath)
>             p = n[0]+'.prj'
>             shx = n[0]+'.shx'
>             s = os.path.getsize(filepath)
> 
> #Function to get size in humam readable terms:
>             def sizeof_fmt(num):
>                  for x in ['bytes','KB','MB','GB','TB']:
>                       if num < 1024.0:
>                            return "%3.1f%s" % (num, x)

This returns a string value

>                       num /= 1024.0
> 
>             kb = sizeof_fmt(s)

So kb1 will be astring

>             shx1 = os.path.getsize(shx)
>             kb2 = sizeof_fmt(shx1)

And so will kb2

> #Finally I want to sum the 3 terms:
> total = kb+kb2+kb3

Where does kb3 come from?

> But the output I got is : 15.5KB108.0bytes169.0bytes
> 
> Does anyone have an idea how to fix it?
> Thank you!!

Looks like you are adding the strings. You need to get the
sum then call your format function on the total.

HTH,

Alan G.


From sierra_mtnview at sbcglobal.net  Thu Jul 28 20:38:18 2011
From: sierra_mtnview at sbcglobal.net (Wayne Watson)
Date: Thu, 28 Jul 2011 11:38:18 -0700
Subject: [Tutor] Getting Idle to work in Win7
In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA6F1C8BC@EMARC112VS01.exchad.jpmchase.net>
References: <4E307E0C.2040801@sbcglobal.net>
	<CANLXbfCFzfzDnqOmvovrQqN79Pjk0=cY-e4AsSYCm=+28GTnVg@mail.gmail.com>
	<0604E20B5F6F2F4784C9C8C71C5DD4DD2EA6F1C8BC@EMARC112VS01.exchad.jpmchase.net>
Message-ID: <4E31AC9A.80304@sbcglobal.net>

An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110728/ab4a532c/attachment.html>

From ramit.prasad at jpmchase.com  Thu Jul 28 20:42:56 2011
From: ramit.prasad at jpmchase.com (Prasad, Ramit)
Date: Thu, 28 Jul 2011 14:42:56 -0400
Subject: [Tutor] Sum files' size
In-Reply-To: <CAFEP6HvS2vdEhT+vDE-dwZhvXXDw0FFPz4vXRe6nsBQQKxBSdA@mail.gmail.com>
References: <CAFEP6HvS2vdEhT+vDE-dwZhvXXDw0FFPz4vXRe6nsBQQKxBSdA@mail.gmail.com>
Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA700B5AA@EMARC112VS01.exchad.jpmchase.net>

>kb = sizeof_fmt(s)
>shx1 = os.path.getsize(shx)
>kb2 = sizeof_fmt(shx1)
> total = kb+kb2+kb3

Instead only retrieve the formatted output at the end. That way you will not have to worry about converting back from strings, nor have to worry about adding number with different units (e.g. 10KB + 10MB).

kb = s
kb2 = os.path.getsize(shx)
total = sizeof_fmt(kb+kb2+kb3)

Ramit


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



This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase &
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.

From rhettnaxel at gmail.com  Thu Jul 28 20:52:18 2011
From: rhettnaxel at gmail.com (Alexander)
Date: Thu, 28 Jul 2011 14:52:18 -0400
Subject: [Tutor] Getting Idle to work in Win7
In-Reply-To: <4E31AC9A.80304@sbcglobal.net>
References: <4E307E0C.2040801@sbcglobal.net>
	<CANLXbfCFzfzDnqOmvovrQqN79Pjk0=cY-e4AsSYCm=+28GTnVg@mail.gmail.com>
	<0604E20B5F6F2F4784C9C8C71C5DD4DD2EA6F1C8BC@EMARC112VS01.exchad.jpmchase.net>
	<4E31AC9A.80304@sbcglobal.net>
Message-ID: <CANS6qmAQhRvU4H3-L4M0TzAqKjd9oOgK2ARy++s_azR5Aamy0A@mail.gmail.com>

Hi Wayne. I'm interested in the issues your facing. Could you right click on
the IDLE shortcut in your start menu and tell me the details? Specifically
under:
*General*:* type of file, description, location, attributes*, (any *advanced
* attributes?);
*Shortcut*: tab, the *Target type*, *Target location *(if any),
*Target*, *Start
in* path, *Run *choice, any *Advanced *options?
*Compatability: *anything selected here?
*Security: *Are the permissions Full control?
*Details: **name, type, path, owner*
Looking forward to resolving the issue, Alexander.

On Thu, Jul 28, 2011 at 2:38 PM, Wayne Watson
<sierra_mtnview at sbcglobal.net>wrote:

>  I decided to re-install.  It looks like I'm in the same boat as before.
> Edit with IDLE isn't even a choice.
>
> I tried from the command line to run pythonw.exe, and that gave me the
> typical >>> input choice. Python at least works at that level. IDLE comes up
> with idle.pyw.
>
>
> On 7/27/2011 3:49 PM, Prasad, Ramit wrote:
>
>  *From:* tutor-bounces+ramit.prasad=jpmchase.com at python.org [
> mailto:tutor-bounces+ramit.prasad=jpmchase.com at python.org<tutor-bounces+ramit.prasad=jpmchase.com at python.org>]
> *On Behalf Of *Walter Prins
> *Sent:* Wednesday, July 27, 2011 4:39 PM
> *To:* tutor at python.org
> *Subject:* Re: [Tutor] Getting Idle to work in Win7****
>
> ** **
>
> Hi****
>
> On 27 July 2011 22:07, Wayne Watson <sierra_mtnview at sbcglobal.net> wrote:*
> ***
>
> It's been many months since I played with Python, and have forgotten how to
> bring up IDLE. If I simply click on a py file, I see what may be a dos
> window appear and quickly disappear. If I right-click on the file, and
> select IDLE, the same thing happens. If I go directly to All Programs, the
> same thing happens when I select IDLE.****
>
>
> There must be something wrong with your Python installation.
> Right-click->"Edit with Idle" and starting IDLE from All Programs works fine
> for me. (Win 7 64-bit, with both Python 2.7 and 3.2 installed.)  I suggest
> you reinstall Python as a start.  It might also be worthwhile to try to run
> your Python script from the command line, as well as starting Idle from the
> command line so you can see what error message might be printed.
>
> Cheers
>
> Walter****
>
> ** **
>
> Open cmd.exe and then navigate to the directory where Python is installed
> (C:\Python27) for me and then cd into the Lib\idlelib directory and run
> idle.bat. Hopefully there should be some errors that show in the window. If
> not you can try running it ?..\..\pythonw.exe idle.pyw? and hopefully that
> will show the problem.****
>
> ** **
>
> ** **
>
> Ramit****
>
> ** **
>
> ** **
>
> Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology****
>
> 712 Main Street | Houston, TX 77002****
>
> work phone: 713 - 216 - 5423****
>
> ** **
>
> ** **
>
> ** **
>
> ** **
>
> ** **
>
> This communication is for informational purposes only. It is not intended
> as an offer or solicitation for the purchase or sale of any financial
> instrument or as an official confirmation of any transaction. All market
> prices, data and other information are not warranted as to completeness or
> accuracy and are subject to change without notice. Any comments or
> statements made herein do not necessarily reflect those of JPMorgan Chase &
> Co., its subsidiaries and affiliates. This transmission may contain
> information that is privileged, confidential, legally privileged, and/or
> exempt from disclosure under applicable law. If you are not the intended
> recipient, you are hereby notified that any disclosure, copying,
> distribution, or use of the information contained herein (including any
> reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any
> attachments are believed to be free of any virus or other defect that might
> affect any computer system into which it is received and opened, it is the
> responsibility of the recipient to ensure that it is virus free and no
> responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and
> affiliates, as applicable, for any loss or damage arising in any way from
> its use. If you received this transmission in error, please immediately
> contact the sender and destroy the material in its entirety, whether in
> electronic or hard copy format. Thank you. Please refer to
> http://www.jpmorgan.com/pages/disclosures for disclosures relating to
> European legal entities.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:http://mail.python.org/mailman/listinfo/tutor
>
>
> --
>            Wayne Watson (Watson Adventures, Prop., Nevada City, CA)
>
>              (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
>               Obz Site:  39? 15' 7" N, 121? 2' 32" W, 2700 feet
>
>                   "The physicist uses ordinary words
>                   in a peculiar manner." -- Richard Feynma in
>                         The Character of Physical Law
>
>
>                     Web Page: <www.speckledwithstars.net/>
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Alexander
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110728/44d4e694/attachment.html>

From steve at pearwood.info  Thu Jul 28 21:43:57 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 29 Jul 2011 05:43:57 +1000
Subject: [Tutor] Sum files' size
In-Reply-To: <CAFEP6HvS2vdEhT+vDE-dwZhvXXDw0FFPz4vXRe6nsBQQKxBSdA@mail.gmail.com>
References: <CAFEP6HvS2vdEhT+vDE-dwZhvXXDw0FFPz4vXRe6nsBQQKxBSdA@mail.gmail.com>
Message-ID: <4E31BBFD.1070600@pearwood.info>

Susana Iraiis Delgado Rodriguez wrote:
> I want to get the size of  3 files. I already completed this step. Then I
> need to sum the 3 results I got. In order to do it I have the next code:
[...]
> #Finally I want to sum the 3 terms:
> total = kb+kb2+kb3
> But the output I got is : 15.5KB108.0bytes169.0bytes
> 
> Does anyone have an idea how to fix it?


Sum the three terms while they are still numbers, before you convert 
them into strings with units.




-- 
Steven


From eire1130 at gmail.com  Thu Jul 28 21:53:26 2011
From: eire1130 at gmail.com (James Reynolds)
Date: Thu, 28 Jul 2011 15:53:26 -0400
Subject: [Tutor] Fwd:  KeyError?
In-Reply-To: <CAM-hM0VQ9CDmwV7_2UaW+0SbVsOasTA6APRFE+x+-v7_aGp2+Q@mail.gmail.com>
References: <CAM-hM0WUsf8U_ixiEQB=OO0UfoTuPhCMsFXoS0Xg3k487mORyA@mail.gmail.com>
	<0604E20B5F6F2F4784C9C8C71C5DD4DD2EA6F1D0B5@EMARC112VS01.exchad.jpmchase.net>
	<CAE0jAbpHL2oKN8xCFOqNGbLWyRMTBhBzFGnXSXd=OjOFzXkmWw@mail.gmail.com>
	<CAM-hM0VQ9CDmwV7_2UaW+0SbVsOasTA6APRFE+x+-v7_aGp2+Q@mail.gmail.com>
Message-ID: <CAE0jAbo0GpdK2pK9-4JPzgpiuVRMAU=DtY_PnFZsWF1c=1x0SQ@mail.gmail.com>

---------- Forwarded message ----------
From: Shwinn Ricci <armvrt at gmail.com>
Date: Thu, Jul 28, 2011 at 1:13 PM
Subject: Re: [Tutor] KeyError?
To: James Reynolds <eire1130 at gmail.com>




On Thu, Jul 28, 2011 at 12:42 PM, James Reynolds <eire1130 at gmail.com> wrote:

>
>
> On Thu, Jul 28, 2011 at 12:11 PM, Prasad, Ramit <ramit.prasad at jpmchase.com
> > wrote:
>
>> *From:* tutor-bounces+ramit.prasad=jpmchase.com at python.org [mailto:
>> tutor-bounces+ramit.prasad=jpmchase.com at python.org] *On Behalf Of *Shwinn
>> Ricci
>> *Sent:* Thursday, July 28, 2011 10:51 AM
>> *To:* tutor at python.org
>> *Subject:* [Tutor] KeyError?****
>>
>> ** **
>>
>> I have an excel file that I am reading cell values from and putting them
>> into a dictionary. the dictionary looks like this:
>>
>> scafPositions = {position[j]: direction[j]}
>>
>> where position[j] is exclusively floating/numerical values and
>> direction[j] is exclusively strings.
>>
>> When I try to find whether a test value val is in the array of positions,
>> and then try to look its direction up with ScafPositions[val], I get a
>> KeyError. Is this because my data isn't standalone numbers, but numbers that
>> are calculated based off other cells? Or can I not test for val?****
>>
>> ======================================****
>>
>> ** **
>>
>> Your problem is probably that you are reassigning a new dictionary to the
>> name scafPositions each time instead of updating it. You should have
>> something like the following.****
>>
>> ** **
>>
>> scafPositions = {}****
>>
>> ** **
>>
>> #loop structure here:****
>>
>>     #do stuff****
>>
>>     scafPositions[ position[j] ] = direction[j]****
>>
>>
>>
>
> this is my code:
>

def LookUp(helix, scafPos):

 # create dictionaries (keyed by vstrand #) of
 # scaffold position with value representing orientation

        book = xlrd.open_workbook('CoordinatesSpreadsheet.xls')
        sheet = book.sheet_by_index(0)
        cols = sheet.row_values(2,1,150)
       9
        position = {}
        direction = {}
        scafPositions = {}
        for i in range(len(cols)):
            rows = sheet.col_values(i+2, 5, 500)

            #create lists of position and direction, sets up dictionary
            for j in range(len(rows)):
                          position[j] = float(sheet.cell(j+5, i+3).value)
                          direction[j] = sheet.cell(j+5, i+1).value

                          scafPositions[position[j]] = direction[j]
            i += 5


   #returns value for appropriate caDNAno position, which is represented as
a concatenation of the input helix and scaffold position
        val = float(helix) + (float(scafPos) * 0.001)

        if (scafPositions[val] == "out"):
           print "Warning: Base pointing outwards"



        return scafPositions[val]


def main(argv):
    return LookUp(sys.argv[1], sys.argv[2])


if __name__ == "__main__":
    main(sys.argv[1:])

perhaps im on the wrong sheet? all the tutorials say "sheet0" but I'm on
openoffice and the first sheet is 'sheet1'

>
> Or it could be it's not introspecting the formula within excel and his key
> is the string "=A1*sheet2!$B$1"or it could be he's looking for a float / int
> when in reality it's a string (because it must be converted explicitly).
>
> Without a traceback and the code, it's hard to know for sure.
>
> My guess is leading towards introspection.
>
> As far as printing the contents, once you create your dict with all the
> data just use the print statement / function depending on your version of
> python
>
> print scafPositions or print(scafPositions)
>
> You could loop through it as well
>
> for key, value in scafPositions.items():
>     print key, value
>
> This will give you an idea of what is in the dict.
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

Sending this whole thing to the entire list. You should send replies to the
list as well.

going to go bit by bit here:


def LookUp(helix, scafPos):
>         book = xlrd.open_workbook('CoordinatesSpreadsheet.xls')
>         sheet = book.sheet_by_index(0)


ok good so far (but don't capitalize functions)

        cols = sheet.row_values(2,1,150)


Here you are getting a slice of columns, from a single row. About 149
columns worth.

        position = {}
>         direction = {}


You don't need these dictionaries for anything useful as far as I can tell,
so drop them

        for i in range(len(cols)):
>             rows = sheet.col_values(i+2, 5, 500)


This doesn't make sense with the above, you are now taking a slice of rows
from a single column. I would probably rewrite this (i'll give you a
suggestion in a moment)

            for j in range(len(rows)):
>                 position[j] = float(sheet.cell(j+5, i+3).value)
>                 direction[j] = sheet.cell(j+5, i+1).value
>                 scafPositions[position[j]] = direction[j]
>             i += 5



Ok, so position isn't a dict anymore. Just make position a straight variable
(position = float(sheet.cell(j+5, i+3).value)) and the same with direction,
like this:

            for j in range(len(rows)):
>                 position = float(sheet.cell(j+5, i+3).value)
>                 direction = sheet.cell(j+5, i+1).value
>                 scafPositions[position] = direction
>             i += 5


I'm a big fan of naming things, even when you don't need them, but
technically you don't need the direction variable. You could just do:


            for j in range(len(rows)):
>                 position = float(sheet.cell(j+5, i+3).value)
>                 scafPositions[position] = sheet.cell(j+5, i+1).value
>             i += 5


The  i += 5 doesn't make much sense to me.

Your saying the data you want is in each fifth column relative to the next
column in "cols". So, if it's on column 4, the next column looked at would
be 9, 14, etc. Once those rows are complete, it will look at 5,10,15 etc,
prior to the offsets.

        val = float(helix) + (float(scafPos) * 0.001)


How do you know that this calculation exists the spreadsheet? Can you be
assured of it, 100% of the time with no failures?

        if (scafPositions[val] == "out"):
>             print "Warning: Base pointing outwards"



Without seeing your traceback, I'll bet this is where its throwing the
error.

I would probably have it more like this:

def lookup(helix, scafPos):
>  # create dictionaries (keyed by vstrand #) of
>  # scaffold position with value representing orientation
>
>         book = xlrd.open_workbook('CoordinatesSpreadsheet.xls')
>         sheet = book.sheet_by_index(0)
>         scafPositions = {}
>         for i in range(sheet.ncols)[1:150]: #ncols and nrows is a builtin
> to this module, returning the count of total rows or columns.
>             #range is a list, so you can just take a slice of that.
>             for j in range(sheet.nrows)[5:500]:
>                 position = float(sheet.cell(j+5, i+3).value) #I'm going to
> assume you want to look at the cell five down and 3 to the right from this
>                 direction = sheet.cell(j+5, i+1).value
>                 scafPositions[position] = direction
>                 print scafPositions #only one run once, the delete this
> line
>                 break # only run once with this line, then delete.
>             i += 5 #Are you sure this is what you want?
>
>         val = float(helix) + (float(scafPos) * 0.001)
>         if (scafPositions[val] == "out"):
>             print "Warning: Base pointing outwards"
>

 I use xlrd and xlwt all the time, but if you want to learn python, it might
not be the best way to go about it.

I am nearly 100% certain that xlrd can not calculate cell contents for you.
What I do is copy and past the values only into the sheet,and then run
python.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110728/aabd67e5/attachment-0001.html>

From dave at csc.lsu.edu  Fri Jul 29 00:18:17 2011
From: dave at csc.lsu.edu (dave)
Date: Thu, 28 Jul 2011 17:18:17 -0500
Subject: [Tutor] Don't understand this class/constructor call syntax
In-Reply-To: <4E2D1686.8090109@btinternet.com>
References: <20110722223458.M83643@csc.lsu.edu>	<4E2A3B53.3000409@pearwood.info>	<20110723171954.M52452@csc.lsu.edu>	<4E2BC4A2.3030601@pearwood.info>	<20110724183239.M12544@csc.lsu.edu>	<4E2CB823.9050902@pearwood.info>
	<20110726011305.M72864@csc.lsu.edu>
	<4E2D1686.8090109@btinternet.com>
Message-ID: <20110728221347.M44772@csc.lsu.edu>

Yes that is roughly what I meant.  GNU Radio uses a lot of sub-classing--if
this is the correct term.  For example all blocks inherit hier_block2 which
has methods such as connect for connecting two blocks together.  I wondered if
the instance named self wasn't being passed as a replacement for the implicit
self parameter rather than in place of the pass_as_USRP=True parameter.

Steven D'Aprano also replied on this subject and if I understand him, then it
would require a special syntax that is not present in the GNU Radio code.

Dave





On Mon, 25 Jul 2011 08:08:54 +0100, Alan Gauld wrote
> dave wrote:
> > Is it even possible to replace the implicit self argument of the initializer
> > by passing something else?  If so, what would be the syntax.
> 
> Im not sure  this is what you mean but...
> 
> When you call a method on an object like:
> 
> class MyClass:
>     def aMethod(self,spam): pass
> 
> anObject= MyClass()
> anObject.aMethod(42)
> 
> You could replace the last line with:
> 
> MyClass.aMethod(anObject, 42)
> 
> This explicitly specifies the value of self in aMethod()
> 
> So you could in theory pass any object into the method,
> although in most cases it would result in an error.
> 
> Is that what you mean?
> 
> Alan G.
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From ramit.prasad at jpmchase.com  Fri Jul 29 01:05:49 2011
From: ramit.prasad at jpmchase.com (Prasad, Ramit)
Date: Thu, 28 Jul 2011 19:05:49 -0400
Subject: [Tutor] Sorting lists both ways at once and programmatically
 loading a variable.
Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA700BB74@EMARC112VS01.exchad.jpmchase.net>

I have 2 questions.

1. Is there a way to do a reverse and a normal sort at the same time?
I have a list of tuples (there are more than 2 elements in the tuples but I only want to sort by the first two). I want to sort in reverse for the first element (int) and in order for the second element (string).

Example: [ (1,3) (5, 2), (5, 1), (1, 1) ]. 
The output should be:[ (5,1), (5,2), (1,1), (1,3) ]
I can create a hack for this by sorting both values in order but it is a hack and not a "Good" solution (untested): 
>>> sorted( lst, key=lambda x: (9999999999-x[0],x[1]) )



2. How would you programmatically get a variable when there is no class involved? If I was in a class I could do something like 
>>> programmatically_determined_variable = getattr( self, var_basename + str(number) )
How would I do this from a module function or directly in the module? And is the solution "safe"?

Ramit


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



This communication is for informational purposes only. It is not
intended as an offer or solicitation for the purchase or sale of
any financial instrument or as an official confirmation of any
transaction. All market prices, data and other information are not
warranted as to completeness or accuracy and are subject to change
without notice. Any comments or statements made herein do not
necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
and affiliates.

This transmission may contain information that is privileged,
confidential, legally privileged, and/or exempt from disclosure
under applicable law. If you are not the intended recipient, you
are hereby notified that any disclosure, copying, distribution, or
use of the information contained herein (including any reliance
thereon) is STRICTLY PROHIBITED. Although this transmission and any
attachments are believed to be free of any virus or other defect
that might affect any computer system into which it is received and
opened, it is the responsibility of the recipient to ensure that it
is virus free and no responsibility is accepted by JPMorgan Chase &
Co., its subsidiaries and affiliates, as applicable, for any loss
or damage arising in any way from its use. If you received this
transmission in error, please immediately contact the sender and
destroy the material in its entirety, whether in electronic or hard
copy format. Thank you.

Please refer to http://www.jpmorgan.com/pages/disclosures for
disclosures relating to European legal entities.

From d at davea.name  Fri Jul 29 01:14:51 2011
From: d at davea.name (Dave Angel)
Date: Thu, 28 Jul 2011 19:14:51 -0400
Subject: [Tutor] Sorting lists both ways at once and programmatically
 loading a variable.
In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA700BB74@EMARC112VS01.exchad.jpmchase.net>
References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA700BB74@EMARC112VS01.exchad.jpmchase.net>
Message-ID: <4E31ED6B.1050706@davea.name>

On 07/28/2011 07:05 PM, Prasad, Ramit wrote:
> I have 2 questions.
>
> 1. Is there a way to do a reverse and a normal sort at the same time?
> I have a list of tuples (there are more than 2 elements in the tuples but I only want to sort by the first two). I want to sort in reverse for the first element (int) and in order for the second element (string).
>
> Example: [ (1,3) (5, 2), (5, 1), (1, 1) ].
> The output should be:[ (5,1), (5,2), (1,1), (1,3) ]
> I can create a hack for this by sorting both values in order but it is a hack and not a "Good" solution (untested):
>>>> sorted( lst, key=lambda x: (9999999999-x[0],x[1]) )
First point.  Nothing wrong with your solution, but you can leave out 
the 999999 part.  Just use -x[0]
Another option.  Do two sorts, first on the secondary key, then on the 
primary (reversed).  Since Python's sort is stable,
     it'll do the right thing.

>
> 2. How would you programmatically get a variable when there is no class involved? If I was in a class I could do something like
>>>> programmatically_determined_variable = getattr( self, var_basename + str(number) )
> How would I do this from a module function or directly in the module? And is the solution "safe"?
>
> Ramit
>
globals() is a dictionary of all the global variables, so you can do the 
same getaddr() technique.

DaveA

-- 

DaveA


From alan.gauld at btinternet.com  Fri Jul 29 01:44:50 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 29 Jul 2011 00:44:50 +0100
Subject: [Tutor] Getting Idle to work in Win7
In-Reply-To: <4E31AC9A.80304@sbcglobal.net>
References: <4E307E0C.2040801@sbcglobal.net>	<CANLXbfCFzfzDnqOmvovrQqN79Pjk0=cY-e4AsSYCm=+28GTnVg@mail.gmail.com>	<0604E20B5F6F2F4784C9C8C71C5DD4DD2EA6F1C8BC@EMARC112VS01.exchad.jpmchase.net>
	<4E31AC9A.80304@sbcglobal.net>
Message-ID: <4E31F472.4090001@btinternet.com>

Wayne Watson wrote:

> I tried from the command line to run pythonw.exe, and that gave me the typical 
>  >>> input choice. Python at least works at that level. IDLE comes up with idle.pyw.

Don't run pythonw to catch bugs, use python (no w).

>> Python script from the command line, as well as starting Idle from the command 
>> line so you can see what error message might be printed.

HTH,

Alan G.


From alan.gauld at btinternet.com  Fri Jul 29 01:44:50 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 29 Jul 2011 00:44:50 +0100
Subject: [Tutor] Getting Idle to work in Win7
In-Reply-To: <4E31AC9A.80304@sbcglobal.net>
References: <4E307E0C.2040801@sbcglobal.net>	<CANLXbfCFzfzDnqOmvovrQqN79Pjk0=cY-e4AsSYCm=+28GTnVg@mail.gmail.com>	<0604E20B5F6F2F4784C9C8C71C5DD4DD2EA6F1C8BC@EMARC112VS01.exchad.jpmchase.net>
	<4E31AC9A.80304@sbcglobal.net>
Message-ID: <4E31F472.4090001@btinternet.com>

Wayne Watson wrote:

> I tried from the command line to run pythonw.exe, and that gave me the typical 
>  >>> input choice. Python at least works at that level. IDLE comes up with idle.pyw.

Don't run pythonw to catch bugs, use python (no w).

>> Python script from the command line, as well as starting Idle from the command 
>> line so you can see what error message might be printed.

HTH,

Alan G.


From alan.gauld at btinternet.com  Fri Jul 29 01:53:32 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 29 Jul 2011 00:53:32 +0100
Subject: [Tutor] Sorting lists both ways at once and programmatically
 loading a variable.
In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA700BB74@EMARC112VS01.exchad.jpmchase.net>
References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA700BB74@EMARC112VS01.exchad.jpmchase.net>
Message-ID: <4E31F67C.8010005@btinternet.com>

Prasad, Ramit wrote:
> I have 2 questions.
> 
> 1. Is there a way to do a reverse and a normal sort at the same time?
> I have a list of tuples (there are more than 2 elements in the tuples but I only want to sort by the first two). I want to sort in reverse for the first element (int) and in order for the second element (string).
> 
> Example: [ (1,3) (5, 2), (5, 1), (1, 1) ]. 
> The output should be:[ (5,1), (5,2), (1,1), (1,3) ]
> I can create a hack for this by sorting both values in order but it is a hack and not a "Good" solution (untested): 
>>>> sorted( lst, key=lambda x: (9999999999-x[0],x[1]) )

Its late and I'm going to bed so this might be ruibbish, but couldn't 
you just negate the first element? So -5 is smaller than -1 etc...

> 2. How would you programmatically get a variable when there is no class involved? If I was in a class I could do something like 
>>>> programmatically_determined_variable = getattr( self, var_basename + str(number) )
> How would I do this from a module function or directly in the module? And is the solution "safe"?

Sorry, brain hurts trying to work out what you mean here... :-)

Good night,

Alan G.,


From alan.gauld at btinternet.com  Fri Jul 29 01:53:32 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 29 Jul 2011 00:53:32 +0100
Subject: [Tutor] Sorting lists both ways at once and programmatically
 loading a variable.
In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA700BB74@EMARC112VS01.exchad.jpmchase.net>
References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA700BB74@EMARC112VS01.exchad.jpmchase.net>
Message-ID: <4E31F67C.8010005@btinternet.com>

Prasad, Ramit wrote:
> I have 2 questions.
> 
> 1. Is there a way to do a reverse and a normal sort at the same time?
> I have a list of tuples (there are more than 2 elements in the tuples but I only want to sort by the first two). I want to sort in reverse for the first element (int) and in order for the second element (string).
> 
> Example: [ (1,3) (5, 2), (5, 1), (1, 1) ]. 
> The output should be:[ (5,1), (5,2), (1,1), (1,3) ]
> I can create a hack for this by sorting both values in order but it is a hack and not a "Good" solution (untested): 
>>>> sorted( lst, key=lambda x: (9999999999-x[0],x[1]) )

Its late and I'm going to bed so this might be ruibbish, but couldn't 
you just negate the first element? So -5 is smaller than -1 etc...

> 2. How would you programmatically get a variable when there is no class involved? If I was in a class I could do something like 
>>>> programmatically_determined_variable = getattr( self, var_basename + str(number) )
> How would I do this from a module function or directly in the module? And is the solution "safe"?

Sorry, brain hurts trying to work out what you mean here... :-)

Good night,

Alan G.,


From g.nius.ck at gmail.com  Fri Jul 29 02:32:50 2011
From: g.nius.ck at gmail.com (Christopher King)
Date: Thu, 28 Jul 2011 20:32:50 -0400
Subject: [Tutor] Mainloop conflict
Message-ID: <CAKBg9Z0xjV8vPPMoxLtrHoEFTtxdme0=pj-XPyJZSpCTQ3mPuQ@mail.gmail.com>

Dear Tutor Dudes,
    I have a socket Gui program. The only problem is that socket.recv waits
for a response, which totally screws Tkinter I think. I tried making the
timeout extremely small (it was alright if I didn't receive anything, I
was excepting that a lot) but I think that screwed socket. Anyone have words
of wisdom.

Sincerely,
    Me
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110728/93e8cabd/attachment.html>

From d at davea.name  Fri Jul 29 03:01:47 2011
From: d at davea.name (Dave Angel)
Date: Thu, 28 Jul 2011 21:01:47 -0400
Subject: [Tutor] Mainloop conflict
In-Reply-To: <CAKBg9Z0xjV8vPPMoxLtrHoEFTtxdme0=pj-XPyJZSpCTQ3mPuQ@mail.gmail.com>
References: <CAKBg9Z0xjV8vPPMoxLtrHoEFTtxdme0=pj-XPyJZSpCTQ3mPuQ@mail.gmail.com>
Message-ID: <4E32067B.5080308@davea.name>

On 07/28/2011 08:32 PM, Christopher King wrote:
> Dear Tutor Dudes,
>      I have a socket Gui program. The only problem is that socket.recv waits
> for a response, which totally screws Tkinter I think. I tried making the
> timeout extremely small (it was alright if I didn't receive anything, I
> was excepting that a lot) but I think that screwed socket. Anyone have words
> of wisdom.
>
> Sincerely,
>      Me
>
Sure:

Do the socket I/O on a separate thread.

-- 

DaveA


From redacted@example.com  Fri Jul 29 03:58:47 2011
From: redacted@example.com (Alexander Quest)
Date: Thu, 28 Jul 2011 18:58:47 -0700
Subject: [Tutor] Running files from command prompt
Message-ID: <CAHgjEe3ht7=MKam_cWVPDpVg6hnAuGRjW-MEc3eHT6+pB9Kb_w@mail.gmail.com>

I downloaded the google's python exercise files from their website (
http://code.google.com/edu/languages/google-python-class/set-up.html),
unzipped them, and placed them in C.
I then added the following to the PATH variable under system settings so
that I could type "python" in command prompt and have Windows start the
interpreter: C:\Python31;C:\Python31\Tools\Scripts

When I type in "python" in the command prompt, the interpreter opens, but
when I try to open one of the programs from the Google exercise files
(hello.py), I get the following error:
Traceback <most recent call last>:
   File "<stdin>", line 1, in <module>
NameError: name 'hello' is not defined

Or, if I just type in "python hello.py" first in the command prompt (as
opposed to typing in python, hitting enter, and THEN typing in hello.py, as
above), I get the following error:


python: can't open file 'hello.py': [Errno 2] No such file or directory.

So I guess my question is how do I run .py files from the command prompt now
that I seem to have gotten Windows to recognize and open the interpreter
when I type in "python"? Thanks for any help.

-Alex

P.S. Just as an aside, when I open up the command prompt, the initial
directory is C:\Users\Alexander, but my google exercises are in
C:\google-python-exercises and python itself is in C:\Python31. I don't know
if this makes a difference or not.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110728/edc6d4d7/attachment.html>

From d at davea.name  Fri Jul 29 04:11:39 2011
From: d at davea.name (Dave Angel)
Date: Thu, 28 Jul 2011 22:11:39 -0400
Subject: [Tutor] Running files from command prompt
In-Reply-To: <CAHgjEe3ht7=MKam_cWVPDpVg6hnAuGRjW-MEc3eHT6+pB9Kb_w@mail.gmail.com>
References: <CAHgjEe3ht7=MKam_cWVPDpVg6hnAuGRjW-MEc3eHT6+pB9Kb_w@mail.gmail.com>
Message-ID: <4E3216DB.2030700@davea.name>

On 07/28/2011 09:58 PM, Alexander Quest wrote:
> I downloaded the google's python exercise files from their website (
> http://code.google.com/edu/languages/google-python-class/set-up.html),
> unzipped them, and placed them in C.
> I then added the following to the PATH variable under system settings so
> that I could type "python" in command prompt and have Windows start the
> interpreter: C:\Python31;C:\Python31\Tools\Scripts
>
> When I type in "python" in the command prompt, the interpreter opens, but
> when I try to open one of the programs from the Google exercise files
> (hello.py), I get the following error:
> Traceback<most recent call last>:
>     File "<stdin>", line 1, in<module>
> NameError: name 'hello' is not defined
>

When you're running the python interpreter, you can't just type the name 
of your script.  You need to import it
      import hello

However, first it needs to be in the python's module search path.  
Easiest way is to make
  it your current directory.

So, from a command prompt:

cd C:\google-python-exercises

python
XXXX starting Python version ....

 >>>>import hello


> Or, if I just type in "python hello.py" first in the command prompt (as
> opposed to typing in python, hitting enter, and THEN typing in hello.py, as
> above), I get the following error:
>
>
> python: can't open file 'hello.py': [Errno 2] No such file or directory.
>
> So I guess my question is how do I run .py files from the command prompt now
> that I seem to have gotten Windows to recognize and open the interpreter
> when I type in "python"? Thanks for any help.
>
Similarly, before running python, change to the directory you want the 
script to run in.
Normally, you'd do:

cd c:\google-python-exercises
python hello.py


> -Alex
>
> P.S. Just as an aside, when I open up the command prompt, the initial
> directory is C:\Users\Alexander, but my google exercises are in
> C:\google-python-exercises and python itself is in C:\Python31. I don't know
> if this makes a difference or not.
>


-- 

DaveA


From redacted@example.com  Fri Jul 29 04:58:05 2011
From: redacted@example.com (Alexander Quest)
Date: Thu, 28 Jul 2011 19:58:05 -0700
Subject: [Tutor] Running files from command prompt
In-Reply-To: <4E3216DB.2030700@davea.name>
References: <CAHgjEe3ht7=MKam_cWVPDpVg6hnAuGRjW-MEc3eHT6+pB9Kb_w@mail.gmail.com>
	<4E3216DB.2030700@davea.name>
Message-ID: <CAHgjEe1EcSiUPQkNR3_bOHJJ8ujjSf+kqg4wGxZCfOXC6rd9-Q@mail.gmail.com>

Awesome- thanks for that Dave! The programs all work now, except that the
google exercise programs are all from Python 2.X and I'm running 3.1, so
some of them are giving me errors. Is there a way around this or do I have
to download a 2.X version so I can run these without a problem? Thanks
again.

-Alex

On Thu, Jul 28, 2011 at 7:11 PM, Dave Angel <d at davea.name> wrote:

> On 07/28/2011 09:58 PM, Alexander Quest wrote:
>
>> I downloaded the google's python exercise files from their website (
>> http://code.google.com/edu/**languages/google-python-class/**set-up.html<http://code.google.com/edu/languages/google-python-class/set-up.html>
>> ),
>> unzipped them, and placed them in C.
>> I then added the following to the PATH variable under system settings so
>> that I could type "python" in command prompt and have Windows start the
>> interpreter: C:\Python31;C:\Python31\Tools\**Scripts
>>
>> When I type in "python" in the command prompt, the interpreter opens, but
>> when I try to open one of the programs from the Google exercise files
>> (hello.py), I get the following error:
>> Traceback<most recent call last>:
>>    File "<stdin>", line 1, in<module>
>> NameError: name 'hello' is not defined
>>
>>
> When you're running the python interpreter, you can't just type the name of
> your script.  You need to import it
>     import hello
>
> However, first it needs to be in the python's module search path.  Easiest
> way is to make
>  it your current directory.
>
> So, from a command prompt:
>
> cd C:\google-python-exercises
>
> python
> XXXX starting Python version ....
>
> >>>>import hello
>
>
>
>  Or, if I just type in "python hello.py" first in the command prompt (as
>> opposed to typing in python, hitting enter, and THEN typing in hello.py,
>> as
>> above), I get the following error:
>>
>>
>> python: can't open file 'hello.py': [Errno 2] No such file or directory.
>>
>> So I guess my question is how do I run .py files from the command prompt
>> now
>> that I seem to have gotten Windows to recognize and open the interpreter
>> when I type in "python"? Thanks for any help.
>>
>>  Similarly, before running python, change to the directory you want the
> script to run in.
> Normally, you'd do:
>
> cd c:\google-python-exercises
> python hello.py
>
>
>
>  -Alex
>>
>> P.S. Just as an aside, when I open up the command prompt, the initial
>> directory is C:\Users\Alexander, but my google exercises are in
>> C:\google-python-exercises and python itself is in C:\Python31. I don't
>> know
>> if this makes a difference or not.
>>
>>
>
> --
>
> DaveA
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110728/26270424/attachment-0001.html>

From redacted@example.com  Fri Jul 29 05:28:13 2011
From: redacted@example.com (Alexander Quest)
Date: Thu, 28 Jul 2011 20:28:13 -0700
Subject: [Tutor] Running files from command prompt
In-Reply-To: <CAHgjEe1EcSiUPQkNR3_bOHJJ8ujjSf+kqg4wGxZCfOXC6rd9-Q@mail.gmail.com>
References: <CAHgjEe3ht7=MKam_cWVPDpVg6hnAuGRjW-MEc3eHT6+pB9Kb_w@mail.gmail.com>
	<4E3216DB.2030700@davea.name>
	<CAHgjEe1EcSiUPQkNR3_bOHJJ8ujjSf+kqg4wGxZCfOXC6rd9-Q@mail.gmail.com>
Message-ID: <CAHgjEe2BfbUPu8zR5n2EVzNvraqscr97PdaoUpomJp+WLXpMrA@mail.gmail.com>

To clarify, the particular file that was giving me trouble was the basic
"hello world" file. The original code on line 29 read as such: print
'Hello', name
When I ran "C:\google-python-exercises> python hello.py, it gave me an error
on that line (line 29), but when I changed that line to print ('Hello',
name), that is, including the parentheses, it printed out "hello world" as
it should. I'm assuming that this means that one of the differences between
Python 2.X and Python 3.X is that the print function necessitates
parentheses in the latter versions but not in the former. I am a bit
confused as to why this is, assuming I am correct in my assumption above,
because I was under the impression that code written for earlier python
versions will work for later python versions, as is the case here. Anyways,
I just wanted to add this info to clarify my last question regarding whether
or not I should install Python 2.X and uninstall Python 3.1 that I have now,
since I'm guessing that doing the google exercises will continue to give me
these errors with other programs (but this is, of course, still assuming
that the error cited above truly is caused by version incompatibility).

-Alex


On Thu, Jul 28, 2011 at 7:58 PM, Alexander Quest <redacted@example.com>wrote:

> Awesome- thanks for that Dave! The programs all work now, except that the
> google exercise programs are all from Python 2.X and I'm running 3.1, so
> some of them are giving me errors. Is there a way around this or do I have
> to download a 2.X version so I can run these without a problem? Thanks
> again.
>
> -Alex
>
>
> On Thu, Jul 28, 2011 at 7:11 PM, Dave Angel <d at davea.name> wrote:
>
>> On 07/28/2011 09:58 PM, Alexander Quest wrote:
>>
>>> I downloaded the google's python exercise files from their website (
>>> http://code.google.com/edu/**languages/google-python-class/**set-up.html<http://code.google.com/edu/languages/google-python-class/set-up.html>
>>> ),
>>> unzipped them, and placed them in C.
>>> I then added the following to the PATH variable under system settings so
>>> that I could type "python" in command prompt and have Windows start the
>>> interpreter: C:\Python31;C:\Python31\Tools\**Scripts
>>>
>>> When I type in "python" in the command prompt, the interpreter opens, but
>>> when I try to open one of the programs from the Google exercise files
>>> (hello.py), I get the following error:
>>> Traceback<most recent call last>:
>>>    File "<stdin>", line 1, in<module>
>>> NameError: name 'hello' is not defined
>>>
>>>
>> When you're running the python interpreter, you can't just type the name
>> of your script.  You need to import it
>>     import hello
>>
>> However, first it needs to be in the python's module search path.  Easiest
>> way is to make
>>  it your current directory.
>>
>> So, from a command prompt:
>>
>> cd C:\google-python-exercises
>>
>> python
>> XXXX starting Python version ....
>>
>> >>>>import hello
>>
>>
>>
>>  Or, if I just type in "python hello.py" first in the command prompt (as
>>> opposed to typing in python, hitting enter, and THEN typing in hello.py,
>>> as
>>> above), I get the following error:
>>>
>>>
>>> python: can't open file 'hello.py': [Errno 2] No such file or directory.
>>>
>>> So I guess my question is how do I run .py files from the command prompt
>>> now
>>> that I seem to have gotten Windows to recognize and open the interpreter
>>> when I type in "python"? Thanks for any help.
>>>
>>>  Similarly, before running python, change to the directory you want the
>> script to run in.
>> Normally, you'd do:
>>
>> cd c:\google-python-exercises
>> python hello.py
>>
>>
>>
>>  -Alex
>>>
>>> P.S. Just as an aside, when I open up the command prompt, the initial
>>> directory is C:\Users\Alexander, but my google exercises are in
>>> C:\google-python-exercises and python itself is in C:\Python31. I don't
>>> know
>>> if this makes a difference or not.
>>>
>>>
>>
>> --
>>
>> DaveA
>>
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110728/66febe95/attachment.html>

From wolfrage8765 at gmail.com  Fri Jul 29 06:14:50 2011
From: wolfrage8765 at gmail.com (Jordan)
Date: Thu, 28 Jul 2011 21:14:50 -0700
Subject: [Tutor] About the Mailing List
In-Reply-To: <mailman.7821.1311908287.1163.tutor@python.org>
References: <mailman.7821.1311908287.1163.tutor@python.org>
Message-ID: <4E3233BA.8060602@gmail.com>

How do I see what in the mailing list has already been responded too,
before it sends me the digest? For instance I wanted to respond to one
of the questions, but seeing that the time was almost two hours ago. I
am sure someone has already responded. Where could I check to see if
this is true? I assume the mailing list are posted some wheres on-line.
But I can only find the sign up page. Thanks in advance for the link.
--
Jordan

From stefan_ml at behnel.de  Fri Jul 29 06:30:02 2011
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 29 Jul 2011 06:30:02 +0200
Subject: [Tutor] Mainloop conflict
In-Reply-To: <CAKBg9Z0xjV8vPPMoxLtrHoEFTtxdme0=pj-XPyJZSpCTQ3mPuQ@mail.gmail.com>
References: <CAKBg9Z0xjV8vPPMoxLtrHoEFTtxdme0=pj-XPyJZSpCTQ3mPuQ@mail.gmail.com>
Message-ID: <j0td0a$ua3$1@dough.gmane.org>

Christopher King, 29.07.2011 02:32:
>      I have a socket Gui program. The only problem is that socket.recv waits
> for a response, which totally screws Tkinter I think. I tried making the
> timeout extremely small (it was alright if I didn't receive anything, I
> was excepting that a lot) but I think that screwed socket. Anyone have words
> of wisdom.

Most of the GUI main loops (including tk, I believe) have a way to hook in 
additional file descriptors and sockets that can be listened on, so that 
you get a normal event when data becomes available in them.

Stefan


From steve at pearwood.info  Fri Jul 29 07:27:26 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 29 Jul 2011 15:27:26 +1000
Subject: [Tutor] Running files from command prompt
In-Reply-To: <CAHgjEe2BfbUPu8zR5n2EVzNvraqscr97PdaoUpomJp+WLXpMrA@mail.gmail.com>
References: <CAHgjEe3ht7=MKam_cWVPDpVg6hnAuGRjW-MEc3eHT6+pB9Kb_w@mail.gmail.com>	<4E3216DB.2030700@davea.name>	<CAHgjEe1EcSiUPQkNR3_bOHJJ8ujjSf+kqg4wGxZCfOXC6rd9-Q@mail.gmail.com>
	<CAHgjEe2BfbUPu8zR5n2EVzNvraqscr97PdaoUpomJp+WLXpMrA@mail.gmail.com>
Message-ID: <4E3244BE.6040901@pearwood.info>

Alexander Quest wrote:
> To clarify, the particular file that was giving me trouble was the basic
> "hello world" file. The original code on line 29 read as such: print
> 'Hello', name
> When I ran "C:\google-python-exercises> python hello.py, it gave me an error
> on that line (line 29), but when I changed that line to print ('Hello',
> name), that is, including the parentheses, it printed out "hello world" as
> it should. I'm assuming that this means that one of the differences between
> Python 2.X and Python 3.X is that the print function necessitates
> parentheses in the latter versions but not in the former. 


Yes, that is correct.

To be a programmer (whether professional or amateur), you need to learn 
to *pay attention to the error given*. "It gave me an error" is 
meaningless. What does the error message say?

In this case, I expect it is a SyntaxError. But you need to learn to 
read the error message and understand what it is trying to tell you. 
Some errors are cryptic and don't help, but generally speaking Python is 
pretty good about giving useful error messages:


 >>> a = [1, 2, 3]
 >>> len a
   File "<stdin>", line 1
     len a
         ^
SyntaxError: invalid syntax


Admittedly you do need to learn that Python functions require 
parentheses, but apart from that, the error tells you what is wrong: you 
can't follow a function len with another name a without something 
between them. This is illegal syntax.



> I am a bit
> confused as to why this is, assuming I am correct in my assumption above,
> because I was under the impression that code written for earlier python
> versions will work for later python versions, as is the case here. 

Not quite. It is (mostly) true for Python 1.x and 2.x, but Python 3 has 
deliberately included some backwards incompatible changes. The biggest 
two are that strings are now Unicode rather than byte strings, and that 
print is now a function instead of a statement. So, yes, in Python 3 you 
have to call it with parentheses.

The differences are still quite minor -- think of Python 2.x and Python 
3.x being like the differences between American English and British 
English. Provided you pay attention to the error messages, and remember 
to add round brackets after print, tutorials for 2.x should still 
*mostly* work.


> I just wanted to add this info to clarify my last question regarding whether
> or not I should install Python 2.X and uninstall Python 3.1 that I have now,

Personally, I would consider it wiser to find a Python 3 tutorial. 
Python 3 is the future, and you will need to learn it eventually.




-- 
Steven

From steve at pearwood.info  Fri Jul 29 07:32:36 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 29 Jul 2011 15:32:36 +1000
Subject: [Tutor] About the Mailing List
In-Reply-To: <4E3233BA.8060602@gmail.com>
References: <mailman.7821.1311908287.1163.tutor@python.org>
	<4E3233BA.8060602@gmail.com>
Message-ID: <4E3245F4.40406@pearwood.info>

Jordan wrote:
> How do I see what in the mailing list has already been responded too,
> before it sends me the digest? For instance I wanted to respond to one
> of the questions, but seeing that the time was almost two hours ago. I
> am sure someone has already responded. Where could I check to see if
> this is true? I assume the mailing list are posted some wheres on-line.
> But I can only find the sign up page. Thanks in advance for the link.

Digest mode is a pain in the backside for people wanting to reply, and 
an even bigger pain for those who read the replies to digests. Please 
consider doing yourself, and everyone else, a favour by switching to 
individual emails.

You can see the archives by going to this page here:

http://mail.python.org/mailman/listinfo/tutor

and following the links to the archives. There are *three* given: two 
external archives (Activestate and Gmane) and one held by python.org itself.




-- 
Steven


From kb1pkl at aim.com  Fri Jul 29 08:39:41 2011
From: kb1pkl at aim.com (Corey Richardson)
Date: Fri, 29 Jul 2011 02:39:41 -0400
Subject: [Tutor] About the Mailing List
In-Reply-To: <4E3245F4.40406@pearwood.info>
References: <mailman.7821.1311908287.1163.tutor@python.org>
	<4E3233BA.8060602@gmail.com> <4E3245F4.40406@pearwood.info>
Message-ID: <1311921467-sup-7502@fea4e5c0ad4e1c0215b0caa4e3>

Excerpts from Steven D'Aprano's message of Fri Jul 29 01:32:36 -0400 2011:
> Jordan wrote:
> > How do I see what in the mailing list has already been responded too,
> > before it sends me the digest? For instance I wanted to respond to one
> > of the questions, but seeing that the time was almost two hours ago. I
> > am sure someone has already responded. Where could I check to see if
> > this is true? I assume the mailing list are posted some wheres on-line.
> > But I can only find the sign up page. Thanks in advance for the link.
> 
> Digest mode is a pain in the backside for people wanting to reply, and 
> an even bigger pain for those who read the replies to digests. Please 
> consider doing yourself, and everyone else, a favour by switching to 
> individual emails.
> 

I'll add on to that and say find the threading feature of your user
agent -- or switch to one that has said feature. I know recent thunderbird's
do it, if that's the sort of thing you're into. Thread view makes
things bucketloads easier.
-- 
Corey Richardson
  "Those who deny freedom to others, deserve it not for themselves"
     -- Abraham Lincoln
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 490 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20110729/471fc2bf/attachment.pgp>

From alan.gauld at btinternet.com  Fri Jul 29 10:13:27 2011
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 29 Jul 2011 09:13:27 +0100
Subject: [Tutor] About the Mailing List
In-Reply-To: <4E3245F4.40406@pearwood.info>
References: <mailman.7821.1311908287.1163.tutor@python.org>	<4E3233BA.8060602@gmail.com>
	<4E3245F4.40406@pearwood.info>
Message-ID: <4E326BA7.6060308@btinternet.com>

Steven D'Aprano wrote:

> You can see the archives by going to this page here:
> 
> http://mail.python.org/mailman/listinfo/tutor
> 
> and following the links to the archives. There are *three* given: two 
> external archives (Activestate and Gmane) and one held by python.org 
> itself.

And if you use Gmane you can read the list as a newsfeed which gives you 
the advantages of a digest and the ability to send single targetted 
replies. Both Outlook Express and Thunderbird can read newsfeeds as well 
as mail. Other mail tools may well do likewise.

HTH,

Alan G
A gmane news user :-)

From strangegeorge2 at gmail.com  Fri Jul 29 11:52:49 2011
From: strangegeorge2 at gmail.com (George Anonymous)
Date: Fri, 29 Jul 2011 12:52:49 +0300
Subject: [Tutor] Urllib Problem
Message-ID: <CA+gVJUwu=S584=5QXorqTTuVgg_WREAp5r_ZewwPm6onYNApGw@mail.gmail.com>

I am trying to make a simple programm with Python 3,that tries to open
differnet pages from a wordlist and prints which are alive.Here is the code:
from urllib import request
fob=open('c:/passwords/pass.txt','r')
x = fob.readlines()
for i in x:
    urllib.request.openurl('www.google.gr/' + i)

But it doesent work.Whats the problem?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110729/26619d3f/attachment.html>

From karim.liateni at free.fr  Fri Jul 29 11:58:52 2011
From: karim.liateni at free.fr (Karim)
Date: Fri, 29 Jul 2011 11:58:52 +0200
Subject: [Tutor] Urllib Problem
In-Reply-To: <CA+gVJUwu=S584=5QXorqTTuVgg_WREAp5r_ZewwPm6onYNApGw@mail.gmail.com>
References: <CA+gVJUwu=S584=5QXorqTTuVgg_WREAp5r_ZewwPm6onYNApGw@mail.gmail.com>
Message-ID: <4E32845C.3020807@free.fr>

On 07/29/2011 11:52 AM, George Anonymous wrote:
> I am trying to make a simple programm with Python 3,that tries to open 
> differnet pages from a wordlist and prints which are alive.Here is the 
> code:
> from urllib import request
> fob=open('c:/passwords/pass.txt','r')
> x = fob.readlines()
> for i in x:
>     urllib.request.openurl('www.google.gr/ <http://www.google.gr/>' + i)
>
> But it doesent work.Whats the problem?


Please give the exception error you get?!
And you should have in the html header
the html code error number which gives
you the fail answer from the server.

Cheers
Karim

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

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110729/f84d110a/attachment.html>

From hanlie.pretorius at gmail.com  Fri Jul 29 12:12:00 2011
From: hanlie.pretorius at gmail.com (Hanlie Pretorius)
Date: Fri, 29 Jul 2011 12:12:00 +0200
Subject: [Tutor] Reading .gz files
Message-ID: <CAFpCUPrbFt62Gi8q_E+AmpKMNs7dw7whWw=tTjscP5fobq+vkw@mail.gmail.com>

Hi,

I'm working on Windows XP with Python 2.6.

I need to read and process hundreds of binary files that are in the
.gz archive format.

I found a site (http://www.doughellmann.com/PyMOTW/gzip/) and tried
their code with two files: one of the hundreds of files that I need to
process (f1 below) and one that I created with 7-Zip from a text file
that contains the text 'Text to test gzip module.' (f2 below). The
code and the output follow:

[code]
import gzip

f1 = 'GSMaP_MVK+.20050101.00.0.1deg.hourly.v484.gz'
f2 = ''text.txt.gz'
if1 = gzip.open(f1, 'rb')
if2 = gzip.open(f2,'rb')
try:
   print if1.read()
   print 'done with f1'
   print if2.read()
   print 'done with f2'
finally:
   if1.close()
   if2.close()
[/code]

[output]
done with f1
Text to test gzip module.
done with f2
[/output]

This seems to indicate that something is wrong with f1 (the GSMaP file - a
binary file), but I can unzip the file manually and read it with a
python script. I have hundreds of GSMAP files that have unique
archived file names, but they all unzip to the same binary file, so I
have to process the archived files in the python script.

I would be grateful if someone could help me achieve this.

Regards
Hanlie

From rhettnaxel at gmail.com  Fri Jul 29 14:30:54 2011
From: rhettnaxel at gmail.com (Alexander)
Date: Fri, 29 Jul 2011 08:30:54 -0400
Subject: [Tutor] Urllib Problem
In-Reply-To: <4E32845C.3020807@free.fr>
References: <CA+gVJUwu=S584=5QXorqTTuVgg_WREAp5r_ZewwPm6onYNApGw@mail.gmail.com>
	<4E32845C.3020807@free.fr>
Message-ID: <CANS6qmApQ1F9NYhk_Nwhzmc64QY5ge-HbEGzES58szVAg6R93A@mail.gmail.com>

On Fri, Jul 29, 2011 at 5:58 AM, Karim <karim.liateni at free.fr> wrote:

> **
> On 07/29/2011 11:52 AM, George Anonymous wrote:
>
> I am trying to make a simple programm with Python 3,that tries to open
> differnet pages from a wordlist and prints which are alive.Here is the code:
> from urllib import request
> fob=open('c:/passwords/pass.txt','r')
> x = fob.readlines()
> for i in x:
>     urllib.request.openurl('www.google.gr/' + i)
>
> But it doesent work.Whats the problem?
>
>
> Please give the exception error you get?!
> And you should have in the html header
> the html code error number which gives
> you the fail answer from the server.
>
> Cheers
> Karim
>
> As Karim noted you'll want to mention any exceptions you are getting. I'm
not sure what it is you are trying to do with your code. If you'd like to
try to open each line and try something if it works else an exception the
code may read something similar to:

fob = open('C:/passwords/pass.txt','r')
fob_rlines = fob.readlines()
for line in fob_rlines:
try:
#whatever it is you would like to do with each line
except Exception: #where code didn't work and an exception occured
#whatever you would like to do when a particular *Exception* occurs
Hope that helps,
Alexander

>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:http://mail.python.org/mailman/listinfo/tutor
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110729/87afe40f/attachment.html>

From steve at pearwood.info  Fri Jul 29 15:16:59 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 29 Jul 2011 23:16:59 +1000
Subject: [Tutor] Urllib Problem
In-Reply-To: <CA+gVJUwu=S584=5QXorqTTuVgg_WREAp5r_ZewwPm6onYNApGw@mail.gmail.com>
References: <CA+gVJUwu=S584=5QXorqTTuVgg_WREAp5r_ZewwPm6onYNApGw@mail.gmail.com>
Message-ID: <4E32B2CB.9030206@pearwood.info>

George Anonymous wrote:
> I am trying to make a simple programm with Python 3,that tries to open
> differnet pages from a wordlist and prints which are alive.Here is the code:
> from urllib import request
> fob=open('c:/passwords/pass.txt','r')
> x = fob.readlines()
> for i in x:
>     urllib.request.openurl('www.google.gr/' + i)
> 
> But it doesent work.Whats the problem?


A guessing game! I LOVE guessing games!!! :)

Let's seen let me guess what you mean by "doesn't work":

- the computer locks up and sits there until you hit the restart switch
- the computer gives a Blue Screen Of Death
- Python raises an exception
- Python downloads the Yahoo website instead of Google
- something else


My guess is... you're getting a NameError exception, like this one:


 >>> from urllib import request
 >>> x = urllib.request.openurl('www.google.com')
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'urllib' is not defined


Am I close?


You need to use request.urlopen, not urllib.request.openurl.

That's your *first* problem. There are more. Come back if you need help 
with the others, and next time, don't make us play guessing games. Show 
us the code you use -- copy and paste it, don't retype it from memory -- 
what you expect should happen, and what actually happens instead.




-- 
Steven


From steve at pearwood.info  Fri Jul 29 15:36:28 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 29 Jul 2011 23:36:28 +1000
Subject: [Tutor] Reading .gz files
In-Reply-To: <CAFpCUPrbFt62Gi8q_E+AmpKMNs7dw7whWw=tTjscP5fobq+vkw@mail.gmail.com>
References: <CAFpCUPrbFt62Gi8q_E+AmpKMNs7dw7whWw=tTjscP5fobq+vkw@mail.gmail.com>
Message-ID: <4E32B75C.4020009@pearwood.info>

Hanlie Pretorius wrote:

> [code]
> import gzip
> 
> f1 = 'GSMaP_MVK+.20050101.00.0.1deg.hourly.v484.gz'
> f2 = ''text.txt.gz'
> if1 = gzip.open(f1, 'rb')
> if2 = gzip.open(f2,'rb')
> try:
>    print if1.read()
>    print 'done with f1'
>    print if2.read()
>    print 'done with f2'
> finally:
>    if1.close()
>    if2.close()
> [/code]
> 
> [output]
> done with f1
> Text to test gzip module.
> done with f2
> [/output]

> This seems to indicate that something is wrong with f1 (the GSMaP file - a

Are you sure it is an actual gzip file? You refer to gzip, 7-zip, and 
unzip in your post -- these are all different compression formats. Just 
because the file is *named* .gz doesn't necessarily mean it is a gzip file.


Try this:

if1 = gzip.open(f1, 'rb')
print repr(if1.read())
print if1.size, if1.crc, if1.name

and see what they say.





-- 
Steven


From steve at pearwood.info  Fri Jul 29 15:41:51 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 29 Jul 2011 23:41:51 +1000
Subject: [Tutor] Reading .gz files
In-Reply-To: <CAFpCUPrbFt62Gi8q_E+AmpKMNs7dw7whWw=tTjscP5fobq+vkw@mail.gmail.com>
References: <CAFpCUPrbFt62Gi8q_E+AmpKMNs7dw7whWw=tTjscP5fobq+vkw@mail.gmail.com>
Message-ID: <4E32B89F.8040000@pearwood.info>

Oh, I forgot to say something else...

Hanlie Pretorius wrote:

> f1 = 'GSMaP_MVK+.20050101.00.0.1deg.hourly.v484.gz'
> f2 = ''text.txt.gz'
> if1 = gzip.open(f1, 'rb')
> if2 = gzip.open(f2,'rb')
> try:
>    print if1.read()
>    print 'done with f1'


Once you've read the file once, the file pointer is at the end of the 
file, and reading it again returns the empty string. Example:


 >>> y = gzip.open('spam.gz', 'rb')
 >>> y.read()  # read to the end
'spam spam spam'
 >>> y.read()  # anything left?
''
 >>> y.seek(0)  # go back to the beginning
 >>> y.read()
'spam spam spam'



-- 
Steven


From g.nius.ck at gmail.com  Fri Jul 29 17:08:46 2011
From: g.nius.ck at gmail.com (Christopher King)
Date: Fri, 29 Jul 2011 11:08:46 -0400
Subject: [Tutor] Mainloop conflict
In-Reply-To: <4E32067B.5080308@davea.name>
References: <CAKBg9Z0xjV8vPPMoxLtrHoEFTtxdme0=pj-XPyJZSpCTQ3mPuQ@mail.gmail.com>
	<4E32067B.5080308@davea.name>
Message-ID: <CAKBg9Z3JSy20uVuAMirYvqNLSix5pCEtW53oyX4CJ98SM0y=jw@mail.gmail.com>

I was afraid of that.

On Thursday, July 28, 2011, Dave Angel <d at davea.name> wrote:
> On 07/28/2011 08:32 PM, Christopher King wrote:
>>
>> Dear Tutor Dudes,
>>     I have a socket Gui program. The only problem is that socket.recv
waits
>> for a response, which totally screws Tkinter I think. I tried making the
>> timeout extremely small (it was alright if I didn't receive anything, I
>> was excepting that a lot) but I think that screwed socket. Anyone have
words
>> of wisdom.
>>
>> Sincerely,
>>     Me
>>
> Sure:
>
> Do the socket I/O on a separate thread.
>
> --
>
> DaveA
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110729/a667b55a/attachment-0001.html>

From d at davea.name  Fri Jul 29 17:29:20 2011
From: d at davea.name (Dave Angel)
Date: Fri, 29 Jul 2011 11:29:20 -0400
Subject: [Tutor] Mainloop conflict
In-Reply-To: <CAKBg9Z3JSy20uVuAMirYvqNLSix5pCEtW53oyX4CJ98SM0y=jw@mail.gmail.com>
References: <CAKBg9Z0xjV8vPPMoxLtrHoEFTtxdme0=pj-XPyJZSpCTQ3mPuQ@mail.gmail.com>	<4E32067B.5080308@davea.name>
	<CAKBg9Z3JSy20uVuAMirYvqNLSix5pCEtW53oyX4CJ98SM0y=jw@mail.gmail.com>
Message-ID: <4E32D1D0.7090703@davea.name>

On 07/29/2011 11:08 AM, Christopher King wrote:
> I was afraid of that.
>
Please don't top-post.  It's becoming more prevalent on this list, but 
it makes things very confusing.  I need to put my response just after 
yours, but then the other relevant pieces are out of order.
> On Thursday, July 28, 2011, Dave Angel<d at davea.name>  wrote:
>> On 07/28/2011 08:32 PM, Christopher King wrote:
>>> Dear Tutor Dudes,
>>>      I have a socket Gui program. The only problem is that socket.recv
> waits
>>> for a response, which totally screws Tkinter I think. I tried making the
>>> timeout extremely small (it was alright if I didn't receive anything, I
>>> was excepting that a lot) but I think that screwed socket. Anyone have
> words
>>> of wisdom.
>>>
>>> Sincerely,
>>>      Me
>>>
>> Sure:
>>
>> Do the socket I/O on a separate thread.
>>
>> --
>>
>> DaveA
>>
>>
>
Threads aren't that tough in Python.

Threads aren't always helpful in CPython, because of the GIL. But this 
is one case where they are.  And somebody has pointed out a library 
which presumably hides the thread details from you.



-- 

DaveA


From redacted@example.com  Fri Jul 29 19:12:59 2011
From: redacted@example.com (Alexander Quest)
Date: Fri, 29 Jul 2011 10:12:59 -0700
Subject: [Tutor] Running files from command prompt
In-Reply-To: <4E3244BE.6040901@pearwood.info>
References: <CAHgjEe3ht7=MKam_cWVPDpVg6hnAuGRjW-MEc3eHT6+pB9Kb_w@mail.gmail.com>
	<4E3216DB.2030700@davea.name>
	<CAHgjEe1EcSiUPQkNR3_bOHJJ8ujjSf+kqg4wGxZCfOXC6rd9-Q@mail.gmail.com>
	<CAHgjEe2BfbUPu8zR5n2EVzNvraqscr97PdaoUpomJp+WLXpMrA@mail.gmail.com>
	<4E3244BE.6040901@pearwood.info>
Message-ID: <CAHgjEe0cUq2cr2Yz1C235ygcnkVsw8vBD_A_FS84X5KKQUt1Mw@mail.gmail.com>

Alexander- thanks for the tip as to sticking with Python 3.
Steven, I greatly appreciate that breakdown. You're right about the error:
it was a syntax error on that line; I'll make sure to include the
descriptions in the future. As far as finding a new tutorial, I am going to
see if Google's class works out with Python 3.1, and if not, I'll switch
over to a different one.

-Alexander

On Thu, Jul 28, 2011 at 10:27 PM, Steven D'Aprano <steve at pearwood.info>wrote:

> Alexander Quest wrote:
>
>> To clarify, the particular file that was giving me trouble was the basic
>> "hello world" file. The original code on line 29 read as such: print
>> 'Hello', name
>> When I ran "C:\google-python-exercises> python hello.py, it gave me an
>> error
>> on that line (line 29), but when I changed that line to print ('Hello',
>> name), that is, including the parentheses, it printed out "hello world" as
>> it should. I'm assuming that this means that one of the differences
>> between
>> Python 2.X and Python 3.X is that the print function necessitates
>> parentheses in the latter versions but not in the former.
>>
>
>
> Yes, that is correct.
>
> To be a programmer (whether professional or amateur), you need to learn to
> *pay attention to the error given*. "It gave me an error" is meaningless.
> What does the error message say?
>
> In this case, I expect it is a SyntaxError. But you need to learn to read
> the error message and understand what it is trying to tell you. Some errors
> are cryptic and don't help, but generally speaking Python is pretty good
> about giving useful error messages:
>
>
> >>> a = [1, 2, 3]
> >>> len a
>  File "<stdin>", line 1
>    len a
>        ^
> SyntaxError: invalid syntax
>
>
> Admittedly you do need to learn that Python functions require parentheses,
> but apart from that, the error tells you what is wrong: you can't follow a
> function len with another name a without something between them. This is
> illegal syntax.
>
>
>
>
>  I am a bit
>> confused as to why this is, assuming I am correct in my assumption above,
>> because I was under the impression that code written for earlier python
>> versions will work for later python versions, as is the case here.
>>
>
> Not quite. It is (mostly) true for Python 1.x and 2.x, but Python 3 has
> deliberately included some backwards incompatible changes. The biggest two
> are that strings are now Unicode rather than byte strings, and that print is
> now a function instead of a statement. So, yes, in Python 3 you have to call
> it with parentheses.
>
> The differences are still quite minor -- think of Python 2.x and Python 3.x
> being like the differences between American English and British English.
> Provided you pay attention to the error messages, and remember to add round
> brackets after print, tutorials for 2.x should still *mostly* work.
>
>
>
>  I just wanted to add this info to clarify my last question regarding
>> whether
>> or not I should install Python 2.X and uninstall Python 3.1 that I have
>> now,
>>
>
> Personally, I would consider it wiser to find a Python 3 tutorial. Python 3
> is the future, and you will need to learn it eventually.
>
>
>
>
> --
> Steven
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110729/3db7ddee/attachment.html>

From susana.delgado_s at utzmg.edu.mx  Fri Jul 29 19:27:05 2011
From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez)
Date: Fri, 29 Jul 2011 12:27:05 -0500
Subject: [Tutor] Sum files' size
In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2EA700B5AA@EMARC112VS01.exchad.jpmchase.net>
References: <CAFEP6HvS2vdEhT+vDE-dwZhvXXDw0FFPz4vXRe6nsBQQKxBSdA@mail.gmail.com>
	<0604E20B5F6F2F4784C9C8C71C5DD4DD2EA700B5AA@EMARC112VS01.exchad.jpmchase.net>
Message-ID: <CAFEP6Hty=8KwYxq1DGcX1X9F+srjXF-wDHLWeRk43=mcEpE28g@mail.gmail.com>

Thank you to all of you!

After I read your mails I started to modify my code, I applied Ramit
suggestion and got the result I wanted:

mport os
file_list = []
folders = None
for root, folders, files in os.walk('C:\\'):
            file_list.extend(os.path.join(
root,fi) for fi in files if (fi.endswith.shp))
for row, filepath in enumerate(file_list, start=1):
            n = os.path.splitext(filepath)
            p = n[0]+'.prj'
            shx = n[0]+'.shx'


#Function to get size in humam readable terms:
            def sizeof_fmt(num):
                 for x in ['bytes','KB','MB','GB','TB']:
                      if num < 1024.0:
                           return "%3.1f%s" % (num, x)
                      num /= 1024.0
            s = os.path.getsize(filepath)
            shx1 = os.path.getsize(shx)
            p1 = s = os.path.getsize(p)
total = sizeof_fmt(s+shx1+p1)



2011/7/28 Prasad, Ramit <ramit.prasad at jpmchase.com>

> >kb = sizeof_fmt(s)
> >shx1 = os.path.getsize(shx)
> >kb2 = sizeof_fmt(shx1)
> > total = kb+kb2+kb3
>
> Instead only retrieve the formatted output at the end. That way you will
> not have to worry about converting back from strings, nor have to worry
> about adding number with different units (e.g. 10KB + 10MB).
>
> kb = s
> kb2 = os.path.getsize(shx)
> total = sizeof_fmt(kb+kb2+kb3)
>
> Ramit
>
>
> Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
> 712 Main Street | Houston, TX 77002
> work phone: 713 - 216 - 5423
>
>
>
> This communication is for informational purposes only. It is not
> intended as an offer or solicitation for the purchase or sale of
> any financial instrument or as an official confirmation of any
> transaction. All market prices, data and other information are not
> warranted as to completeness or accuracy and are subject to change
> without notice. Any comments or statements made herein do not
> necessarily reflect those of JPMorgan Chase & Co., its subsidiaries
> and affiliates.
>
> This transmission may contain information that is privileged,
> confidential, legally privileged, and/or exempt from disclosure
> under applicable law. If you are not the intended recipient, you
> are hereby notified that any disclosure, copying, distribution, or
> use of the information contained herein (including any reliance
> thereon) is STRICTLY PROHIBITED. Although this transmission and any
> attachments are believed to be free of any virus or other defect
> that might affect any computer system into which it is received and
> opened, it is the responsibility of the recipient to ensure that it
> is virus free and no responsibility is accepted by JPMorgan Chase &
> Co., its subsidiaries and affiliates, as applicable, for any loss
> or damage arising in any way from its use. If you received this
> transmission in error, please immediately contact the sender and
> destroy the material in its entirety, whether in electronic or hard
> copy format. Thank you.
>
> Please refer to http://www.jpmorgan.com/pages/disclosures for
> disclosures relating to European legal entities.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110729/3b813300/attachment.html>

From stefan_ml at behnel.de  Fri Jul 29 20:04:37 2011
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 29 Jul 2011 20:04:37 +0200
Subject: [Tutor] Mainloop conflict
In-Reply-To: <CAKBg9Z3JSy20uVuAMirYvqNLSix5pCEtW53oyX4CJ98SM0y=jw@mail.gmail.com>
References: <CAKBg9Z0xjV8vPPMoxLtrHoEFTtxdme0=pj-XPyJZSpCTQ3mPuQ@mail.gmail.com>	<4E32067B.5080308@davea.name>
	<CAKBg9Z3JSy20uVuAMirYvqNLSix5pCEtW53oyX4CJ98SM0y=jw@mail.gmail.com>
Message-ID: <j0usnl$sev$1@dough.gmane.org>

Christopher King, 29.07.2011 17:08:
> On Thursday, July 28, 2011, Dave Angel wrote:
>> On 07/28/2011 08:32 PM, Christopher King wrote:
>>>
>>> Dear Tutor Dudes,
>>>      I have a socket Gui program. The only problem is that socket.recv
> waits
>>> for a response, which totally screws Tkinter I think. I tried making the
>>> timeout extremely small (it was alright if I didn't receive anything, I
>>> was excepting that a lot) but I think that screwed socket. Anyone have
> words
>>> of wisdom.
>>>
>>> Sincerely,
>>>      Me
>>>
>> Sure:
>>
>> Do the socket I/O on a separate thread.
>
> I was afraid of that.

Understandable. However, as I already said, you don't need to do that, just 
go the obvious route.

Stefan


From __peter__ at web.de  Fri Jul 29 22:17:13 2011
From: __peter__ at web.de (Peter Otten)
Date: Fri, 29 Jul 2011 22:17:13 +0200
Subject: [Tutor] Mainloop conflict
References: <CAKBg9Z0xjV8vPPMoxLtrHoEFTtxdme0=pj-XPyJZSpCTQ3mPuQ@mail.gmail.com>
	<4E32067B.5080308@davea.name>
	<CAKBg9Z3JSy20uVuAMirYvqNLSix5pCEtW53oyX4CJ98SM0y=jw@mail.gmail.com>
	<j0usnl$sev$1@dough.gmane.org>
Message-ID: <j0v4g6$dg9$1@dough.gmane.org>

Stefan Behnel wrote:

> Christopher King, 29.07.2011 17:08:
>> On Thursday, July 28, 2011, Dave Angel wrote:
>>> On 07/28/2011 08:32 PM, Christopher King wrote:
>>>>
>>>> Dear Tutor Dudes,
>>>>      I have a socket Gui program. The only problem is that socket.recv
>> waits
>>>> for a response, which totally screws Tkinter I think. I tried making
>>>> the timeout extremely small (it was alright if I didn't receive
>>>> anything, I was excepting that a lot) but I think that screwed socket.
>>>> Anyone have
>> words
>>>> of wisdom.
>>>>
>>>> Sincerely,
>>>>      Me
>>>>
>>> Sure:
>>>
>>> Do the socket I/O on a separate thread.
>>
>> I was afraid of that.
> 
> Understandable. However, as I already said, you don't need to do that,
> just go the obvious route.

While searching for

http://effbot.org/zone/tkinter-threads.htm

I stumbled upon

http://effbot.org/pyfaq/can-i-have-tk-events-handled-while-waiting-for-i-o.htm

which looks even simpler indeed.


From sergey at mighty.co.za  Fri Jul 29 23:01:00 2011
From: sergey at mighty.co.za (Sergey)
Date: Fri, 29 Jul 2011 23:01:00 +0200
Subject: [Tutor] List of lists optimization and printing.
Message-ID: <154cab62cb20c12c419384fa720e281f@mighty.webmail.co.za>

Hello.

Yes, catb.org and so on.
I was searching for some kind of finding max width in a table (a list of two
lists) and had found this mailing list.
So I want somebody to look at my code and say what can be done better from a
programmer point of view.
Just SQL like printing and writing.
I mean optimization.
I always want to know what is the best way. Thanks.
* I don't know is it good to paste 62 lines there so here's the pastie
http://pastie.org/2291721
I hope it will be monospaced.^U
I know about SQLAlchemy but I just want to have my data in plain text because I
can't find good cross-platform suites to keep contacts, many contacts. I mean
phone number, name and so on. Something for a little bit entertprise tasks.
Yes.
Thanks.
Debian bleeding edge.
Python 2.6 default. And 2.7, 3.2 too.

Site: site
Login: login
Password: password
[['site', 'login', 'password']]
[4, 5, 8]
+------+-------+----------+
| Site | Login | Password |
+------+-------+----------+
| site | login | password |
+------+-------+----------+

____________________________________________________________
South Africas premier free email service - www.webmail.co.za 

Save on insurance with OUTsurance
https://www.outsurance.co.za/insurance-quote/?source=webmailmailer&cr=facp11_468x60&cid=221



From emekamicro at gmail.com  Sat Jul 30 09:40:41 2011
From: emekamicro at gmail.com (Emeka)
Date: Sat, 30 Jul 2011 08:40:41 +0100
Subject: [Tutor] How to make tkMessage function to have duration
Message-ID: <CAOypoo5uEJYopDTCGvoe-NzoQBvkkb_Y_tz7uv2_2OtZW5QC0Q@mail.gmail.com>

Hello All,

Say I have the below(code), .... I would want the message to last say 30
seconds and afterwards disappear. I won't want the user to be the one to
enable it to disappear.

Basically, what I want is to be able to show the user some message , and
after some seconds, the message goes away

import Tkinter
import tkMessageBox

top = Tkinter.Tk()
def hello():
   tkMessageBox.showinfo("Say Hello", "Hello World")

B1 = Tkinter.Button(top, text = "Say Hello", command = hello)
B1.pack()

top.mainloop()

-- 
*Satajanus  Nig. Ltd


*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110730/64c12420/attachment.html>

From steve at pearwood.info  Sat Jul 30 13:25:27 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 30 Jul 2011 21:25:27 +1000
Subject: [Tutor] How to make tkMessage function to have duration
In-Reply-To: <CAOypoo5uEJYopDTCGvoe-NzoQBvkkb_Y_tz7uv2_2OtZW5QC0Q@mail.gmail.com>
References: <CAOypoo5uEJYopDTCGvoe-NzoQBvkkb_Y_tz7uv2_2OtZW5QC0Q@mail.gmail.com>
Message-ID: <4E33EA27.50301@pearwood.info>

Emeka wrote:
> Hello All,
> 
> Say I have the below(code), .... I would want the message to last say 30
> seconds and afterwards disappear. I won't want the user to be the one to
> enable it to disappear.
> 
> Basically, what I want is to be able to show the user some message , and
> after some seconds, the message goes away

I *hate* it when applications do that. Just as I'm trying to read the 
message, take a screen shot, or whatever, the message disappears. I 
think that's one of the worst things you can do in an application.

If the message isn't important enough to require it to stay visible 
until the user explicitly closes it, then it shouldn't go into a dialog 
in the first place.



-- 
Steven

From emekamicro at gmail.com  Sat Jul 30 17:27:21 2011
From: emekamicro at gmail.com (Emeka)
Date: Sat, 30 Jul 2011 16:27:21 +0100
Subject: [Tutor] How to make tkMessage function to have duration
In-Reply-To: <4E33EA27.50301@pearwood.info>
References: <CAOypoo5uEJYopDTCGvoe-NzoQBvkkb_Y_tz7uv2_2OtZW5QC0Q@mail.gmail.com>
	<4E33EA27.50301@pearwood.info>
Message-ID: <CAOypoo49WRri7EWAoiU96OUs8rPwCincc=teLm4jxKOOa5j6OQ@mail.gmail.com>

Steven,,


Thanks!


Emeka

On Sat, Jul 30, 2011 at 12:25 PM, Steven D'Aprano <steve at pearwood.info>wrote:

> Emeka wrote:
>
>> Hello All,
>>
>> Say I have the below(code), .... I would want the message to last say 30
>> seconds and afterwards disappear. I won't want the user to be the one to
>> enable it to disappear.
>>
>> Basically, what I want is to be able to show the user some message , and
>> after some seconds, the message goes away
>>
>
> I *hate* it when applications do that. Just as I'm trying to read the
> message, take a screen shot, or whatever, the message disappears. I think
> that's one of the worst things you can do in an application.
>
> If the message isn't important enough to require it to stay visible until
> the user explicitly closes it, then it shouldn't go into a dialog in the
> first place.
>
>
>
> --
> Steven
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>



-- 
*Satajanus  Nig. Ltd


*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110730/c3697f06/attachment.html>

From Tom_Roche at pobox.com  Sat Jul 30 23:49:02 2011
From: Tom_Roche at pobox.com (Tom Roche)
Date: Sat, 30 Jul 2011 17:49:02 -0400
Subject: [Tutor] newbie needs pypy setup tips
Message-ID: <877h6zfnht.fsf@pobox.com>


I need advice about configuring pypy to run other python code. Why I ask:

I'm running a model implemented in python. Unfortunately a run on "straight" python 2.6.x or 2.7.x requires

- 130 min on my ubuntu laptop (on which working would be more convenient)
- 55 min on a better build machine on which I currently have access

However I have read that this model runs 5x faster under pypy, so I wanna get me that, but I'm finding the pypy docs pretty inscrutable. Nevertheless, I have managed to do

me at it:~$ uname -rv
> 2.6.32-33-generic #70-Ubuntu SMP Thu Jul 7 21:13:52 UTC 2011
me at it:~$ which pypy
> /usr/local/bin/pypy
me at it:~$ ls -al $(which pypy)
> lrwxrwxrwx 1 root root 37 2011-07-30 16:06 /usr/local/bin/pypy -> /opt/pypy-c-jit-1.5.0-alpha0/bin/pypy
me at it:~$ pypy --version
> Python 2.7.1 (b590cf6de419, Apr 30 2011, 02:00:34)
> [PyPy 1.5.0-alpha0 with GCC 4.4.3]

However, when I try to *really* run the @#$%^&! thing, it spews:

me at it:~$ pypy
> debug: WARNING: library path not found, using compiled-in sys.path and sys.prefix will be unset
> 'import site' failed
> Python 2.7.1 (b590cf6de419, Apr 30 2011, 02:00:34)
> [PyPy 1.5.0-alpha0 with GCC 4.4.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> debug: OperationError:
> debug:  operror-type: ImportError
> debug:  operror-value: No module named _pypy_interact

What do I need to do to fix its library path?

TIA, Tom Roche <Tom_Roche at pobox.com>

From eire1130 at gmail.com  Sun Jul 31 00:06:04 2011
From: eire1130 at gmail.com (eire1130 at gmail.com)
Date: Sat, 30 Jul 2011 22:06:04 +0000
Subject: [Tutor] newbie needs pypy setup tips
In-Reply-To: <877h6zfnht.fsf@pobox.com>
References: <877h6zfnht.fsf@pobox.com>
Message-ID: <836810990-1312063566-cardhu_decombobulator_blackberry.rim.net-18925951-@b1.c28.bise6.blackberry>

I think, but not 100 percent, that pypy has a list. You might get better traction there if you don't get a good *nswer here.

Although I have a couple questions. Have you profiled in python to look for hotspots?

Have you tried writting portions in c?

What kind of model is it, out of curiousity.
Sent from my Verizon Wireless BlackBerry

-----Original Message-----
From: Tom Roche <Tom_Roche at pobox.com>
Sender: tutor-bounces+eire1130=gmail.com at python.org
Date: Sat, 30 Jul 2011 17:49:02 
To: <tutor at python.org>
Reply-To: tutor at python.org, Tom Roche <Tom_Roche at pobox.com>
Subject: [Tutor] newbie needs pypy setup tips


I need advice about configuring pypy to run other python code. Why I ask:

I'm running a model implemented in python. Unfortunately a run on "straight" python 2.6.x or 2.7.x requires

- 130 min on my ubuntu laptop (on which working would be more convenient)
- 55 min on a better build machine on which I currently have access

However I have read that this model runs 5x faster under pypy, so I wanna get me that, but I'm finding the pypy docs pretty inscrutable. Nevertheless, I have managed to do

me at it:~$ uname -rv
> 2.6.32-33-generic #70-Ubuntu SMP Thu Jul 7 21:13:52 UTC 2011
me at it:~$ which pypy
> /usr/local/bin/pypy
me at it:~$ ls -al $(which pypy)
> lrwxrwxrwx 1 root root 37 2011-07-30 16:06 /usr/local/bin/pypy -> /opt/pypy-c-jit-1.5.0-alpha0/bin/pypy
me at it:~$ pypy --version
> Python 2.7.1 (b590cf6de419, Apr 30 2011, 02:00:34)
> [PyPy 1.5.0-alpha0 with GCC 4.4.3]

However, when I try to *really* run the @#$%^&! thing, it spews:

me at it:~$ pypy
> debug: WARNING: library path not found, using compiled-in sys.path and sys.prefix will be unset
> 'import site' failed
> Python 2.7.1 (b590cf6de419, Apr 30 2011, 02:00:34)
> [PyPy 1.5.0-alpha0 with GCC 4.4.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> debug: OperationError:
> debug:  operror-type: ImportError
> debug:  operror-value: No module named _pypy_interact

What do I need to do to fix its library path?

TIA, Tom Roche <Tom_Roche at pobox.com>
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

From g.nius.ck at gmail.com  Sun Jul 31 04:30:34 2011
From: g.nius.ck at gmail.com (Christopher King)
Date: Sat, 30 Jul 2011 22:30:34 -0400
Subject: [Tutor] Mainloop conflict
In-Reply-To: <j0v4g6$dg9$1@dough.gmane.org>
References: <CAKBg9Z0xjV8vPPMoxLtrHoEFTtxdme0=pj-XPyJZSpCTQ3mPuQ@mail.gmail.com>
	<4E32067B.5080308@davea.name>
	<CAKBg9Z3JSy20uVuAMirYvqNLSix5pCEtW53oyX4CJ98SM0y=jw@mail.gmail.com>
	<j0usnl$sev$1@dough.gmane.org> <j0v4g6$dg9$1@dough.gmane.org>
Message-ID: <CAKBg9Z2eQmoYeBXxUhieCnCmnRWRiHwrEbJ=KBNWRN28T_5r+A@mail.gmail.com>

I think I'll go with threading. I've become more familiar with it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110730/9b42e528/attachment.html>

From stefan_ml at behnel.de  Sun Jul 31 07:01:41 2011
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Sun, 31 Jul 2011 07:01:41 +0200
Subject: [Tutor] Mainloop conflict
In-Reply-To: <CAKBg9Z2eQmoYeBXxUhieCnCmnRWRiHwrEbJ=KBNWRN28T_5r+A@mail.gmail.com>
References: <CAKBg9Z0xjV8vPPMoxLtrHoEFTtxdme0=pj-XPyJZSpCTQ3mPuQ@mail.gmail.com>	<4E32067B.5080308@davea.name>	<CAKBg9Z3JSy20uVuAMirYvqNLSix5pCEtW53oyX4CJ98SM0y=jw@mail.gmail.com>	<j0usnl$sev$1@dough.gmane.org>
	<j0v4g6$dg9$1@dough.gmane.org>
	<CAKBg9Z2eQmoYeBXxUhieCnCmnRWRiHwrEbJ=KBNWRN28T_5r+A@mail.gmail.com>
Message-ID: <j12njl$3rj$1@dough.gmane.org>

Christopher King, 31.07.2011 04:30:
> I think I'll go with threading. I've become more familiar with it.

That's ok. When used carefully, threads can be pretty helpful to gain 
concurrency in I/O tasks.

But just in case you ever feel like using them for anything else, this is 
worth a read:

http://ptolemy.eecs.berkeley.edu/publications/papers/06/problemwithThreads/

Stefan


From rdmoores at gmail.com  Sun Jul 31 07:28:11 2011
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sat, 30 Jul 2011 22:28:11 -0700
Subject: [Tutor] How to replace the '\'s in a path with '/'s?
Message-ID: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>

64-bit Vista
Python 3.2.1

I would like to write a function that would take a path such as
'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
and return 'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' . I've
tried this:

def test(path):
   return path.replace('\', '/')

print(test('C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'))

gets me

File "c:\P32Working\untitled-5.py", line 2
   return path.replace('\', '/')
                               ^
SyntaxError: EOL while scanning string literal
Process terminated with an exit code of 1

Thanks,

Dick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110730/efc1caf7/attachment.html>

From shahdharmit at gmail.com  Sun Jul 31 08:09:45 2011
From: shahdharmit at gmail.com (Dharmit Shah)
Date: Sun, 31 Jul 2011 11:39:45 +0530
Subject: [Tutor] How to replace the '\'s in a path with '/'s?
In-Reply-To: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
References: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
Message-ID: <CAJQZracs=cfM93Ps-AFrHBQ1B_tMx1k6oS0=DMV4-T2kX_AAmQ@mail.gmail.com>

Ruchard,

Try return path.replace('\\', '/'). That gave me the output desired by you.
I don't know the reason. But I guess it's because \ is used as escape
character. I am sure someone in the list will point out the accurate reason.

On Sun, Jul 31, 2011 at 10:58 AM, Richard D. Moores <rdmoores at gmail.com>wrote:

> 64-bit Vista
> Python 3.2.1
>
> I would like to write a function that would take a path such as
> 'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
> and return 'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' . I've
> tried this:
>
> def test(path):
>    return path.replace('\', '/')
>
> print(test('C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'))
>
> gets me
>
> File "c:\P32Working\untitled-5.py", line 2
>    return path.replace('\', '/')
>                                ^
> SyntaxError: EOL while scanning string literal
> Process terminated with an exit code of 1
>
> Thanks,
>
> Dick
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Regards

Dharmit Shah <http://about.me/dharmit>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110731/aeb9bf34/attachment.html>

From ian.douglas at iandouglas.com  Sun Jul 31 08:14:36 2011
From: ian.douglas at iandouglas.com (ian douglas)
Date: Sat, 30 Jul 2011 23:14:36 -0700
Subject: [Tutor] How to replace the '\'s in a path with '/'s?
In-Reply-To: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
References: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
Message-ID: <CAFNSOgXwOPoUMLQ6X8Ze4j7BHQV9hYL46HXh8NWbbo9xCw1ukw@mail.gmail.com>

Try a double backslash

replace('\\','/')
On Jul 30, 2011 10:30 PM, "Richard D. Moores" <rdmoores at gmail.com> wrote:
> 64-bit Vista
> Python 3.2.1
>
> I would like to write a function that would take a path such as
> 'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
> and return 'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' .
I've
> tried this:
>
> def test(path):
> return path.replace('\', '/')
>
> print(test('C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'))
>
> gets me
>
> File "c:\P32Working\untitled-5.py", line 2
> return path.replace('\', '/')
> ^
> SyntaxError: EOL while scanning string literal
> Process terminated with an exit code of 1
>
> Thanks,
>
> Dick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110730/bfffec09/attachment.html>

From rhettnaxel at gmail.com  Sun Jul 31 08:16:26 2011
From: rhettnaxel at gmail.com (Alexander Etter)
Date: Sun, 31 Jul 2011 02:16:26 -0400
Subject: [Tutor] How to replace the '\'s in a path with '/'s?
In-Reply-To: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
References: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
Message-ID: <842D67E9-C063-4A10-AEF9-4C110E4DA1C2@gmail.com>

On Jul 31, 2011, at 1:28, "Richard D. Moores" <rdmoores at gmail.com> wrote:

> 64-bit Vista
> Python 3.2.1
> 
> I would like to write a function that would take a path such as 'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
> and return 'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf' . I've tried this:
> 
> def test(path):
>    return path.replace('\', '/')
> 
> print(test('C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'))
> 
> gets me
> 
> File "c:\P32Working\untitled-5.py", line 2
>    return path.replace('\', '/')
>                                ^
> SyntaxError: EOL while scanning string literal
> Process terminated with an exit code of 1
> 
> Thanks,
> 
> Dick
> 
Hi Dick. EOL means End-of-line. Try using double slashes when specifying a path. The back slash  \ by itself may be interpreted as an escape character or keyword. For example:
print(test('C:\\Users\\Dick\\Desktop\\Documents\\Notes\\CollegeNotes.rtf'))
Hope that helps,
Alexander
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110731/12b0bd3e/attachment.html>

From sandipb at foss-community.com  Sun Jul 31 08:32:18 2011
From: sandipb at foss-community.com (Sandip Bhattacharya)
Date: Sun, 31 Jul 2011 12:02:18 +0530
Subject: [Tutor] How to replace the '\'s in a path with '/'s?
In-Reply-To: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
References: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
Message-ID: <20110731063218.GA2757@sandipb.net>

On Sat, Jul 30, 2011 at 10:28:11PM -0700, Richard D. Moores wrote:
> File "c:\P32Working\untitled-5.py", line 2
>    return path.replace('\', '/')
>                                ^
> SyntaxError: EOL while scanning string literal
> Process terminated with an exit code of 1

The first backslash up there is escaping the ending quote. This is  what
you want:
    return path.replace('\\', '/')

Generally, converting slashes manually should be kept at a minimum. You
should be using library functions as much as possible. The experts here
can correct me here, but this is a roundabout way I would be doing this:

    # I use a linux machine. Using this to work with Windows paths
    # Use os.path if you are on windows
    import ntpath

    # Use raw strings so that backslash doesnt matter
    path=r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'

    #take out drive first because ntpath.split end sentinel is predictable that way
    drive,rest = ntpath.splitdrive(path)

    # This will store the path components
    comps = []
    comps.append(drive)

    while rest != '\\':
        parts = ntpath.split(rest)
        comps.insert(1,parts[1])
        rest = parts[0]


    print '/'.join(comps)

I am not happy with the loop to collect the components. But I couldn't
find a single path function which splits a path into all the components
in one go.

- Sandip



From steve at pearwood.info  Sun Jul 31 09:29:48 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 31 Jul 2011 17:29:48 +1000
Subject: [Tutor] How to replace the '\'s in a path with '/'s?
In-Reply-To: <20110731063218.GA2757@sandipb.net>
References: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
	<20110731063218.GA2757@sandipb.net>
Message-ID: <4E35046C.1090903@pearwood.info>

Sandip Bhattacharya wrote:

> Generally, converting slashes manually should be kept at a minimum. You
> should be using library functions as much as possible. The experts here
> can correct me here, but this is a roundabout way I would be doing this:

str.replace('\\', '/') is a perfectly fine library function to use to 
convert backslashes.

[...]
>     # Use raw strings so that backslash doesnt matter
>     path=r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'

That's not quite true. Even with raw strings, you can't write:

path = r'C:\Users\Dick\Desktop\Documents\Notes\'

Try it and see what happens.


[...]
> I am not happy with the loop to collect the components. But I couldn't
> find a single path function which splits a path into all the components
> in one go.

Just use str.split.

Be prepared to filter out empty path components if the user enters a 
path with doubled-up backslashes:

C:\Users\Dick\\Desktop

but that's no real difficulty.



-- 
Steven


From steve at pearwood.info  Sun Jul 31 10:03:09 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 31 Jul 2011 18:03:09 +1000
Subject: [Tutor] How to replace the '\'s in a path with '/'s?
In-Reply-To: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
References: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
Message-ID: <4E350C3D.2080007@pearwood.info>

Richard D. Moores wrote:

> File "c:\P32Working\untitled-5.py", line 2
>    return path.replace('\', '/')
>                                ^
> SyntaxError: EOL while scanning string literal


Others have already told you how to solve the immediate problem (namely, 
escape the backslash), but I'd like to talk more about general 
problem-solving techniques, in the principle that it is better to teach 
someone how to catch their own fish rather than just to feed them fish 
for a day.

As a programmer (amateur or profession), we *must* learn to read the 
error messages and glean as much information as possible. In this case, 
the error tells you that the line couldn't even be executed, because it 
doesn't compile: you get a SyntaxError.

SyntaxErrors show you where the failure occurs: look at the ^ up-arrow 
under the line of code. It points to the end of the line. Combine that 
with the error message "EOL while scanning string literal" and the cause 
of the error is solved: Python ran out of line before the string was closed.

(You may need to google on "EOL" to learn that it means "End Of Line".)

This of course opens more questions. Python, apparently, thinks that the 
closing bracket ) is inside a string, instead of outside of it. Look at 
the offending line and work backwards, and you should be able to see 
that Python sees the line as:

     return path.replace( AAA / BBB

where AAA is the string '\', ' and BBB is the broken string ')


This gives you a clue to try in the interactive interpreter. You should 
*expect* this to raise an exception, but it does not:

 >>> s = '\', '
 >>> print s
',
 >>> print repr(s)
"', "



which should lead you to googling on "python backslash", which in turn 
leads to a mass of information. Just from the google search results 
themselves, I see:

   # first search result
   2. Lexical analysis ? Python v2.7.2 documentation
   Python uses the 7-bit ASCII character set for program text. ... A
   backslash does not continue a token except for string literals


   # second search result
   2.4.1 String literals
   21 Feb 2008 ? The backslash ( \ ) character is used to escape
   characters ...


   # third result
   Python Gotchas
   3 Jun 2008 ? 2 "raw" strings and backslashes (when dealing with
   Windows filenames). ...


The first one looks a bit technical (what on earth is lexical analysis? 
-- look it up if you care) but the second and third look very promising. 
Backslash is used to escape characters, and backslashes in Windows 
filenames are a Gotcha.


And now you know how to catch fish :)




-- 
Steven

From rdmoores at gmail.com  Sun Jul 31 11:35:00 2011
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sun, 31 Jul 2011 02:35:00 -0700
Subject: [Tutor] How to replace the '\'s in a path with '/'s?
In-Reply-To: <20110731063218.GA2757@sandipb.net>
References: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
	<20110731063218.GA2757@sandipb.net>
Message-ID: <CALMxxx=EnqNzsmUVRfSt47Op=a7adD0ANbzzYJm4mYX=1O3k8w@mail.gmail.com>

On Sat, Jul 30, 2011 at 23:32, Sandip Bhattacharya
<sandipb at foss-community.com> wrote:
>
> On Sat, Jul 30, 2011 at 10:28:11PM -0700, Richard D. Moores wrote:
> > File "c:\P32Working\untitled-5.py", line 2
> > ? ?return path.replace('\', '/')
> > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?^
> > SyntaxError: EOL while scanning string literal
> > Process terminated with an exit code of 1
>
> The first backslash up there is escaping the ending quote. This is ?what
> you want:
> ? ?return path.replace('\\', '/')
>
> Generally, converting slashes manually should be kept at a minimum. You
> should be using library functions as much as possible. The experts here
> can correct me here, but this is a roundabout way I would be doing this:
>
> ? ?# I use a linux machine. Using this to work with Windows paths
> ? ?# Use os.path if you are on windows
> ? ?import ntpath
>
> ? ?# Use raw strings so that backslash doesnt matter
> ? ?path=r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
>
> ? ?#take out drive first because ntpath.split end sentinel is predictable that way
> ? ?drive,rest = ntpath.splitdrive(path)
>
> ? ?# This will store the path components
> ? ?comps = []
> ? ?comps.append(drive)
>
> ? ?while rest != '\\':
> ? ? ? ?parts = ntpath.split(rest)
> ? ? ? ?comps.insert(1,parts[1])
> ? ? ? ?rest = parts[0]
>
>
> ? ?print '/'.join(comps)
>
> I am not happy with the loop to collect the components. But I couldn't
> find a single path function which splits a path into all the components
> in one go.

Terrific! I now have my function, thanks to Sandip:

def fwd2bk_path_slashes(path):
? ? import os.path

? ? # Use raw strings so that backslash doesn't matter
? ? #path=r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'

? ? #take out drive first because os.path.split end sentinel is
predictable that way
? ? drive, rest = os.path.splitdrive(path)

? ? # This will store the path components
? ? comps = []
? ? comps.append(drive)

? ? while rest != '\\':
? ? ? ? parts = os.path.split(rest)
? ? ? ? comps.insert(1, parts[1])
? ? ? ? rest = parts[0]

? ? return ('/'.join(comps))


I've put it in my mycomp.py module, my collection of useful functions.
>>> from mycalc import fwd2bk_path_slashes
>>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
>>> fwd3bk_path_slashes(path)
'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf'


BTW I had figured out that I could solve my problem if I either
manually doubled all the backslashes in the path or manually changed
each backslash to a forward slash, but that wouldn't solve my problem
-- I wanted a function that would convert paths such as

'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
to paths such as
'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf'

I can live with having to put the path in single quotes and then
precede this with an  r  .

===============Stop reading here; what follows is OT====================

I'll explain why I wanted the function for those few who might be curious:

I have a bunch of RTF files which are used to collect one sort of
information or another. Comcast Voicemail Notes.rtf, Diary.rtf, Python
Notes.rtf, IPython Notes.rtf, Vista Notes.rtf, Agent Ransack Tips.rtf,
etc.

I also use ActiveWords (http://www.activewords.com/). I've been using
it for years, and now have over 1600 "active words" that do all sorts
of things for me: access websites (with my default browser), call
programs, open folders, execute Python programs, etc. And of course,
open files such as those RTF files. One of those RTFs is
ActiveWords,rtf (which I open using the activeword 'aw'. 'nyt' gets me
to the New York Times; 'at' (for 'add times') executes/calls my Python
script for adding times (such as track times on a CD), 'prec' (for
'precision') enters an often used bit of code,
'decimal.getcontext().prec ='.

Now of course I can remember only the activewords that I frequently
use. To retrieve the others of the 1600+, I have them all listed, one
per line in ActiveWords.rtf, and have a Python script that essentially
greps them for the one I want. Each line has the activeword, a short
description of what it does, and the path if the activeword opens a
folder or a file. For each path, I copy it from Windows Explorer
(using Shift when I right-click on the file or folder, then select
'Copy as path' from the context menu that opens. But if I paste this
into its line in ActiveWords.rtf, my grepping script makes a mess of
it. Therefore my need for a function to first convert those
backslashes to forward slashes.

Dick

From __peter__ at web.de  Sun Jul 31 12:34:18 2011
From: __peter__ at web.de (Peter Otten)
Date: Sun, 31 Jul 2011 12:34:18 +0200
Subject: [Tutor] How to replace the '\'s in a path with '/'s?
References: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
	<20110731063218.GA2757@sandipb.net>
Message-ID: <j13b30$kr$1@dough.gmane.org>

Sandip Bhattacharya wrote:

> On Sat, Jul 30, 2011 at 10:28:11PM -0700, Richard D. Moores wrote:
>> File "c:\P32Working\untitled-5.py", line 2
>>    return path.replace('\', '/')
>>                                ^
>> SyntaxError: EOL while scanning string literal
>> Process terminated with an exit code of 1
> 
> The first backslash up there is escaping the ending quote. This is  what
> you want:
>     return path.replace('\\', '/')
> 
> Generally, converting slashes manually should be kept at a minimum. You
> should be using library functions as much as possible. The experts here
> can correct me here, but this is a roundabout way I would be doing this:
> 
>     # I use a linux machine. Using this to work with Windows paths
>     # Use os.path if you are on windows
>     import ntpath
> 
>     # Use raw strings so that backslash doesnt matter
>     path=r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
> 
>     #take out drive first because ntpath.split end sentinel is predictable
>     #that way
>     drive,rest = ntpath.splitdrive(path)
> 
>     # This will store the path components
>     comps = []
>     comps.append(drive)
> 
>     while rest != '\\':
>         parts = ntpath.split(rest)
>         comps.insert(1,parts[1])
>         rest = parts[0]
> 
> 
>     print '/'.join(comps)
> 
> I am not happy with the loop to collect the components. But I couldn't
> find a single path function which splits a path into all the components
> in one go.

What happens if the path looks like 

r"C:relative\path\to\my\file.txt"

or

r"C:/mixed\slashes.txt"?


From sergey at mighty.co.za  Sun Jul 31 17:35:26 2011
From: sergey at mighty.co.za (Sergey)
Date: Sun, 31 Jul 2011 17:35:26 +0200
Subject: [Tutor] How to replace the '\'s in a path with '/'s?
In-Reply-To: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
References: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
Message-ID: <c37bb45ebb0ba472af39caed113bc6b5@mighty.co.za>

Maybe something useful could be find in urllib? It can open local files. And
UNIX slashes are equal to Web slashes.
http://docs.python.org/release/3.2.1/library/urllib.request.html#urllib.request.URLopener
--
class urllib.request.URLopener(proxies=None, **x509)

    Base class for opening and reading URLs. Unless you need to support opening
objects using schemes other than http:, ftp:, or file:, you probably want to use
FancyURLopener.
--

>On Sat, 30 Jul 2011 22:28:11 -0700 "Richard D. Moores" <rdmoores at gmail.com>
wrote

>I would like to write a function that would take a path 

____________________________________________________________
South Africas premier free email service - www.webmail.co.za 

For super low premiums, click here http://www.dialdirect.co.za/?vdn=15828



From rdmoores at gmail.com  Sun Jul 31 17:52:58 2011
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sun, 31 Jul 2011 08:52:58 -0700
Subject: [Tutor] How to replace the '\'s in a path with '/'s?
In-Reply-To: <j13b30$kr$1@dough.gmane.org>
References: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
	<20110731063218.GA2757@sandipb.net> <j13b30$kr$1@dough.gmane.org>
Message-ID: <CALMxxx=ijFiirj26ix7w+_vO5_ykUAc8BNguSoObGtK0aad=KA@mail.gmail.com>

On Sun, Jul 31, 2011 at 03:34, Peter Otten <__peter__ at web.de> wrote:
>
> Sandip Bhattacharya wrote:
>
> > On Sat, Jul 30, 2011 at 10:28:11PM -0700, Richard D. Moores wrote:
> >> File "c:\P32Working\untitled-5.py", line 2
> >> ? ?return path.replace('\', '/')
> >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?^
> >> SyntaxError: EOL while scanning string literal
> >> Process terminated with an exit code of 1
> >
> > The first backslash up there is escaping the ending quote. This is ?what
> > you want:
> > ? ? return path.replace('\\', '/')
> >
> > Generally, converting slashes manually should be kept at a minimum. You
> > should be using library functions as much as possible. The experts here
> > can correct me here, but this is a roundabout way I would be doing this:
> >
> > ? ? # I use a linux machine. Using this to work with Windows paths
> > ? ? # Use os.path if you are on windows
> > ? ? import ntpath
> >
> > ? ? # Use raw strings so that backslash doesnt matter
> > ? ? path=r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
> >
> > ? ? #take out drive first because ntpath.split end sentinel is predictable
> > ? ? #that way
> > ? ? drive,rest = ntpath.splitdrive(path)
> >
> > ? ? # This will store the path components
> > ? ? comps = []
> > ? ? comps.append(drive)
> >
> > ? ? while rest != '\\':
> > ? ? ? ? parts = ntpath.split(rest)
> > ? ? ? ? comps.insert(1,parts[1])
> > ? ? ? ? rest = parts[0]
> >
> >
> > ? ? print '/'.join(comps)
> >
> > I am not happy with the loop to collect the components. But I couldn't
> > find a single path function which splits a path into all the components
> > in one go.
>
> What happens if the path looks like
>
> r"C:relative\path\to\my\file.txt"
>
> or
>
> r"C:/mixed\slashes.txt"?
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

From rdmoores at gmail.com  Sun Jul 31 17:57:02 2011
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sun, 31 Jul 2011 08:57:02 -0700
Subject: [Tutor] How to replace the '\'s in a path with '/'s?
In-Reply-To: <j13b30$kr$1@dough.gmane.org>
References: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
	<20110731063218.GA2757@sandipb.net> <j13b30$kr$1@dough.gmane.org>
Message-ID: <CALMxxx=_Q05HDXp=3p=Lj5c7uUHBTQMYrFs3m95+P3HmUKC+4w@mail.gmail.com>

On Sun, Jul 31, 2011 at 03:34, Peter Otten <__peter__ at web.de> wrote:
> Sandip Bhattacharya wrote:
>
>> On Sat, Jul 30, 2011 at 10:28:11PM -0700, Richard D. Moores wrote:
>>> File "c:\P32Working\untitled-5.py", line 2
>>> ? ?return path.replace('\', '/')
>>> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?^
>>> SyntaxError: EOL while scanning string literal
>>> Process terminated with an exit code of 1
>>
>> The first backslash up there is escaping the ending quote. This is ?what
>> you want:
>> ? ? return path.replace('\\', '/')
>>
>> Generally, converting slashes manually should be kept at a minimum. You
>> should be using library functions as much as possible. The experts here
>> can correct me here, but this is a roundabout way I would be doing this:
>>
>> ? ? # I use a linux machine. Using this to work with Windows paths
>> ? ? # Use os.path if you are on windows
>> ? ? import ntpath
>>
>> ? ? # Use raw strings so that backslash doesnt matter
>> ? ? path=r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
>>
>> ? ? #take out drive first because ntpath.split end sentinel is predictable
>> ? ? #that way
>> ? ? drive,rest = ntpath.splitdrive(path)
>>
>> ? ? # This will store the path components
>> ? ? comps = []
>> ? ? comps.append(drive)
>>
>> ? ? while rest != '\\':
>> ? ? ? ? parts = ntpath.split(rest)
>> ? ? ? ? comps.insert(1,parts[1])
>> ? ? ? ? rest = parts[0]
>>
>>
>> ? ? print '/'.join(comps)
>>
>> I am not happy with the loop to collect the components. But I couldn't
>> find a single path function which splits a path into all the components
>> in one go.
>
> What happens if the path looks like
>
> r"C:relative\path\to\my\file.txt"
>
> or
>
> r"C:/mixed\slashes.txt"?

Not quite sure what the intent of your question is, but all the paths
I want to modify are full, with only back slashes.

Dick

From sergey at mighty.co.za  Sun Jul 31 17:59:33 2011
From: sergey at mighty.co.za (Sergey)
Date: Sun, 31 Jul 2011 17:59:33 +0200
Subject: [Tutor] How to replace the '\'s in a path with '/'s?
In-Reply-To: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
References: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
Message-ID: <932e280e5da69d1cdaf40b009540eec5@mighty.co.za>

Gotcha!
http://pymon.googlecode.com/svn/tags/pymon-0.2/Internet/rsync.py
231-239 strings

## code ##

def convertPath(path):
	# Convert windows, mac path to unix version.
	separator = os.path.normpath("/")
	if separator != "/":
		path = re.sub(re.escape(separator), "/", path)

	# Help file, folder pattern to express that it should match the all file or
folder name.
	path = "/" + path
	return path

## code ##

>On Sat, 30 Jul 2011 22:28:11 -0700 "Richard D. Moores" <rdmoores at gmail.com>
wrote


____________________________________________________________
South Africas premier free email service - www.webmail.co.za 

Save on insurance with OUTsurance
https://www.outsurance.co.za/insurance-quote/?source=webmailmailer&cr=facp11_468x60&cid=221



From rdmoores at gmail.com  Sun Jul 31 18:18:33 2011
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sun, 31 Jul 2011 09:18:33 -0700
Subject: [Tutor] How to replace the '\'s in a path with '/'s?
In-Reply-To: <932e280e5da69d1cdaf40b009540eec5@mighty.co.za>
References: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
	<932e280e5da69d1cdaf40b009540eec5@mighty.co.za>
Message-ID: <CALMxxxkRBrZgxPf_oyj+84RGPB4Y-dR-cwaxiMfDHwyVr=PSbA@mail.gmail.com>

On Sun, Jul 31, 2011 at 08:59, Sergey <sergey at mighty.co.za> wrote:
> Gotcha!
> http://pymon.googlecode.com/svn/tags/pymon-0.2/Internet/rsync.py
> 231-239 strings
>
> ## code ##
>
> def convertPath(path):
> ? ? ? ?# Convert windows, mac path to unix version.
> ? ? ? ?separator = os.path.normpath("/")
> ? ? ? ?if separator != "/":
> ? ? ? ? ? ? ? ?path = re.sub(re.escape(separator), "/", path)
>
> ? ? ? ?# Help file, folder pattern to express that it should match the all file or
> folder name.
> ? ? ? ?path = "/" + path
> ? ? ? ?return path
>
> ## code ##

Nice!

I went with


import os.path
import re

def convertPath(path):
    separator = os.path.normpath("/")
    if separator != "/":
        path = re.sub(re.escape(separator), "/", path)

    return path



path=r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'

print(convertPath(path))

"""
Output
C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf
"""
Dick

From sergey at mighty.co.za  Sun Jul 31 18:32:13 2011
From: sergey at mighty.co.za (Sergey)
Date: Sun, 31 Jul 2011 18:32:13 +0200
Subject: [Tutor] How to replace the '\'s in a path with '/'s?
In-Reply-To: <CALMxxxkRBrZgxPf_oyj+84RGPB4Y-dR-cwaxiMfDHwyVr=PSbA@mail.gmail.com>
References: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
	<932e280e5da69d1cdaf40b009540eec5@mighty.co.za> ,
	<CALMxxxkRBrZgxPf_oyj+84RGPB4Y-dR-cwaxiMfDHwyVr=PSbA@mail.gmail.com>
Message-ID: <49ffa4f61bfa609ad9c8e07ab55116e2@mighty.webmail.co.za>

Haha. Works!
Happy help you.
Ask gurus about regexps. I know they have an opinion about its speed and
optimization. So they can try to criticise. But the problem is solved. It's
good. 


On Sun, 31 Jul 2011 09:18:33 -0700 "Richard D. Moores" <rdmoores at gmail.com>
wrote

> 
> Nice!
> 
> I went with
> 
> 
> import os.path
> import re
> 
> def convertPath(path):
>     separator = os.path.normpath("/")
>     if separator != "/":
>         path = re.sub(re.escape(separator), "/", path)
> 
>     return path
> 
> 
> 
> path=r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
> 
> print(convertPath(path))
> 
> """
> Output
> C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf
> """
> Dick

____________________________________________________________
South Africas premier free email service - www.webmail.co.za 

For super low premiums, click here http://www.dialdirect.co.za/?vdn=15828



From steve at pearwood.info  Sun Jul 31 18:37:09 2011
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 01 Aug 2011 02:37:09 +1000
Subject: [Tutor] How to replace the '\'s in a path with '/'s?
In-Reply-To: <932e280e5da69d1cdaf40b009540eec5@mighty.co.za>
References: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
	<932e280e5da69d1cdaf40b009540eec5@mighty.co.za>
Message-ID: <4E3584B5.3040709@pearwood.info>

Sergey wrote:
> Gotcha!
> http://pymon.googlecode.com/svn/tags/pymon-0.2/Internet/rsync.py
> 231-239 strings
> 
> ## code ##
> 
> def convertPath(path):
> 	# Convert windows, mac path to unix version.
> 	separator = os.path.normpath("/")
> 	if separator != "/":
> 		path = re.sub(re.escape(separator), "/", path)

The above code is buggy. It doesn't work as expected on a classic Mac. 
Hint: import macpath; print macpath.normpath('/')

Besides, there is no need to use the 20 lb sledgehammer of regular 
expressions to crack the tiny little peanut of replacing a simple 
character with another simple character.

The above function is much more sensibly written as:

def convertPath(path):
     separator = os.path.sep
     if sep != '/':
         path = path.replace(os.path.sep, '/')
     return path

Or even more simply:

     return path.replace(os.path.sep, '/')

(although that may do a small amount of unnecessary work on Unix systems).




-- 
Steven


From sergey at mighty.co.za  Sun Jul 31 18:52:58 2011
From: sergey at mighty.co.za (Sergey)
Date: Sun, 31 Jul 2011 18:52:58 +0200
Subject: [Tutor] How to replace the '\'s in a path with '/'s?
In-Reply-To: <4E3584B5.3040709@pearwood.info>
References: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
	<932e280e5da69d1cdaf40b009540eec5@mighty.co.za> ,
	<4E3584B5.3040709@pearwood.info>
Message-ID: <f78453841e61b29f305b9a43063922d4@mighty.webmail.co.za>

Nice!
That's what I've been expecting.
Thanks.

Your one string command is tiny and complete. And elegant.
Final desicion?
Or it could be something better and more professional?
So we have removed regexps and everything is fine now. Yes?


On Mon, 01 Aug 2011 02:37:09 +1000 Steven D'Aprano <steve at pearwood.info> wrote

> Sergey wrote:
> > Gotcha!
> > http://pymon.googlecode.com/svn/tags/pymon-0.2/Internet/rsync.py
> > 231-239 strings
> >
> > ## code ##
> >
> > def convertPath(path):
> > 	# Convert windows, mac path to unix version.
> > 	separator = os.path.normpath("/")
> > 	if separator != "/":
> > 		path = re.sub(re.escape(separator), "/", path)
> 
> The above code is buggy. It doesn't work as expected on a classic Mac.
> Hint: import macpath; print macpath.normpath('/')
> 
> Besides, there is no need to use the 20 lb sledgehammer of regular
> expressions to crack the tiny little peanut of replacing a simple
> character with another simple character.
> 
> The above function is much more sensibly written as:
> 
> def convertPath(path):
>      separator = os.path.sep
>      if sep != '/':
>          path = path.replace(os.path.sep, '/')
>      return path
> 
> Or even more simply:
> 
>      return path.replace(os.path.sep, '/')
> 
> (although that may do a small amount of unnecessary work on Unix systems).
> 
> 
> 
> 
> --
> Steven
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



____________________________________________________________
South Africas premier free email service - www.webmail.co.za 

For super low premiums, click here http://www.dialdirect.co.za/?vdn=15828



From __peter__ at web.de  Sun Jul 31 19:34:52 2011
From: __peter__ at web.de (Peter Otten)
Date: Sun, 31 Jul 2011 19:34:52 +0200
Subject: [Tutor] How to replace the '\'s in a path with '/'s?
References: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
	<20110731063218.GA2757@sandipb.net> <j13b30$kr$1@dough.gmane.org>
	<CALMxxx=_Q05HDXp=3p=Lj5c7uUHBTQMYrFs3m95+P3HmUKC+4w@mail.gmail.com>
Message-ID: <j143nh$sd5$1@dough.gmane.org>

Richard D. Moores wrote:

>> What happens if the path looks like
>>
>> r"C:relative\path\to\my\file.txt"
>>
>> or
>>
>> r"C:/mixed\slashes.txt"?
> 
> Not quite sure what the intent of your question is, but all the paths
> I want to modify are full, with only back slashes.

If you invoke your fwd2bk_path_slashes() with one of those paths it'll stay 
in the while loop forever (until it runs out of memory). 

I'd consider that a bug that you should be aware of.



From rdmoores at gmail.com  Sun Jul 31 19:50:41 2011
From: rdmoores at gmail.com (Richard D. Moores)
Date: Sun, 31 Jul 2011 10:50:41 -0700
Subject: [Tutor] How to replace the '\'s in a path with '/'s?
In-Reply-To: <j143nh$sd5$1@dough.gmane.org>
References: <CALMxxx=Ntr_Y7TM-hCkz-oZLgorxDQq=wxgS2hYtkQx+avZ9iA@mail.gmail.com>
	<20110731063218.GA2757@sandipb.net> <j13b30$kr$1@dough.gmane.org>
	<CALMxxx=_Q05HDXp=3p=Lj5c7uUHBTQMYrFs3m95+P3HmUKC+4w@mail.gmail.com>
	<j143nh$sd5$1@dough.gmane.org>
Message-ID: <CALMxxx=B=4izQkFWFMswOjakgHcqbqjCszrqTa8j9eKZYGwE1A@mail.gmail.com>

On Sun, Jul 31, 2011 at 10:34, Peter Otten <__peter__ at web.de> wrote:
>
> Richard D. Moores wrote:
>
> >> What happens if the path looks like
> >>
> >> r"C:relative\path\to\my\file.txt"
> >>
> >> or
> >>
> >> r"C:/mixed\slashes.txt"?
> >
> > Not quite sure what the intent of your question is, but all the paths
> > I want to modify are full, with only back slashes.
>
> If you invoke your fwd2bk_path_slashes() with one of those paths it'll stay
> in the while loop forever (until it runs out of memory).
>
> I'd consider that a bug that you should be aware of.

Yes. Thanks.

Dick

From rhettnaxel at gmail.com  Sun Jul 31 20:22:41 2011
From: rhettnaxel at gmail.com (Alexander Etter)
Date: Sun, 31 Jul 2011 14:22:41 -0400
Subject: [Tutor] Mailing list documentation
Message-ID: <CE62CCFD-0165-4A4F-8E6C-139084C3A49D@gmail.com>

Hello everyone, is there a page that contains documentation for this mailing list? I've seen a few users top post and others advise against it; if there isn't a page listing conventions let's create it and if there is what is it's URL and how do you suggest users read it?
Alexander

From sergey at mighty.co.za  Sun Jul 31 21:30:07 2011
From: sergey at mighty.co.za (Sergey)
Date: Sun, 31 Jul 2011 21:30:07 +0200
Subject: [Tutor] Mailing list documentation
In-Reply-To: <CE62CCFD-0165-4A4F-8E6C-139084C3A49D@gmail.com>
References: <CE62CCFD-0165-4A4F-8E6C-139084C3A49D@gmail.com>
Message-ID: <0ae946b0272de6e1eceefdd4488612c7@mighty.webmail.co.za>

On Sun, 31 Jul 2011 14:22:41 -0400 Alexander Etter <rhettnaxel at gmail.com> wrote

> Hello everyone, is there a page that contains documentation for this mailing
> list? I've seen a few users top post and others advise against it; if there
> isn't a page listing conventions let's create it and if there is what is it's
> URL and how do you suggest users read it?
> Alexander
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

---
tutor-request at python.org
Fri, 29 Jul 2011 19:52:43 +0200    (2 days, 1 hour ago)

Welcome to the Tutor at python.org mailing list! This list is for folks
who want to ask (and/or answer) questions from folks who wish to learn
how to program with Python.  Feel free to ask even the most basic of
questions -- that's what the list is for!

For best results when asking a question on this list: - Try to write
some code to solve your problem - Show the code you have written -
Describe what the code does and what you want it to do - If the code
generates an error, copy and paste the entire error message, including
the traceback, into your email. - Tell us what OS and Python version
you are using.

- Don't ask us to do your homework. - Don't assume we know what you
are talking about. If you are having trouble with a third-party
library, include a link to the library home page.

When replying to a posting: - Use Reply All to reply to the entire
list - Don't top post - put your reply after the text to which you are
replying

For all posts: - Format your email as plain text, not HTML


To post to this list, send your email to:

  tutor at python.org

General information about the mailing list is at:

  http://mail.python.org/mailman/listinfo/tutor

If you ever want to unsubscribe or change your options (eg, switch to
or from digest mode, change your password, etc.), visit your
subscription page at:

  http://mail.python.org/mailman/options/tutor/***************

You can also make such adjustments via email by sending a message to:

  Tutor-request at python.org

with the word `help' in the subject or body (don't include the
quotes), and you will get back a message with instructions.

You must know your password to change your options (including changing
the password, itself) or to unsubscribe.  It is:

***********************

Normally, Mailman will remind you of your python.org mailing list
passwords once every month, although you can disable this if you
prefer.  This reminder will also include instructions on how to
unsubscribe or change your account options.  There is also a button on
your options page that will email your current password to you.


____________________________________________________________
South Africas premier free email service - www.webmail.co.za 

For super low premiums, click here http://www.dialdirect.co.za/?vdn=15828



From abdulhakim.haliru at leproghrammeen.com  Sun Jul 31 22:22:30 2011
From: abdulhakim.haliru at leproghrammeen.com (abdulhakim haliru)
Date: Sun, 31 Jul 2011 20:22:30 +0000
Subject: [Tutor] How do I learn python for web development
In-Reply-To: <mailman.8288.1312088516.1163.tutor@python.org>
References: <mailman.8288.1312088516.1163.tutor@python.org>
Message-ID: <1968144381-1312143754-cardhu_decombobulator_blackberry.rim.net-2065918079-@b18.c19.bise7.blackberry>

Hi guys,

I am really interested in switching from PHP to python but there don't appear to be a book for such.

Can anyone advice me please.

Abdulhakim.
Sent from my BlackBerry wireless device from MTN

-----Original Message-----
From: tutor-request at python.org
Sender: tutor-bounces+abdulhakim.haliru=leproghrammeen.com at python.org
Date: Sun, 31 Jul 2011 07:01:56 
To: <tutor at python.org>
Reply-To: tutor at python.org
Subject: Tutor Digest, Vol 89, Issue 92

Send Tutor mailing list submissions to
	tutor at python.org

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

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

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


Today's Topics:

   1. Re: How to make tkMessage function to have duration
      (Steven D'Aprano)
   2. Re: How to make tkMessage function to have duration (Emeka)
   3. newbie needs pypy setup tips (Tom Roche)
   4. Re: newbie needs pypy setup tips (eire1130 at gmail.com)
   5. Re: Mainloop conflict (Christopher King)
   6. Re: Mainloop conflict (Stefan Behnel)


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

Message: 1
Date: Sat, 30 Jul 2011 21:25:27 +1000
From: Steven D'Aprano <steve at pearwood.info>
To: tutor at python.org
Subject: Re: [Tutor] How to make tkMessage function to have duration
Message-ID: <4E33EA27.50301 at pearwood.info>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

Emeka wrote:
> Hello All,
> 
> Say I have the below(code), .... I would want the message to last say 30
> seconds and afterwards disappear. I won't want the user to be the one to
> enable it to disappear.
> 
> Basically, what I want is to be able to show the user some message , and
> after some seconds, the message goes away

I *hate* it when applications do that. Just as I'm trying to read the 
message, take a screen shot, or whatever, the message disappears. I 
think that's one of the worst things you can do in an application.

If the message isn't important enough to require it to stay visible 
until the user explicitly closes it, then it shouldn't go into a dialog 
in the first place.



-- 
Steven


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

Message: 2
Date: Sat, 30 Jul 2011 16:27:21 +0100
From: Emeka <emekamicro at gmail.com>
To: "Steven D'Aprano" <steve at pearwood.info>
Cc: tutor at python.org
Subject: Re: [Tutor] How to make tkMessage function to have duration
Message-ID:
	<CAOypoo49WRri7EWAoiU96OUs8rPwCincc=teLm4jxKOOa5j6OQ at mail.gmail.com>
Content-Type: text/plain; charset="iso-8859-1"

Steven,,


Thanks!


Emeka

On Sat, Jul 30, 2011 at 12:25 PM, Steven D'Aprano <steve at pearwood.info>wrote:

> Emeka wrote:
>
>> Hello All,
>>
>> Say I have the below(code), .... I would want the message to last say 30
>> seconds and afterwards disappear. I won't want the user to be the one to
>> enable it to disappear.
>>
>> Basically, what I want is to be able to show the user some message , and
>> after some seconds, the message goes away
>>
>
> I *hate* it when applications do that. Just as I'm trying to read the
> message, take a screen shot, or whatever, the message disappears. I think
> that's one of the worst things you can do in an application.
>
> If the message isn't important enough to require it to stay visible until
> the user explicitly closes it, then it shouldn't go into a dialog in the
> first place.
>
>
>
> --
> Steven
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>



-- 
*Satajanus  Nig. Ltd


*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110730/c3697f06/attachment-0001.html>

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

Message: 3
Date: Sat, 30 Jul 2011 17:49:02 -0400
From: Tom Roche <Tom_Roche at pobox.com>
To: tutor at python.org,
Subject: [Tutor] newbie needs pypy setup tips
Message-ID: <877h6zfnht.fsf at pobox.com>
Content-Type: text/plain; charset=us-ascii


I need advice about configuring pypy to run other python code. Why I ask:

I'm running a model implemented in python. Unfortunately a run on "straight" python 2.6.x or 2.7.x requires

- 130 min on my ubuntu laptop (on which working would be more convenient)
- 55 min on a better build machine on which I currently have access

However I have read that this model runs 5x faster under pypy, so I wanna get me that, but I'm finding the pypy docs pretty inscrutable. Nevertheless, I have managed to do

me at it:~$ uname -rv
> 2.6.32-33-generic #70-Ubuntu SMP Thu Jul 7 21:13:52 UTC 2011
me at it:~$ which pypy
> /usr/local/bin/pypy
me at it:~$ ls -al $(which pypy)
> lrwxrwxrwx 1 root root 37 2011-07-30 16:06 /usr/local/bin/pypy -> /opt/pypy-c-jit-1.5.0-alpha0/bin/pypy
me at it:~$ pypy --version
> Python 2.7.1 (b590cf6de419, Apr 30 2011, 02:00:34)
> [PyPy 1.5.0-alpha0 with GCC 4.4.3]

However, when I try to *really* run the @#$%^&! thing, it spews:

me at it:~$ pypy
> debug: WARNING: library path not found, using compiled-in sys.path and sys.prefix will be unset
> 'import site' failed
> Python 2.7.1 (b590cf6de419, Apr 30 2011, 02:00:34)
> [PyPy 1.5.0-alpha0 with GCC 4.4.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> debug: OperationError:
> debug:  operror-type: ImportError
> debug:  operror-value: No module named _pypy_interact

What do I need to do to fix its library path?

TIA, Tom Roche <Tom_Roche at pobox.com>


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

Message: 4
Date: Sat, 30 Jul 2011 22:06:04 +0000
From: eire1130 at gmail.com
To: tutor at python.org,"Tom Roche" <Tom_Roche at pobox.com>
Subject: Re: [Tutor] newbie needs pypy setup tips
Message-ID:
	<836810990-1312063566-cardhu_decombobulator_blackberry.rim.net-18925951- at b1.c28.bise6.blackberry>
	
Content-Type: text/plain

I think, but not 100 percent, that pypy has a list. You might get better traction there if you don't get a good *nswer here.

Although I have a couple questions. Have you profiled in python to look for hotspots?

Have you tried writting portions in c?

What kind of model is it, out of curiousity.
Sent from my Verizon Wireless BlackBerry

-----Original Message-----
From: Tom Roche <Tom_Roche at pobox.com>
Sender: tutor-bounces+eire1130=gmail.com at python.org
Date: Sat, 30 Jul 2011 17:49:02 
To: <tutor at python.org>
Reply-To: tutor at python.org, Tom Roche <Tom_Roche at pobox.com>
Subject: [Tutor] newbie needs pypy setup tips


I need advice about configuring pypy to run other python code. Why I ask:

I'm running a model implemented in python. Unfortunately a run on "straight" python 2.6.x or 2.7.x requires

- 130 min on my ubuntu laptop (on which working would be more convenient)
- 55 min on a better build machine on which I currently have access

However I have read that this model runs 5x faster under pypy, so I wanna get me that, but I'm finding the pypy docs pretty inscrutable. Nevertheless, I have managed to do

me at it:~$ uname -rv
> 2.6.32-33-generic #70-Ubuntu SMP Thu Jul 7 21:13:52 UTC 2011
me at it:~$ which pypy
> /usr/local/bin/pypy
me at it:~$ ls -al $(which pypy)
> lrwxrwxrwx 1 root root 37 2011-07-30 16:06 /usr/local/bin/pypy -> /opt/pypy-c-jit-1.5.0-alpha0/bin/pypy
me at it:~$ pypy --version
> Python 2.7.1 (b590cf6de419, Apr 30 2011, 02:00:34)
> [PyPy 1.5.0-alpha0 with GCC 4.4.3]

However, when I try to *really* run the @#$%^&! thing, it spews:

me at it:~$ pypy
> debug: WARNING: library path not found, using compiled-in sys.path and sys.prefix will be unset
> 'import site' failed
> Python 2.7.1 (b590cf6de419, Apr 30 2011, 02:00:34)
> [PyPy 1.5.0-alpha0 with GCC 4.4.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> debug: OperationError:
> debug:  operror-type: ImportError
> debug:  operror-value: No module named _pypy_interact

What do I need to do to fix its library path?

TIA, Tom Roche <Tom_Roche at pobox.com>
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

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

Message: 5
Date: Sat, 30 Jul 2011 22:30:34 -0400
From: Christopher King <g.nius.ck at gmail.com>
To: python mail list <tutor at python.org>
Subject: Re: [Tutor] Mainloop conflict
Message-ID:
	<CAKBg9Z2eQmoYeBXxUhieCnCmnRWRiHwrEbJ=KBNWRN28T_5r+A at mail.gmail.com>
Content-Type: text/plain; charset="iso-8859-1"

I think I'll go with threading. I've become more familiar with it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110730/9b42e528/attachment-0001.html>

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

Message: 6
Date: Sun, 31 Jul 2011 07:01:41 +0200
From: Stefan Behnel <stefan_ml at behnel.de>
To: tutor at python.org
Subject: Re: [Tutor] Mainloop conflict
Message-ID: <j12njl$3rj$1 at dough.gmane.org>
Content-Type: text/plain; charset=UTF-8; format=flowed

Christopher King, 31.07.2011 04:30:
> I think I'll go with threading. I've become more familiar with it.

That's ok. When used carefully, threads can be pretty helpful to gain 
concurrency in I/O tasks.

But just in case you ever feel like using them for anything else, this is 
worth a read:

http://ptolemy.eecs.berkeley.edu/publications/papers/06/problemwithThreads/

Stefan



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

_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor


End of Tutor Digest, Vol 89, Issue 92
*************************************

From eire1130 at gmail.com  Sun Jul 31 22:27:12 2011
From: eire1130 at gmail.com (eire1130 at gmail.com)
Date: Sun, 31 Jul 2011 20:27:12 +0000
Subject: [Tutor] How do I learn python for web development
In-Reply-To: <1968144381-1312143754-cardhu_decombobulator_blackberry.rim.net-2065918079-@b18.c19.bise7.blackberry>
References: <mailman.8288.1312088516.1163.tutor@python.org><1968144381-1312143754-cardhu_decombobulator_blackberry.rim.net-2065918079-@b18.c19.bise7.blackberry>
Message-ID: <725283150-1312144033-cardhu_decombobulator_blackberry.rim.net-569129859-@b1.c28.bise6.blackberry>

There are several books om django. This is what you are looking for


Sent from my Verizon Wireless BlackBerry

-----Original Message-----
From: "abdulhakim haliru" <abdulhakim.haliru at leproghrammeen.com>
Sender: tutor-bounces+eire1130=gmail.com at python.org
Date: Sun, 31 Jul 2011 20:22:30 
To: <tutor at python.org>
Reply-To: abdulhakim.haliru at leproghrammeen.com
Subject: [Tutor] How do I learn python for web development

Hi guys,

I am really interested in switching from PHP to python but there don't appear to be a book for such.

Can anyone advice me please.

Abdulhakim.
Sent from my BlackBerry wireless device from MTN

-----Original Message-----
From: tutor-request at python.org
Sender: tutor-bounces+abdulhakim.haliru=leproghrammeen.com at python.org
Date: Sun, 31 Jul 2011 07:01:56 
To: <tutor at python.org>
Reply-To: tutor at python.org
Subject: Tutor Digest, Vol 89, Issue 92

Send Tutor mailing list submissions to
	tutor at python.org

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

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

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


Today's Topics:

   1. Re: How to make tkMessage function to have duration
      (Steven D'Aprano)
   2. Re: How to make tkMessage function to have duration (Emeka)
   3. newbie needs pypy setup tips (Tom Roche)
   4. Re: newbie needs pypy setup tips (eire1130 at gmail.com)
   5. Re: Mainloop conflict (Christopher King)
   6. Re: Mainloop conflict (Stefan Behnel)


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

Message: 1
Date: Sat, 30 Jul 2011 21:25:27 +1000
From: Steven D'Aprano <steve at pearwood.info>
To: tutor at python.org
Subject: Re: [Tutor] How to make tkMessage function to have duration
Message-ID: <4E33EA27.50301 at pearwood.info>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

Emeka wrote:
> Hello All,
> 
> Say I have the below(code), .... I would want the message to last say 30
> seconds and afterwards disappear. I won't want the user to be the one to
> enable it to disappear.
> 
> Basically, what I want is to be able to show the user some message , and
> after some seconds, the message goes away

I *hate* it when applications do that. Just as I'm trying to read the 
message, take a screen shot, or whatever, the message disappears. I 
think that's one of the worst things you can do in an application.

If the message isn't important enough to require it to stay visible 
until the user explicitly closes it, then it shouldn't go into a dialog 
in the first place.



-- 
Steven


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

Message: 2
Date: Sat, 30 Jul 2011 16:27:21 +0100
From: Emeka <emekamicro at gmail.com>
To: "Steven D'Aprano" <steve at pearwood.info>
Cc: tutor at python.org
Subject: Re: [Tutor] How to make tkMessage function to have duration
Message-ID:
	<CAOypoo49WRri7EWAoiU96OUs8rPwCincc=teLm4jxKOOa5j6OQ at mail.gmail.com>
Content-Type: text/plain; charset="iso-8859-1"

Steven,,


Thanks!


Emeka

On Sat, Jul 30, 2011 at 12:25 PM, Steven D'Aprano <steve at pearwood.info>wrote:

> Emeka wrote:
>
>> Hello All,
>>
>> Say I have the below(code), .... I would want the message to last say 30
>> seconds and afterwards disappear. I won't want the user to be the one to
>> enable it to disappear.
>>
>> Basically, what I want is to be able to show the user some message , and
>> after some seconds, the message goes away
>>
>
> I *hate* it when applications do that. Just as I'm trying to read the
> message, take a screen shot, or whatever, the message disappears. I think
> that's one of the worst things you can do in an application.
>
> If the message isn't important enough to require it to stay visible until
> the user explicitly closes it, then it shouldn't go into a dialog in the
> first place.
>
>
>
> --
> Steven
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>



-- 
*Satajanus  Nig. Ltd


*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110730/c3697f06/attachment-0001.html>

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

Message: 3
Date: Sat, 30 Jul 2011 17:49:02 -0400
From: Tom Roche <Tom_Roche at pobox.com>
To: tutor at python.org,
Subject: [Tutor] newbie needs pypy setup tips
Message-ID: <877h6zfnht.fsf at pobox.com>
Content-Type: text/plain; charset=us-ascii


I need advice about configuring pypy to run other python code. Why I ask:

I'm running a model implemented in python. Unfortunately a run on "straight" python 2.6.x or 2.7.x requires

- 130 min on my ubuntu laptop (on which working would be more convenient)
- 55 min on a better build machine on which I currently have access

However I have read that this model runs 5x faster under pypy, so I wanna get me that, but I'm finding the pypy docs pretty inscrutable. Nevertheless, I have managed to do

me at it:~$ uname -rv
> 2.6.32-33-generic #70-Ubuntu SMP Thu Jul 7 21:13:52 UTC 2011
me at it:~$ which pypy
> /usr/local/bin/pypy
me at it:~$ ls -al $(which pypy)
> lrwxrwxrwx 1 root root 37 2011-07-30 16:06 /usr/local/bin/pypy -> /opt/pypy-c-jit-1.5.0-alpha0/bin/pypy
me at it:~$ pypy --version
> Python 2.7.1 (b590cf6de419, Apr 30 2011, 02:00:34)
> [PyPy 1.5.0-alpha0 with GCC 4.4.3]

However, when I try to *really* run the @#$%^&! thing, it spews:

me at it:~$ pypy
> debug: WARNING: library path not found, using compiled-in sys.path and sys.prefix will be unset
> 'import site' failed
> Python 2.7.1 (b590cf6de419, Apr 30 2011, 02:00:34)
> [PyPy 1.5.0-alpha0 with GCC 4.4.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> debug: OperationError:
> debug:  operror-type: ImportError
> debug:  operror-value: No module named _pypy_interact

What do I need to do to fix its library path?

TIA, Tom Roche <Tom_Roche at pobox.com>


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

Message: 4
Date: Sat, 30 Jul 2011 22:06:04 +0000
From: eire1130 at gmail.com
To: tutor at python.org,"Tom Roche" <Tom_Roche at pobox.com>
Subject: Re: [Tutor] newbie needs pypy setup tips
Message-ID:
	<836810990-1312063566-cardhu_decombobulator_blackberry.rim.net-18925951- at b1.c28.bise6.blackberry>
	
Content-Type: text/plain

I think, but not 100 percent, that pypy has a list. You might get better traction there if you don't get a good *nswer here.

Although I have a couple questions. Have you profiled in python to look for hotspots?

Have you tried writting portions in c?

What kind of model is it, out of curiousity.
Sent from my Verizon Wireless BlackBerry

-----Original Message-----
From: Tom Roche <Tom_Roche at pobox.com>
Sender: tutor-bounces+eire1130=gmail.com at python.org
Date: Sat, 30 Jul 2011 17:49:02 
To: <tutor at python.org>
Reply-To: tutor at python.org, Tom Roche <Tom_Roche at pobox.com>
Subject: [Tutor] newbie needs pypy setup tips


I need advice about configuring pypy to run other python code. Why I ask:

I'm running a model implemented in python. Unfortunately a run on "straight" python 2.6.x or 2.7.x requires

- 130 min on my ubuntu laptop (on which working would be more convenient)
- 55 min on a better build machine on which I currently have access

However I have read that this model runs 5x faster under pypy, so I wanna get me that, but I'm finding the pypy docs pretty inscrutable. Nevertheless, I have managed to do

me at it:~$ uname -rv
> 2.6.32-33-generic #70-Ubuntu SMP Thu Jul 7 21:13:52 UTC 2011
me at it:~$ which pypy
> /usr/local/bin/pypy
me at it:~$ ls -al $(which pypy)
> lrwxrwxrwx 1 root root 37 2011-07-30 16:06 /usr/local/bin/pypy -> /opt/pypy-c-jit-1.5.0-alpha0/bin/pypy
me at it:~$ pypy --version
> Python 2.7.1 (b590cf6de419, Apr 30 2011, 02:00:34)
> [PyPy 1.5.0-alpha0 with GCC 4.4.3]

However, when I try to *really* run the @#$%^&! thing, it spews:

me at it:~$ pypy
> debug: WARNING: library path not found, using compiled-in sys.path and sys.prefix will be unset
> 'import site' failed
> Python 2.7.1 (b590cf6de419, Apr 30 2011, 02:00:34)
> [PyPy 1.5.0-alpha0 with GCC 4.4.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> debug: OperationError:
> debug:  operror-type: ImportError
> debug:  operror-value: No module named _pypy_interact

What do I need to do to fix its library path?

TIA, Tom Roche <Tom_Roche at pobox.com>
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

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

Message: 5
Date: Sat, 30 Jul 2011 22:30:34 -0400
From: Christopher King <g.nius.ck at gmail.com>
To: python mail list <tutor at python.org>
Subject: Re: [Tutor] Mainloop conflict
Message-ID:
	<CAKBg9Z2eQmoYeBXxUhieCnCmnRWRiHwrEbJ=KBNWRN28T_5r+A at mail.gmail.com>
Content-Type: text/plain; charset="iso-8859-1"

I think I'll go with threading. I've become more familiar with it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110730/9b42e528/attachment-0001.html>

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

Message: 6
Date: Sun, 31 Jul 2011 07:01:41 +0200
From: Stefan Behnel <stefan_ml at behnel.de>
To: tutor at python.org
Subject: Re: [Tutor] Mainloop conflict
Message-ID: <j12njl$3rj$1 at dough.gmane.org>
Content-Type: text/plain; charset=UTF-8; format=flowed

Christopher King, 31.07.2011 04:30:
> I think I'll go with threading. I've become more familiar with it.

That's ok. When used carefully, threads can be pretty helpful to gain 
concurrency in I/O tasks.

But just in case you ever feel like using them for anything else, this is 
worth a read:

http://ptolemy.eecs.berkeley.edu/publications/papers/06/problemwithThreads/

Stefan



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

_______________________________________________
Tutor maillist  -  Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor


End of Tutor Digest, Vol 89, Issue 92
*************************************
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

From james at jamesthornton.com  Sun Jul 31 22:42:47 2011
From: james at jamesthornton.com (James Thornton)
Date: Sun, 31 Jul 2011 15:42:47 -0500
Subject: [Tutor] How do I learn python for web development
In-Reply-To: <1968144381-1312143754-cardhu_decombobulator_blackberry.rim.net-2065918079-@b18.c19.bise7.blackberry>
References: <mailman.8288.1312088516.1163.tutor@python.org>
	<1968144381-1312143754-cardhu_decombobulator_blackberry.rim.net-2065918079-@b18.c19.bise7.blackberry>
Message-ID: <CANva_A3d0TT4gOmFpLNUK+6Gm3atwE9n2CJwbhuL9H-PzD_OSw@mail.gmail.com>

On Sun, Jul 31, 2011 at 3:22 PM, abdulhakim haliru
<abdulhakim.haliru at leproghrammeen.com> wrote:
> Hi guys,
>
> I am really interested in switching from PHP to python but there don't appear to be a book for such.

Hi -

Start off by becoming familiar with Python -- here are some good
online tutorials, in order from introductory to more advanced:

http://www.quora.com/How-can-I-learn-to-program-in-Python/answer/James-Thornton

And then do the Flask Quickstart and Tutorial (http://flask.pocoo.org/docs/).

Flask is an elegantly-designed Python Web microframework so it's great
for beginners because you don't have too spend much time learning it
-- it let's you program in Python rather than writing to the
framework.

Ironically, this also makes Flask an ideal choice for advanced Python
programmers because it gives you flexibility rather than always
wondering "will the framework allow me to easily do...?"

- James

-- 
Bulbflow: A Python framework for graph databases (http://bulbflow.com)

ow: A Python framework for graph databases (http://bulbflow.com)