Re: [Tutor] Is there an easy way to center the root window (Tkinter) within the display?

2014-11-27 Thread boB Stepp
On Nov 27, 2014 1:27 PM, "Dave Angel"  wrote:
>
> On 11/27/2014 11:39 AM, boB Stepp wrote:
>>
>> On Thu, Nov 27, 2014 at 9:58 AM, Steven D'Aprano 
wrote:
>
>

>
> You say you're using some 3rd party package to do the heavy lifting. But
you also say there could be as many as 1000 servers involved.  So the scale
of things is quite large.  If it's not impertinent, I'd ask a number of
questions about both your own development environment and that of the 3rd
party product that runs on all those servers.
>
I'm away from my PC for the rest of the day, but I must have left an
incorrect impression of the scale involved & the size of our organization.
There are a total of 9 people distributed amongst 6 centers. There are only
2 servers that distribute the planning software to thin clients. There are
other Windows servers involved with post-planning tasks, but I don't do
anything programming-wise other than FTPing PDF docs from the planning
system to a specific network folder.

I hope this clarifies my particular situation. And I apologize for leaving
such an erroneous impression!!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there an easy way to center the root window (Tkinter) within the display?

2014-11-27 Thread boB Stepp
On Thu, Nov 27, 2014 at 9:58 AM, Steven D'Aprano  wrote:
> On Wed, Nov 26, 2014 at 12:25:23PM -0600, boB Stepp wrote:
>
>> As I am the only person in our
>> group with any programming knowledge (weak though it is), this means I
>> usually wind up trying to solve issues as they arise. These client
>> machines are dedicated to a single purpose: radiation therapy
>> treatment planning.
>
> No offense intended Bob, but this scares me. I know you're trying your
> best, but "weak programming knowledge" and "radiation therapy" is not a
> healthy combination.

Believe me, I think about this constantly!

The planning software we use is FDA approved. My add-on
programs/scripts generally automate repetitive tasks to save the
planner much by hand work. The other types of plans take the results
of the plan and create a visual display to flag things we might want
to look at more closely. Or send printouts of the plan in pdf format
from the Solaris 10 planning environment to where they need to wind up
on our Window's based record and verify software server. Or similar
things that do not alter the plan itself. That is the important point:
They do not alter the treatment plan.

When I have something ready to use we check everything by hand for at
least a couple of weeks. Medical physics evaluates my software as
well. For anything remotely critical that might influence the
evaluation of a plan, we do monthly QA to verify the constancy of the
underlying data and calculations in case something we are potentially
unaware of has changed. I constantly exhort my colleagues to use my
scripts with a critical eye and report immediately anything, however,
slight that is unusual and unexpected. I test and I test and I worry
and I worry... But so far these efforts have not only saved time, but
caught and prevented errors that might otherwise would have needed to
be caught farther down in the review process. Now they get caught at
the planning level and never even come close to getting further. The
scripts generally either prevent the dosimetrist from forgetting to do
something, make him aware of something he should examine more closely
that he might not otherwise catch, and reduce the routine grunt-work
burden.

> I trust you are aware of the Therac-25 disaster?

I have not looked at that particular one (But will now.), but can cite
many more, especially those very recent. The New York Times not long
ago ran a series of articles about this topic.


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


Re: [Tutor] Question about why a list variable is apparently global.

2014-11-27 Thread boB Stepp
On Thu, Nov 27, 2014 at 9:33 AM, Steven D'Aprano  wrote:
> On Thu, Nov 27, 2014 at 09:00:48AM -0600, boB Stepp wrote:

[...]

> But there is a subtlety that you may not expect:
>
> py> class Tricky:
> ... print(x)
> ... x = "inner"
> ... print(x)
> ...
> outer
> inner

Actually, this is what you had me primed to expect. However, ...

> So although classes introduce a new scope, they are not like functions.
> In a function, the above would lead to an error (try it and see).

>>> def tricky_func():
  print(x)
  x = "inner"
  print(x)

>>> tricky_func()
Traceback (most recent call last):
File "", line 1, in 
   tricky_func()
File "", line 2, in tricky_func
print(x)
UnboundLocalError: local variable 'x' referenced before assignment

This surprised me! So I did:

>>> def tricky_func2():
  y = x
  print(x)

>>> tricky_func2()
outer

So why does not print(x) see the global x and instead looks for the
local x? And why is this different between classes and functions?

> * Every module is a separate scope.
>
> * `def` and `class` introduce new scopes.
>
> * Other indented blocks (for, while, if etc.) do not.

Alan's reference to indentation level had me trying to prove the
opposite--unsuccessfully.

> * But lambda expressions do.
>
> * Generator expressions have their own scope too.
>
> * In Python 3 only, so do list comprehensions (and dict and set
>   comprehensions). But not in Python 2.

This is good to know this difference as at work I'm in Python 2.4.4
and at home Python 3.4

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


Re: [Tutor] Question about why a list variable is apparently global.

2014-11-27 Thread boB Stepp
On Thu, Nov 27, 2014 at 4:56 AM, Steven D'Aprano  wrote:
> On Wed, Nov 26, 2014 at 10:18:55PM -0600, boB Stepp wrote:
>
>> So any variables lower in the program are accessible to those above it?
>
> No, that can't be the explanation. Think of this:
>
> b = a + 1
> a = 2
>
> That will fail because when the "b = a + 1" line is executed, a doesn't
> exist yet so there is no way to get a value for it.

This was my original understanding! I see now that I totally
misunderstood what you said in your earlier post:

"No, they also have access to globals and built-ins. You define the list
l at the top level of your module. That makes it a global, so the
printLavel() function can see it."

I did not understand what you meant by "top level of your module". As
I mentioned just moments ago in response to Alan's post, I looked at
Lutz's discussion of scope and I believe I now understand what you
originally meant. OTOH, I see that there is much more to scope/name
spaces than I originally thought, so I don't claim to fully grasp
Lutz's discussion yet.

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


Re: [Tutor] Question about why a list variable is apparently global.

2014-11-27 Thread boB Stepp
On Thu, Nov 27, 2014 at 4:51 AM, Alan Gauld  wrote:
> On 27/11/14 04:18, boB Stepp wrote:

[...]

>> So any variables lower in the program are accessible to those above it?
>
>
> No.
> Its not whether they are defined above or below each other its the level of
> indentation. Both f and g are defined at the outer level of the module. They
> are therefore global(within that module) and can each see the other. Steven
> could just as well have written:
>
> def f(): return "Hello!"
>
> def g(): return f()

Level of indentation is the key? Can you give me an example, not
involving functions, where a variable is defined at an "inner" level
of indentation, but is not accessible at the outermost level of
indentation? I tried to construct such an example myself, but was
unsuccessful.

[...]

>> day today. Despite having Grayson's book on Tkinter, it has been hard
>> going for me.
>
>
> Grayson's book is hard going and is very old now so some things have
> improved and changed. In particular you now have access to Tix and ttf
> on newer versions of Python. But since you are still using 2.4 that probably
> doesn't affect you! :-)

That is the main reason I got the book, because of the version of
Python I am forced to use at work.

> However, if you have access to it, you should consider getting Mark Lutz's
> book Programming Python (4th ed). It's a massive 1600 pages
> of which 400+ are about Tkinter programming (more than Grayson!)

I actually purchased that book and his 4th edition of Learning Python
when I first started getting interested in Python a couple of years
ago. I will check out his Tkinter coverage and see if it is easier
going.

> And there is the bonus of 1200 other pages of detailed info about
> the OS, Networking, databases etc. Again its a bit dry but full
> of information.

I looked at his discussion of scope last night in the latter book. I
still don't think I am fully getting it yet. But I will continue to
persevere.

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


Re: [Tutor] Question about why a list variable is apparently global.

2014-11-26 Thread boB Stepp
On Wed, Nov 26, 2014 at 6:20 PM, Steven D'Aprano  wrote:
> On Wed, Nov 26, 2014 at 05:23:40PM -0600, boB Stepp wrote:
[...]
>> First question: How can the printLabel() function see the list
>> variable, l, defined outside of this function? I thought that
>> functions only had access to variables local to the function and
>> whatever else is passed to it during the function call.
>
> No, they also have access to globals and built-ins. You define the list
> l at the top level of your module. That makes it a global, so the
> printLavel() function can see it.
>
> Note that this principle is critical to Python, otherwise functions
> couldn't call each other, or even built-ins! If you have two functions:
>
> def f(): return g()
>
> def g(): return "Hello!"
>
> "g" is a global "variable" and f() can see it, otherwise it couldn't
> call it.

So any variables lower in the program are accessible to those above it?

> I put variable in scare-quotes because it's actually more of a
> pseudo-constant, a constant by convention, since it is very unusual to
> change things you define as a function. To be more precise, the *name*
> "g" which refers to the function exists in the module's global scope. As
> a short-cut, we call such names "global variables", even if they never
> vary.
>
> You only need to declare a global variable inside a function if you are
> re-assigning a value to it. Hence:
>
> a = 1
> b = 2
> def test():
> global b
> b = b + a

So even though test() has access to a and b, it won't change b when
called unless b is declared global inside the function?

> [...]
>> Third: I am always open to stylistic comments and how to be more pythonic!
>
> Fix your variable names!

I knew I would be dinged on this, but I wanted to get my main question
(about global/local) out there before I left work. The code I posted
has been changed numerous times as I dickered around with Tkinter all
day today. Despite having Grayson's book on Tkinter, it has been hard
going for me. I PROMISE crummy variable names will not make it into
the final code. Once I get the logic working and the appearance like I
want it and more importantly understand what is going on, I am going
to rewrite everything from scratch.

> You have a variable called "buttonNumber" which holds a LIST, not a
> number. Confusing!

In an earlier version buttonNumber was a number.

> You have another variable called "1", or is that "I", no sorry it's "l".
> Notice that depending on the font you use, 1 I and l can look almost
> exactly the same. That's a bad thing. Also, the name "l" doesn't mean
> anything, it doesn't tell you the purpose of the variable.

Originally l (ell) was a physical list written out. I am not used to
the way python iterates, so I was playing around with this feature in
different ways until I was sure I saw what it was doing, especially
with the 2-tuples as list elements. Now that I see how this seems to
work, I am planning on having a configuration file of some sort that
will populate this list. Where I work we have multiple centers and
people will have different versions of this list. So I intend to
separate this out and each center can have their own custom
radiobutton list to choose from.

> Then there is another variable called "var". That's nice, we already
> know it's a variable, but what role does it play in your program? Try to
> find a more descriptive name.

I have been switching back and forth between different python books.
The name var came from Grayson's generic examples. I also got caught
out by "str" as a variable name on an earlier question. That
particular book is especially bad in variable names. But again,
instead of renaming other people's code snippets, I tend to use them
as is while I am experimenting with what their snippets are trying to
do.I suppose I should be more diligent even during my "play" time in
case I wind up copying and pasting portions of the play code into code
I intend to keep. I imagine I might not remember to change all of the
awful names into good ones.

Anyway thanks for your insights!

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


[Tutor] Question about why a list variable is apparently global.

2014-11-26 Thread boB Stepp
Python 2.4.4
Solaris 10

#!/usr/bin/env python

from Tkinter import *

def printLabel():
print "Button number ", var.get(), " was pressed."
print "You selected this option:", l[var.get() - 1][0]

root = Tk()
root.title("ROI List Creator")
root.geometry(newGeometry='225x230+900+300')
root.tk_setPalette(background='gray')

buttonNumber = []
l = [("Brain_Partial", 1), ("Brain_Whole", 2),
("Head & Neck", 3), ("Chest", 4), ("Breast_Whole", 5),
("Breast_Partial", 6), ("Abdomen", 7), ("Pelvis", 8),
("Prostate", 9)]
var = IntVar()
for text, value in l:
buttonNumber.append(Radiobutton(root, text = text, value = value,
command=printLabel, variable = var).pack(anchor=W))
var.set(5)
print "The button's value is: ", var.get()
root.update()
print "The geometry info is: ", root.winfo_geometry()
print "The screen width is: ", root.winfo_screenwidth()
print "The screen height is: ", root.winfo_screenheight()
root.mainloop()

First, I continue to "Easter Egg Hunt" in the sweet land of Python,
and now Tkinter. So what I actually know is quite a hodgepodge at this
time.

The function above, printLabel(), will eventually read a file of names
anatomical structures based upon the user's radiobutton selection and
populate those names into a ROI List in our planning software. But for
now I am mostly focused on designing the small radiobutton window and
getting it to do what I expect. I am totally new to Tkinter, but it
seems much more manageable than what our planning software provides
for scripting GUIs.

First question: How can the printLabel() function see the list
variable, l, defined outside of this function? I thought that
functions only had access to variables local to the function and
whatever else is passed to it during the function call.

Second: Will the statements near the end that return the display
screen's width and height be a reliable way of determining the user's
actual monitor settings? My intent is to use this information to
appropriately scale and position windows; not only in this particular
simple window, but in others to come which will potentially be large
and complex. I have tested this on two different sized monitors where
I work and so far it has given the correct results.

Third: I am always open to stylistic comments and how to be more pythonic!

Fourth: And perhaps this should go into a new thread, I am not sure I
understand the full intent and use of Tkinter's Variable class. Any
clarification on this would be welcome as well.

Thanks in advance!

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


Re: [Tutor] How to change the color of the title bar of the root window in Tkinter?

2014-11-26 Thread boB Stepp
On Wed, Nov 26, 2014 at 11:58 AM, Alan Gauld  wrote:
> On 26/11/14 17:39, boB Stepp wrote:
>
[...]
>> The application I am attempting to write will show up in the
>> foreground of our planning software. This planning software has its
>> own color scheme, which all of us are quite used to.
>
>
> Seriously? It colours its own title bars? That's really poor.
> Unless you test all employees for colour blindness first and
> don't employ those blind to your colour scheme?
> And that's probably illegal now in most western countries!

Color-blind users would not be able to be hired to do this work.
Having normal color vision is a job requirement. Of course, the title
bar colors are truly immaterial, but the colors of the isodose lines
that tell the user what dose different areas of the treatment area are
getting are critical. Contoured structures, both targets of the
radiation and organs that must be spared are all color coded. However,
my lack of skill and ignorance (as usual) is the problem...

Thankfully, Alan, you got me to thinking. And exploring. On our
systems it is difficult to know what is coming from the OS,
Solaris-10, and what is coming from the planning software. I had never
used Solaris prior to getting my current position and the last time I
had dabbled in Unix there were no windows-based interfaces, at least
not in the academic environment I was in then.

So I went into the common desktop environment without the planning
system running and verified that the planning system is in fact using
that color scheme for its windows. Which got me to wondering why the
trivial test window I created was not matching. It turns out that the
window was not getting focus unless the mouse was over the test
window, which resulted in in being totally gray except for the radio
button selected. My bad!

I have been playing with Tkinter on a Windows PC and then copying the
code over to the nearby Solaris box to see how it looks. I did not
have any need (yet) to actually click on anything, I was just looking
for the overall appearance of the window and its subelements.

But as usual you were very helpful and got my thinking (such as it is)
going in the proper direction!

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


Re: [Tutor] Is there an easy way to center the root window (Tkinter) within the display?

2014-11-26 Thread boB Stepp
On Wed, Nov 26, 2014 at 11:50 AM, Alan Gauld  wrote:
> On 26/11/14 17:44, boB Stepp wrote:
>
[...]
> So they can't read email, write reports, browse web sites?
> And what if the OS or sysadmin is also trying to catch their eye - maybe
> because the server is going down and they have 30 secs to save their work?

Actually, they cannot do any of these things except save their work!
There is no sysadmin. Our IS department is totally Windows focused and
does not know how to help us with Solaris 10-based stuff. If we have
problems we either figure it out ourselves or call the owners of the
planning software for remote help. As I am the only person in our
group with any programming knowledge (weak though it is), this means I
usually wind up trying to solve issues as they arise. These client
machines are dedicated to a single purpose: radiation therapy
treatment planning. They either cannot or should not be doing anything
else

> Being a 'good guy' in a multi tasking/multi user world is tough :-)

If a user initiates one of my programs/scripts then the user is
focused on that task to exclusion of anything else, since that
comprises the next step in his planning process workflow.

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


Re: [Tutor] Is there an easy way to center the root window (Tkinter) within the display?

2014-11-26 Thread boB Stepp
On Wed, Nov 26, 2014 at 11:23 AM, Alan Gauld  wrote:
> On 26/11/14 16:46, boB Stepp wrote:
>
>> I can accomplish this by getting the screen height and width and
>> calculating pixel coordinates. But so far I have not found something
>> equivalent to anchor = 'CENTER' that can be applied to the root
>> window. Does such an easy attribute, method, or whatever exist in
>> Tkinter?
>
>
> I'm not aware of one.
> But forcing a window to be centre of the display is usually
> a bad idea - and very annoyying to the user, especially if they have
> explicitly set their preferences for where new windows should appear.

Thanks for bringing this to my attention. I do not believe it applies
to my current situation, but I could see that I need to keep it in
mind for most other things I might do.

In the current scenario, users of our planning system will initiate a
planning system script (proprietary language) that will call my python
program. The user cannot proceed further until my program completes,
which requires user interaction. So I do want it to be front and
center.

I will just have to do this the hard way then, which actually isn't
too hard ~(:>))


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


Re: [Tutor] How to change the color of the title bar of the root window in Tkinter?

2014-11-26 Thread boB Stepp
On Wed, Nov 26, 2014 at 11:25 AM, Alan Gauld  wrote:
> On 26/11/14 16:48, boB Stepp wrote:
>>
>> Python 2.4.4
>> Solaris 10
>
>
> I can't find anything on this and I suspect that's because
> title bar colour is generally part of the user's preferred
> colour scheme. Even in Windoze the title bar colour is part
> of the users preferences. Colour-blind users don't like
> apps that mess with what they can read.

The application I am attempting to write will show up in the
foreground of our planning software. This planning software has its
own color scheme, which all of us are quite used to. As you might
guess, the Tkinter-produced windows do not match this scheme, not
anything close, and I am trying to discover ways to tweak my windows
to agree better with the planning software's display aesthetics.


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


[Tutor] How to change the color of the title bar of the root window in Tkinter?

2014-11-26 Thread boB Stepp
Python 2.4.4
Solaris 10

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


[Tutor] Is there an easy way to center the root window (Tkinter) within the display?

2014-11-26 Thread boB Stepp
Python 2.4.4
Solaris 10

I can accomplish this by getting the screen height and width and
calculating pixel coordinates. But so far I have not found something
equivalent to anchor = 'CENTER' that can be applied to the root
window. Does such an easy attribute, method, or whatever exist in
Tkinter?

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


Re: [Tutor] "Philosophical" question about string slicing from end of a string

2014-11-24 Thread boB Stepp
On Mon, Nov 24, 2014 at 1:06 PM, boB Stepp  wrote:
> On Mon, Nov 24, 2014 at 12:57 PM, Zachary Ware
>  wrote:
> [...]
>>
>> Have I clarified or muddied it for you? :)
>
> Clarified, I believe, if my following statements are correct: I did
> not consider that the behavior was symmetric with positive indices.
> So, index 0 is the "center" relative to which positive and negative
> indices create identical behaviors.
>
Hmm. There is a flaw in my observed "symmetry" in that str[0:3] and
str[-3:0] do not behave the same as the latter returns an empty
string.

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


Re: [Tutor] "Philosophical" question about string slicing from end of a string

2014-11-24 Thread boB Stepp
On Mon, Nov 24, 2014 at 12:57 PM, Zachary Ware
 wrote:
[...]
>
> Have I clarified or muddied it for you? :)

Clarified, I believe, if my following statements are correct: I did
not consider that the behavior was symmetric with positive indices.
So, index 0 is the "center" relative to which positive and negative
indices create identical behaviors.

Thanks!

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


[Tutor] "Philosophical" question about string slicing from end of a string

2014-11-24 Thread boB Stepp
Python 2.7.8
Win7Pro

>>> str = "0123456789"
>>> str[-1]
'9'
>>> str[-3:-1]
'78'
>>> str[-3:]
'789'

I understand that the above is "the way it is" in Python, but I am
puzzled why the designers did not choose that str[-3:-1] returns
'789', especially since str[-1] returns '9'. What is the reason for
choosing Python's actual behavior?

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


Re: [Tutor] How to store and use passwords?

2014-11-18 Thread boB Stepp
On Tue, Nov 18, 2014 at 9:47 AM, Alan Gauld  wrote:
[...]
> You can roll your own password system using the crypt module.
> Get each user to create a password (or give them a default) and
> encrypt it with crypt. Store the result and when they log in
> compare the encrypted password with the stored one.
>
> It may not have all the security features of the passlib
> solution but its a lot better than nothing and will deter
> most crackers long enough for them to get bored and move on.

I see that the crypt module is available for both python versions I
have access to.

> The downside is that you need to build a password management
> module/workflow/UI into your code to allow changes/resets etc.

Another opportunity for furthering my education!

Thanks, Alan!

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


[Tutor] How to store and use passwords?

2014-11-18 Thread boB Stepp
OS: Solaris 10. Python: 2.4.4 on the computer I will be doing my
development work. 2.6.4 on the production environment.

I am working on my first python program at work to automate a set of
tasks that allows for the results of a radiotherapy plan to be
compared to a set of constraints that the plan should meet. The end
result will be a report window where items that meet the constraints
are flagged green, those requiring physician comment yellow, etc. The
form will require two forms of physician approval: one for the overall
document and then a line item approval with comments for those items
that are not "green".

I am still trying to figure out the design while my users merrily keep
changing their requirements. This has led me to investigating the
electronic sign offs of the end product. This would seem to require
(in my mind) a password protected electronic signature for each
physician. I have done some cursory searching on this topic, which led
me to the concept of hashing passwords for storage. I just read
http://www.cyberciti.biz/python-tutorials/securely-hash-passwords-in-python/
which seemed informative, but suggests the use of the module passlib.
Unfortunately, I am not allowed to install anything on the production
environment, nor can anyone else. The physicians do not seem to care
if I password protect their electronic sign offs or not. All of this
information is contained on a subset of our private intranet that
"supposedly" is protected from outside (of our organization) access,
though I am fairly confident that with what little I know I could gain
access from my home. If I can, then I am sure that someone
knowledgeable and skilled would be able to do the same.

Suggestions?

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


Re: [Tutor] Is there a convenient table of Python 3.4 exceptions?

2014-10-24 Thread boB Stepp
On Thu, Oct 23, 2014 at 11:04 PM, Ben Finney  wrote:
> boB Stepp  writes:
>
[...]
>
>> I have so far been unable to find a list of these class/subclass
>> names.
>
> The standard library documentation's chapter on exceptions
> https://docs.python.org/3/library/exceptions.html> shows
> https://docs.python.org/3/library/exceptions.html#exception-hierarchy>.
>

As with Danny, thanks Ben. This is what I was trying to find

[...]
>
> More importantly, though, you should consider *why* you're attempting to
> catch a lot of exception classes. Will you be meaningfully handling
> every one of those situations? That's rather doubtful.
>
> Instead, you should consider which exceptional states your code can
> meaningfully handle, discover what excpetion classes are raised for
> those few situations, and catch *only* those classes.
>

In the programs I have been dabbling in at work, I am often
"surprised" by the situations my users stumble into that I did not
have sufficient imagination to consider up front. And in line with
your statements I have often wondered if I had done enough error
checking, or whether in some instances I was doing too much. Trying to
imagine what the user might do is often a difficult exercise,
especially as my programs have been becoming more lengthy and complex.
I suppose this gets easier with more knowledge and experience?

> Any other exception that gets raised isn't something you can do anything
> useful with, so it should propagate back up to higher levels, either to
> be handled or to exit with a useful error message.
>
As a user of software I have often wished that the error messages
generated were understandable and help me to avoid the condition which
triggered that message in the future.


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


Re: [Tutor] Is there a convenient table of Python 3.4 exceptions?

2014-10-24 Thread boB Stepp
On Thu, Oct 23, 2014 at 10:57 PM, Danny Yoo  wrote:
>
> > I have so far been unable to find a list of these class/subclass names. Of
> > course I can force an error to occur in the interpreter and see what comes
> > up for each type of error I wish to catch. Is there such a table or list?
> >
>
> Hi Bob,
>
> You can find the ones used in the Standard Library here:
>
> https://docs.python.org/3.4/library/exceptions.html
>
Thanks, Danny. That is exactly what I was looking for. Not being
familiar with exception-related vocabulary yet, I was not typing in
the search strings to get me what I wanted. I wound up in "The Python
Language Reference", which is where the quote I gave came from.
Apparently my answers were in the Standard Library Reference. Sigh.

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


[Tutor] Is there a convenient table of Python 3.4 exceptions?

2014-10-23 Thread boB Stepp
I am reading a brief intro to exception handling in Mark Summerfield's
"Programming in Python 3, 2nd ed." He gives the basic syntax as:

try:
try_suite
except exception1 as variable1:
exception_suite1
...
except exceptionN as variableN:
exception_suiteN

My current understanding is that exception1, ... , exceptionN should match
one of Python's exception classes or subclasses in order to perform a match
and execute the corresponding exception suite.

I found this in the docs:

Exceptions are identified by class instances. The except clause is selected
depending on the class of the instance: it must reference the class of the
instance or a base class thereof. The instance can be received by the
handler and can carry additional information about the exceptional
condition.

Note Exception messages are not part of the Python API. Their contents may
change from one version of Python to the next without warning and should
not be relied on by code which will run under multiple versions of the
interpreter.

​I have so far been unable to find a list of these class/subclass names. Of
course I can force an error to occur in the interpreter and see what comes
up for each type of error I wish to catch. Is there such a table or list?​

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


Re: [Tutor] Installing both Python 2.7 and Python 3.4 on Windows 7 Pro 64-bit: Install Python 2.7 FIRST!

2014-10-10 Thread boB Stepp
On Sat, Oct 11, 2014 at 12:24 AM, boB Stepp  wrote:
> On Fri, Oct 10, 2014 at 11:54 PM, Zachary Ware
>  wrote:
>> On Fri, Oct 10, 2014 at 11:34 PM, boB Stepp  wrote:
>>> I can live with 2.7.8 being the default Python, but if I wanted to
>>> make 3.4.2 the default, how would I go about doing it?
>>
>> Check the output of "ftype Python.File", it should be:
>>
>> C:\>ftype Python.File
>> Python.File="C:\Windows\py.exe" "%1" %*
>>
>
> This checked out sat.
>
>> If it's not, make it so :).  Then configure the Python Launcher
>> (py.exe) as described here:
>> https://docs.python.org/3/using/windows.html#customization
>>
>> (You'll probably want your py.ini to look like this:
>>
>> [defaults]
>> python=3
>>
> Cannot locate either of the mentioned py.ini files. I did a search for
> these on my PC and came up empty. I am going to try to create my own
> py.ini file and place it in C:\WINDOWS and see what happens.
>
This did the trick! Many thanks, Zach!


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


Re: [Tutor] Installing both Python 2.7 and Python 3.4 on Windows 7 Pro 64-bit: Install Python 2.7 FIRST!

2014-10-10 Thread boB Stepp
On Fri, Oct 10, 2014 at 11:54 PM, Zachary Ware
 wrote:
> On Fri, Oct 10, 2014 at 11:34 PM, boB Stepp  wrote:
>> I can live with 2.7.8 being the default Python, but if I wanted to
>> make 3.4.2 the default, how would I go about doing it?
>
> Check the output of "ftype Python.File", it should be:
>
> C:\>ftype Python.File
> Python.File="C:\Windows\py.exe" "%1" %*
>

This checked out sat.

> If it's not, make it so :).  Then configure the Python Launcher
> (py.exe) as described here:
> https://docs.python.org/3/using/windows.html#customization
>
> (You'll probably want your py.ini to look like this:
>
> [defaults]
> python=3
>
Cannot locate either of the mentioned py.ini files. I did a search for
these on my PC and came up empty. I am going to try to create my own
py.ini file and place it in C:\WINDOWS and see what happens.


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


Re: [Tutor] Installing both Python 2.7 and Python 3.4 on Windows 7 Pro 64-bit: Install Python 2.7 FIRST!

2014-10-10 Thread boB Stepp
On Fri, Oct 10, 2014 at 7:43 AM, boB Stepp  wrote:
> On Fri, Oct 10, 2014 at 2:05 AM, Wolfgang Maier
>  wrote:
>> On 10/10/2014 05:57 AM, boB Stepp wrote:
[...]
>>
>> It would help if you could share details about how you tried to run the
>> Python 3 program (command line call, double-click, Python launcher for
>> Windows, ..).
>>
> Initially, I ran the program in question by double-clicking on its
> icon, which was my normal way of running it. This is when I realized I
> had a problem. The program would run without error, but give erroneous
> print and input statement results. I next put Python 3 into my path
> variable, but the same error persisted. From the command line I found
> that if I ran it normally (With Python 3 still in the path like it was
> on my previous 3.4.1 installation.), meaning
>
> python program_name.py
>
> it behaved the same way as double-clicking on the icon. However, if I ran it 
> as
>
> py -3 program_name.py
>
> then all was well.
>
> Apparently Python 2.7.8 became the system default installation if I
> installed it last, but after uninstalling both and installing Python
> 3.4.2 last, it became the default. Or, at least when double-clicked on
> it ran normally.
>
> I have since added shebang lines to my programs specifying Python 3.
>
> I hope I have not forgotten any relevant details!
>
Apparently I must have forgotten relevant details because I have
concluded tonight that I have not solved anything. Despite thinking
that I had made Python 3.4.2 my default Python, I am now certain that
Python 2.7.8 is, in fact, my current default Python. So switching the
order of installation did not work and whatever I did last night in my
presumably sleepy or lame state was not what I thought I was doing. If
I double-click on a file or icon to run a program, it runs under
Python 2.7.8. If I run it from the command line with py
program_name.py, then it runs under Python 2.7.8. This is with shebang
lines removed from all programs.

So I apologize for what I wrote earlier.

I can live with 2.7.8 being the default Python, but if I wanted to
make 3.4.2 the default, how would I go about doing it?

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


Re: [Tutor] Installing both Python 2.7 and Python 3.4 on Windows 7 Pro 64-bit: Install Python 2.7 FIRST!

2014-10-10 Thread boB Stepp
On Fri, Oct 10, 2014 at 2:05 AM, Wolfgang Maier
 wrote:
> On 10/10/2014 05:57 AM, boB Stepp wrote:
>>
>> I am hoping to save other people the grief I just worked through. I
>> wanted to run both Python 2 and 3 on my windows PC, and, after
>> googling this topic found that with Python 3.3 or later one could
>> easily do both. So I merrily installed Python 3.4.2 first and then
>> Python 2.7.8. A Python 3 program that had been working fine suddenly
>> stopped working. After working down to a test portion of code that
>> isolated the culprit I realized my Python 3 program was being
>> interpreted by Python 2.
>
>
> It would help if you could share details about how you tried to run the
> Python 3 program (command line call, double-click, Python launcher for
> Windows, ..).
>
Initially, I ran the program in question by double-clicking on its
icon, which was my normal way of running it. This is when I realized I
had a problem. The program would run without error, but give erroneous
print and input statement results. I next put Python 3 into my path
variable, but the same error persisted. From the command line I found
that if I ran it normally (With Python 3 still in the path like it was
on my previous 3.4.1 installation.), meaning

python program_name.py

it behaved the same way as double-clicking on the icon. However, if I ran it as

py -3 program_name.py

then all was well.

Apparently Python 2.7.8 became the system default installation if I
installed it last, but after uninstalling both and installing Python
3.4.2 last, it became the default. Or, at least when double-clicked on
it ran normally.

I have since added shebang lines to my programs specifying Python 3.

I hope I have not forgotten any relevant details!



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


[Tutor] Installing both Python 2.7 and Python 3.4 on Windows 7 Pro 64-bit: Install Python 2.7 FIRST!

2014-10-09 Thread boB Stepp
I am hoping to save other people the grief I just worked through. I
wanted to run both Python 2 and 3 on my windows PC, and, after
googling this topic found that with Python 3.3 or later one could
easily do both. So I merrily installed Python 3.4.2 first and then
Python 2.7.8. A Python 3 program that had been working fine suddenly
stopped working. After working down to a test portion of code that
isolated the culprit I realized my Python 3 program was being
interpreted by Python 2. I soon found that installing Python 2 first
and then 3 enabled both to happily coexist. If there was a mention
about the order of installation anywhere during my searches, I missed
it. Anyway, I hope that my experience helps some other newbie who
wants to play around with both major versions.

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


Re: [Tutor] How best to structure a plain text data file for use in program(s) and later updating with new data?

2014-10-08 Thread boB Stepp
On Wed, Oct 8, 2014 at 2:19 PM, Martin A. Brown  wrote:
>
> Good afternoon,
>
>>> If its not too big a task you could even convert the data
>>> structure to JSON which is quite a close match to what you
>>> have now and the json module will help you read/write
>>> to them.

Looking at some examples of JSON-structured data, I see that I
formatted my data very similarly, as Alan noted. Purely a lucky
coincidence!

>
> I would agree with the JSON recommendation (until your data set grows to
> more than 10GB in size).  Also, if you are operating with JSON, you can add
> elements and delete elements and the serialization bits don't care.  This
> makes it more dynamic than a typical csv/tsv format.  The application still
> has to know about the data type, of course.
>

My data files are rather small and should remain so, about 30 to 40
lines at the most. Definitely forever less than 100 lines for each
file. This is because there are only so many human organs in the
vicinity of our radiation treatments that we might want to track dose
for.

>> I am not seeing JSON listed among python's standard libraries for version
>> 2.4.4. Is this something that has to be independently installed?
>
>
> Yes.  The json module was 'only' added in Python 2.6.  If you wanted to
> operate on JSON in Python 2.4, you had to use something called simplejson
> [0].  According to this post [0], the standard library json module is a(n
> older) release of the simplejson module.
>

I looked at [0] and it states that it is backwards compatible to
version 2.5, which is one iteration higher than my lowest installed
python version at work. They provide a link to an older simplejson
that is from the python 2.2 era, but state that this should be done
only as a last resort.

> Anyway, when I found myself stuck in Python-2.4 land (on the stock Python
> shipped with CentOS-5.x, for example), I often saw and wrote snippets like
> this [1]:
>
>   try:  # -- if Python-2.6+, it's in STDLIB
>   import json
>   except ImportError:  # -- Python-2.4, simplejson
>   import simplejson as json
>
> And, then the rest of the program can operate just the same, regardless of
> which one you used.
>

Is there a typo on [0]? Will it in fact work for python 2.4?

>
>  [0] https://pypi.python.org/pypi/simplejson/
>  [1]
> http://stackoverflow.com/questions/712791/what-are-the-differences-between-json-and-simplejson-python-modules
>

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


Re: [Tutor] How best to structure a plain text data file for use in program(s) and later updating with new data?

2014-10-08 Thread boB Stepp
On Wed, Oct 8, 2014 at 11:27 AM, Alan Gauld  wrote:
> On 08/10/14 16:47, boB Stepp wrote:
>
>>> It looks like you have csv like data.  Except you have a semicolon as
>>> a separator.  Look at the csv module.  That should work for you
>>>
>> Joel, will the labels (like SERIAL_ROI:) cause me difficulties? I will
>> need to strip these off to get to the actual data. But when I
>> implement a data editor later, these labels will be needed (I think.).
>
>
> You will get the name:value fields as strings.
> You can then use string.split(':') to separate them and
> then either lose the label or convert them to a dictionary.

Ah! Thanks. That should work well.

> If its not too big a task you could even convert the data
> structure to JSON which is quite a close match to what you
> have now and the json module will help you read/write
> to them.

I am not seeing JSON listed among python's standard libraries for
version 2.4.4. Is this something that has to be independently
installed?

>> I just now have located the documentation for python 2.4.4. It does
>> not seem to be as friendly or easy to read as for the current version
>> documentation.
>
>
> Shouldn't be that much different.
> What kind of anomalies are you seeing?

Compare the current library index,
https://docs.python.org/2/library/index.html, with the 2.4.4 one,
https://docs.python.org/release/2.4.4/lib/lib.html . On the former I
was able to immediately find the csv module with a quick scroll, but
in the latter I found myself using my browser's find function to
locate the link. The other improvement that the newer presentation has
that the older does not, is an actual brief example along with the
description in the module contents. Perhaps these are minor points...


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


Re: [Tutor] How best to structure a plain text data file for use in program(s) and later updating with new data?

2014-10-08 Thread boB Stepp
On Wed, Oct 8, 2014 at 10:02 AM, Joel Goldstick
 wrote:

[...]

> It looks like you have csv like data.  Except you have a semicolon as
> a separator.  Look at the csv module.  That should work for you
>
Joel, will the labels (like SERIAL_ROI:) cause me difficulties? I will
need to strip these off to get to the actual data. But when I
implement a data editor later, these labels will be needed (I think.).

I just now have located the documentation for python 2.4.4. It does
not seem to be as friendly or easy to read as for the current version
documentation. But I will persevere...

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


[Tutor] How best to structure a plain text data file for use in program(s) and later updating with new data?

2014-10-08 Thread boB Stepp
About two years ago I wrote my most ambitious program to date, a
hodge-podge collection of proprietary scripting, perl and shell files
that collectively total about 20k lines of code. Amazingly it actually
works and has saved my colleagues and I much time and effort. At the
time I created this mess, I was playing "guess the correct proprietary
syntax to do something" and "hunt and peck perl" games and squeezing
this programming work into brief snippets of time away from what I am
actually paid to do. I did not give much thought to design at the time
and knew I would regret it later, which is now today! So now in my
current few snippets of time I wish to redesign this program from
scratch and make it much, ... , much easier to maintain the code and
update the data tables, which change from time to time. And now that I
have some version of python available on all of our current Solaris 10
systems (python versions 2.4.4 and 2.6.4), it seems like a fine time
to (finally!) do some serious python learning.

Right now I have separated my data into their own files. Previously I
had integrated the data with my source code files (Horrors!).
Currently, a snippet from one of these data files is:

NUMBER_FX:ONE; DATA_SOURCE:Timmerman; RELEASE_DATE:(11-2012);

SERIAL_ROI:Chiasm; TEST_VOLUME:< 0.2 cc; VOLUME_MAX_GY:8.0;
MAX_PT_DOSE_GY:10.0; MAX_MEAN_DOSE: ;
SERIAL_ROI:Optic_Nerve_R; TEST_VOLUME:< 0.2 cc; VOLUME_MAX_GY:8.0;
MAX_PT_DOSE_GY:10.0; MAX_MEAN_DOSE: ;
SERIAL_ROI:Optic_Nerve_L; TEST_VOLUME:< 0.2 cc; VOLUME_MAX_GY:8.0;
MAX_PT_DOSE_GY:10.0; MAX_MEAN_DOSE: ;

[...]

PARALLEL_ROI:Lungs_Bilateral; CRITICAL_VOLUME_CC:1500.0;
CRITICAL_VOLUME_DOSE_MAX_GY:7.0; V8GY: ; V20GY: ; MAX_MEAN_DOSE: ;
PARALLEL_ROI:Lungs_Bilateral; CRITICAL_VOLUME_CC:1000.0;
CRITICAL_VOLUME_DOSE_MAX_GY:7.6; V8GY:< 37.0%; V20GY: ; MAX_MEAN_DOSE:
;
PARALLEL_ROI:Liver; CRITICAL_VOLUME_CC:700.0;
CRITICAL_VOLUME_DOSE_MAX_GY:11.0; V8GY: ; V20GY: ; MAX_MEAN_DOSE: ;
PARALLEL_ROI:Renal_Cortex_Bilateral; CRITICAL_VOLUME_CC:200.0;
CRITICAL_VOLUME_DOSE_MAX_GY:9.5; V8GY: ; V20GY: ; MAX_MEAN_DOSE: ;
[EOF]

I just noticed that copying from my data file into my Google email
resulted in all extra spaces being condensed into a single space. I do
not know why this has just happened. Note that there are no tab
characters. The [...] indicates omitted lines of serial tissue data
and [EOF] just notes the end-of-file.

I am far from ready to write any code at this point. I am trying to
organize my data files, so that they will be easy to use by the
programs that will process the data and also to be easily updated
every time these data values get improved upon. For the latter, I
envision writing a second program to enable anyone to update the data
tables when we are given new values. But until that second program
gets written, the data files would have to be opened and edited
manually, which is why I have labels included in all-caps ending in a
colon. This is so the editor will know what he is editing. So,
basically the actual data fields fall between ":" and ";" . String
representations of numbers will need to get converted to floats by the
program. Some fields containing numbers are of a form like "< 0.2 cc"
. These will get copied as is into a GUI display, while the "0.2" will
be used in a computation and/or comparison. Also notice that in each
data file there are two distinct groupings of records--one for serial
tissue (SERIAL_ROI:) and one for parallel tissue (PARALLEL_ROI). The
fields used are different for each grouping. Also, notice that some
fields will have no values, but in other data files they will have
values. And finally the header line at the top of the file identifies
for what number of fractions (FX) the data is to be used for as well
as the source of the data and date that the data was released by that
source.

Finally the questions! Will I easily be able to use python to parse
this data as currently structured, or do I need to restructure this? I
am not at the point where I am aware of what possibilities python
offers to handle these data files. Also, my efforts to search the 'net
did not turn up anything that really clicked for me as the way to go.
I could not seem to come up with a search string that would bring up
what I was really interested in: What are the best practices for
organizing plain text data?

Thanks!

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


Re: [Tutor] pygame module

2014-10-04 Thread boB Stepp
On Fri, Oct 3, 2014 at 4:27 PM, Rob Ward  wrote:
> i downloaded the 3.4 version of python but there is no matching binary file
> for pygame ive tried every 1.9.1 file and still cant import pygame  would an
> older version of python work
>
If you have windows try: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame


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


Re: [Tutor] usage difference between tabs and spaces

2014-09-09 Thread boB Stepp
On Tue, Sep 9, 2014 at 7:27 AM, Mirage Web Studio  wrote:
>
> Hello,
>
> I am not an advanced programmer, but am very good with keyboard and find
> using tabs for syntax and formatting very helpful. But in this list and
> other python documentation i have repeatedly seen people recommending
> use of spaces.
>
> I know that i can use any of them and use tabs as my preference.  But i
> would like to understand why hitting the poor keyboard 4/8/12 times is
> preferred than just hitting it 1/2/3 times.

I will allow the experts to answer your root question. I just want to
point out that most editors have a setting where hitting tab results
in spaces being inserted (of the appropriate number) instead of tab
characters. Thus you can use your preferred tab key and follow
recommended technique!
-- 
boB
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Good Text Editor/IDE for Python

2014-09-01 Thread boB Stepp
On Sun, Aug 31, 2014 at 7:12 PM, Juan Christian
 wrote:
> I've been using PyCharm to code in Python but it seems a bit "overpowered"
> for this task, and there are some annoying bugs. I used Sublime Text 2 in
> the past, but it seems to be dead now (last update was JUN/2013), so I don't
> really know any good options.
>
Sublime Text is still being developed by its creator. He is just being
slow (thorough?) about it. A seemingly stable beta version of Sublime
Text 3 is available, and the plugin community is actively developing
for it.

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


Re: [Tutor] Printing a list count - Help

2014-08-30 Thread boB Stepp
On Fri, Aug 29, 2014 at 2:17 PM, Derek Jenkins  wrote:
> Hi everybody,
>
> I have a list that I want to go through and finally print a total
> count of particular items. In this case, I want to print the result of
> how many A's and B's are in the list.
>
> honor_roll_count = 0
> student_grades = ["A", "C", "B", "B", "C", "A", "F", "B", "B", "B", "C", "A"]
>
> for grades in student_grades:
> honor_roll_count = honor_roll_count + 1
> if grades == "A" or grades == "B":
>     print honor_roll_count
>

Are you sure you have your increment of honor_roll_count where you
want it? As it is placed you are counting how many grades of any kind
there are.

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


Re: [Tutor] subprocess.call not formatting date

2014-07-08 Thread Bob Williams
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On 08/07/14 18:12, Peter Otten wrote:
> I suggest that you calculate the folder name in Python instead:
> 
> # untested name =
> datetime.datetime.now().strftime("%y-%m-%d_%H-%M") destpath =
> os.path.join("/home/bob/A3/docsnaps", name) subprocess.call( 
> ["btrfs", "subvolume", "snapshot", "/home/bob/A3/documents",
> destpath])

Thank you. That worked perfectly. Once it's pointed out it is obvious
to use the python solution, but my brain is becoming less agile as I
collect more birthdays!

Bob
- -- 
Bob Williams
System:  Linux 3.11.10-17-desktop
Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.13.2
Uptime:  06:00am up 2 days 9:43, 5 users, load average: 0.00, 0.02, 0.05
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.22 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iEYEARECAAYFAlO8Nw8ACgkQ0Sr7eZJrmU6HVwCaAkT+nqxn818s1Di8mgqc9U1a
qksAni7exn27xTGgDV2O6vSNtg8FbgMK
=9I7G
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] subprocess.call not formatting date

2014-07-08 Thread Bob Williams
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

I'm using Python 2.7.6 on an openSUSE linux system.

I'm trying to convert a shell (bash) script to a python script, and 
everything's worked OK except this. The following line in the shell script

btrfs subvolume snapshot /home/bob/A3/documents /home/bob/A3/docsnaps/`date 
+%y-%m-%d_%H-%M`

creates a folder of the form

/home/bob/A3/docsnaps/14-07-08_17-32

ie. the name is a formatted date string, which is what I want.

In my python script, this

subprocess.call('btrfs', 'subvolume', 'snapshot', '/home/bob/A3/documents', 
'/home/bob/A3/docsnaps/`date +%y-%m-%d_%H-%M`')

creates a folder

/home/bob/A3/docsnaps/`date +%y-%m-%d_%H-%M`

In other words, it does not format the date, but takes the stuff between the 
backticks (`) as a string.

I tried adding shell=True, but got the following error:

Traceback (most recent call last):
  File "/home/bob/bin/btrfs-backup.py", line 55, in 
subprocess.call('btrfs', 'subvolume', 'snapshot', '/home/bob/A3/documents', 
'/home/bob/A3/docsnaps/`date +%y-%m-%d_%H-%M`', shell=True)
  File "/usr/lib64/python2.7/subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
  File "/usr/lib64/python2.7/subprocess.py", line 658, in __init__
raise TypeError("bufsize must be an integer")
TypeError: bufsize must be an integer

Any suggestions, please?
- -- 
Bob Williams
System:  Linux 3.11.10-17-desktop
Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.13.2
Uptime:  06:00am up 2 days 9:43, 5 users, load average: 0.00, 0.02, 0.05
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.22 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iEYEARECAAYFAlO8H9gACgkQ0Sr7eZJrmU7fdACgkBqVXT+Ozb+XqmEFwhPBdmeX
NcgAnjY6YrbXcmUTAvgLPblk4rOWFAdH
=vfIY
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What are your favourite unofficial resources

2014-06-30 Thread Bob Williams
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On 29/06/14 23:41, Alan Gauld wrote:
> I'm looking for tips for an appendix to a book that I'm working
> on.
> 
> What are the best unofficial (ie not python.org) resources for
> people who have learned the basics but are not experts yet? ie
> Typical tutor list "graduates"...
> 
> I'm thinking about web sites, blogs, books, videos etc. Anything
> that might be worth knowing about.
> 
> I've got a few of my own - Activestate, O'Reilly, ByteOfPython,
> PythonChallenge, ShowMeDo etc.
> 
> But I thought the tutor list readers might be an interesting source
> of alternatives that I hadn't thought of, or even heard of.
> 
> All contributions considered :-)
> 

Python Module of the Week <http://pymotw.com/2/>

Bob
- -- 
Bob Williams
System:  Linux 3.11.10-17-desktop
Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.13.2
Uptime:  06:00am up 1 day 20:14, 0 users, load average: 0.04, 0.05, 0.05
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.22 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iEYEARECAAYFAlOxRIsACgkQ0Sr7eZJrmU5kfQCgkE0dRzO1G+o/GX78s4U7oe3U
mNQAoJ+ayTo+79Xj+9JaHoMrflxDHCzW
=uWQJ
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] code review

2014-06-11 Thread Bob Williams
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On 11/06/14 08:11, Alan Gauld wrote:
> On 11/06/14 00:30, Adam Gold wrote:
> 
>> Thanks for the reply Steven.  It's no more than 100 lines at a
>> guess
> 
> In that case just copy and paste it into a message and send it to
> the group. Anyone with time available can then take a peek.
> 
> 
> hth

One way noobs anywhere can learn is by listening in to other people's
conversations - it's called lurking, I believe.

So I would say, please do this on the list, and many more people than
Adam may benefit. Others can ignore the thread if they wish.

Bob
- -- 
Bob Williams
System:  Linux 3.11.10-11-desktop
Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.13.1
Uptime:  06:00am up 3 days 11:36, 3 users, load average: 0.05, 0.03, 0.05
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.22 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iEYEARECAAYFAlOYFfkACgkQ0Sr7eZJrmU5EUwCgkvjIWEdp1AzodJj6j5fY5yAL
wtsAoKFSwk2U4kq5HW5KsmeErH+9fcXI
=lJCF
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Logical error?

2014-05-03 Thread Bob Williams
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi Steven,

On 03/05/14 02:53, Steven D'Aprano wrote:
> Hi Bob, and welcome!
> 
> My responses interleaved with yours, below.
> 
> On Fri, May 02, 2014 at 11:19:26PM +0100, Bob Williams wrote:
>> -BEGIN PGP SIGNED MESSAGE- Hash: SHA1
>> 
>> Hi,
>> 
>> I'm fairly new to coding and python. My system is linux
>> (openSUSE 13.1).
> 
> Nice to know. And I see you have even more infomation about your
> system in your email signature, including your email client and
> uptime. But what you don't tell us is what version of Python you're
> using. I'm going to guess that it is something in the 3.x range,
> since you call print as a function rather than a statement, but
> can't be sure.
> 
I have both 2 and 3 installed here, but I call this script with
python2. I guess I should concentrate on Python 3 as that's the way
things are going.

> Fortunately in this case I don't think the exact version matters.
> 
> 
> [...]
>> fullPath = []   # declare (initially empty) lists truncPath = []
>> 
>> with codecs.open('/var/log/rsyncd.log', 'r') as rsyncd_log: for
>> line in rsyncd_log.readlines(): fullPath += [line.decode('utf-8',
>> 'ignore').strip()]
> 
> A small note about performance here. If your log files are very
> large (say, hundreds of thousands or millions of lines) you will
> find that this part is *horribly horrible slow*. There's two
> problems, a minor and a major one.
> 
The log file is typically a few thousand lines, so my code runs fast
enough, but I understand your point.

> First, rsyncd_log.readlines will read the entire file in one go.
> Since you end up essentially copying the whole file, you end up
> with two large lists of lines. There are ways to solve that, and
> process the lines lazily, one line at a time without needing to
> store the whole file. But that's not the big problem.
> 
> The big problem is this:
> 
> fullPath += [line.decode('utf-8', 'ignore').strip()]
> 
> which is an O(N**2) algorithm. Do you know that terminology? Very 
> briefly: O(1) means approximately constant time: tripling the size
> of the input makes no difference to the processing time. O(N) means
> linear time: tripling the input triples the processing time.
> O(N**2) means quadratic time: tripling the input increases the
> processing time not by a factor of three, but a factor of three
> squared, or nine.
> 
> With small files, and fast computers, you won't notice. But with
> huge files and a slow computer, that could be painful.
> 
> Instead, a better approach is:
> 
> fullPath.append(line.decode('utf-8', 'ignore').strip())
> 
> which avoids the O(N**2) performance trap.
> 
Understood.
> 
[snip]
> 
> Now at last we get to your immediate problem: the above is intended
> to iterate over the lines of fullPath. But it starts at the 
> beginning of the file, which may not be today. The first time you
> hit a line which is not today, the program exits, before it gets a
> chance to advance to the more recent days. That probably means that
> it looks at the first line in the log, determines that it is not
> today, and exits.
> 
I'd missed the (now obvious) point that my if condition contained two
terms which both have to be true.

> I'm going to suggest a more streamlined algorithm. Most of it is
> actual Python code, assuming you're using Python 3. Only the
> "process this line" part needs to be re-written.
> 
> new_activity = False  # Nothing has happened today. with
> open('/var/log/rsyncd.log', 'r', encoding='utf-8', errors='ignore')
> as rsyncd_log: for line in rsyncd_log: line = line.strip() if
> line[0:10] == today and 'recv' in line: new_activity = True process
> this line  #  <== fix this
> 
> if not new_activity: print("no new albums have been added today")
> 
Thanks. This works nicely.
> 
> 
> This has the benefit that every line is touched only once, not
> three times as in your version. Performance is linear, not
> quadratic. You should be able to adapt this to your needs.
> 
> Good luck, and feel free to ask questions!
> 



- -- 
Bob Williams
System:  Linux 3.11.10-7-desktop
Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.13.0
Uptime:  06:00am up 11:26, 4 users, load average: 0.00, 0.02, 0.05
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.22 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iEYEARECAAYFAlNlXCYACgkQ0Sr7eZJrmU71OACfSy1XWSDA08DNAndcA89AZg6Z
+2IAniQJIrSd7wVJWl2MEtEdHlcdkwfj
=YtSq
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Logical error?

2014-05-02 Thread Bob Williams
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi,

I'm fairly new to coding and python. My system is linux (openSUSE
13.1). I've written the following code to examine a log file, and
extract strings from certain lines if two conditions are met, namely
that the file has been modified today, and the line contains the
string 'recv'.

- ---Code---
#!/usr/bin/python

import sys
import datetime
import codecs
import subprocess

# Format date as /MM/DD
today = (datetime.datetime.now()).strftime('%Y/%m/%d')

fullPath = []   # declare (initially empty) lists
truncPath = []

with codecs.open('/var/log/rsyncd.log', 'r') as rsyncd_log:
for line in rsyncd_log.readlines():
fullPath += [line.decode('utf-8', 'ignore').strip()]
if fullPath[-1][0:10] == today:
print("\n   Rsyncd.log has been modified in the last 24 hours...")
else:
print("\n   No recent rsync activity. Nothing to do.\n")
sys.exit()

# Search for lines starting with today's date and containing 'recv'
# Strip everything up to and including 'recv' and following last '/'
path separator
for i in range(0, len(fullPath)):
if fullPath[i][0:10] == today and 'recv' in fullPath[i]:
print("got there")
begin = fullPath[i].find('recv ')
end = fullPath[i].rfind('/')
fullPath[i] = fullPath[i][begin+5:end]
truncPath.append(fullPath[i])
print("   ...and the following new albums have been added:\n")
else:
print("   ...but no new music has been downloaded.\n")
sys.exit()

- ---Code---

The file rsyncd.log typically contains lines such as (sorry about the
wrapping):

2014/05/02 19:43:14 [20282]
host109-145-nnn-xxx.range109-145.btcentralplus.com recv Logical
Progression Level 3 (1998) Intense/17 Words 2 B Heard Collective -
Sonic Weapon.flac 72912051 72946196

I would expect the script to output a list of artist and album names,
eg Logical Progression Level 3 (1998) Intense. IOW what is between the
string 'recv' and the trailing '/'. What it actually produces is:

:~> python ~/bin/newstuff.py

   Rsyncd.log has been modified in the last 24 hours...
   ...but no new music has been downloaded.

This suggests that the first 'if' clause (matching the first 10
characters of the last line) is satisfied, but the second one isn't,
as the flow jumps to the second 'else' clause.

As the script runs without complaint, this is presumably a logical
error rather than a syntax error, but I cannot see where I've gone wrong.

Bob
- -- 
Bob Williams
System:  Linux 3.11.10-7-desktop
Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.13.0
Uptime:  06:00am up 11:26, 4 users, load average: 0.00, 0.02, 0.05
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.22 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iEYEARECAAYFAlNkGewACgkQ0Sr7eZJrmU57YwCgg91pxyQbFMSe+TqHkEjMuzQ6
03MAnRQ50up6v+kYE+Hf/jK6yOqQw4Ma
=+w0s
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why should modules or packages should define their own domain-specific base exception class?

2014-04-14 Thread bob gailer

On 4/14/2014 10:09 PM, brian arb wrote:
I don't quite understand why the google python style guide recommends 
that packages and modules we write should avoid using the catch-all 
except. Instead the guide encourages you to write domain specific 
exception classes.


class Error(Exception):
  """..."""

class ThisSpecificError(Error):
"""..."""

class ThatSpecificError(Error):
"""..."""


try:
  ...
except mylib.Error:
  ...
|
|
|REF. 
|http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=Exceptions#Exceptions


Thoughts?
Let's say I write a program to process some user input that should 
follow some syntatic / semantic rules. When my program finds a violation 
I want to raise an exception that is specific to these rules, rather 
than a built-in exception.


Raising such exceptions is a useful way to exit from some possibly 
deeply nested series of calls, ifs, whiles, fors, etc. I write except 
statements for my error classes, then let the python-specific ones be 
caught by a different except.


The python-specific exceptions mean something is wrong with my progam, 
which I handle differently than those related to user input.

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


Re: [Tutor] Python & algorithms (Lang line simplification algorithm)

2014-04-14 Thread bob gailer

On 4/14/2014 11:30 AM, Laura Kauria wrote:

Thanks a lot for all the help! I got the courage to start at least..


Some requests regarding posts.

1) put your comments following the relevant text rather than at the top.
2) delete old (irrelevant) text.
4) be more clear with your questions.

I started by converting the pseudocode I had to python.


3) post your code
Still I have problems with perpendicular distance and creating a line 
with python.

I need to create a line between two points

what does that mean (apart from the obvious) in terms of your code>
and then check what is the distance between a line and intermediate 
points which were between lines start and end point. If someone could 
help me with this?
I'm a geographer student so all possible library suggestions 
concerning spatial data is also appreciated.



4) be more clear with your questions.

I can make guesses about what you want, but that wastes time.

" distance between a line and intermediate points which were between 
lines start and end point" as I read this the answer seems to be zero. ( 
a point that is between lines start and end point is on the line). I 
don't think you mean that.


We are here to help. The more you tell us the easier it is for us to help.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Refining Code

2014-04-11 Thread bob gailer

On 4/10/2014 6:26 PM, Saba Usmani wrote:


 My task is :

Welcome to the tutor list. In what school are you learning Python?

What version of Python? What operating system? What do you use to write 
and run your code?


What Python elements have you studied so far? Your code can be greatly 
simplified by the application of tuples, lists, dictionaries, functions 
and/or classes.


Requests: post in plain text rather than html (no formatting). This 
guarantees that all of us will be able to read your posts with ease.


Also reply in such a way that a copy goes to tutor@python.org, to keep 
all of us in the loop.


The rest of my comments follow the relevant part of your post. Please 
also reply in similar fashion. Avoid as much as possible "top posting".


A food vending machine accepts 10p, 20p, 50p and £1 coins. One or more 
coins are inserted and the current credit is calculated and displayed. 
A product is selected from those available. The system checks to see 
if there is enough credit to purchase the product chosen. If there is 
not enough credit the system displays an error message. If there is 
enough credit it dispenses the product, updates the credit available 
and displays the remaining credit. Further selections can be made if 
there is enough credit. The vending machine simulation should have 
five products and prices. Design, code, test and evaluate a program 
for this simulation.
I am glad to see this problem appear again. Recently it was sent to me 
privately by someone who claimed it was not homework!


Critique of the specification: it is a bit vague (imprecise). I assume 
the instructor has a broad tolerance for what is delivered. In a 
business environment I'd want it a lot more precise. Often I have to 
help the user accomplish this, as many users don't know how to do this.


it is a good idea to first develop a sample dialog from the 
specification, review that with the user, then code to reproduce that 
sample. Do this. Either review it with the instructor or forget that step.


I have designed the following code, but would like to know how to make 
it more efficient without making it too complex as I am a beginner or 
is this fine?
Efficient? Do you mean execution time? With today's processor speeds 
that is rarely an issue to be concerned about when first writing code.


Complexity does not necessarily create efficiency.
Also, how do I add a loop to this so that once one product has been 
dispensed the program asks the user if they would like to continue and 
purchase another product?

Alan has given a suggestion already.

Based on your code you already know how to use a while loop. What is 
mysterious about using it here?



Code:

print "Welcome to Snack Attack"

snack1 = 0.40
snack2 = 0.75
snack3 = 1.20
snack4 = 0.99
snack5 = 0.50
insert = 0

You never use this variable!


change = 0

This machine does not dispense change!

currentCredit = 0.00
A = 0.10
B = 0.20
C = 0.50
D = 1.00
a = 0.10
b = 0.20
c = 0.50
d = 1.00
Never Never use floating values for money, as floating point cannot in 
general represent fractional values exactly.


print "Menu"
print "Snack 1: Snickers - £0.40"
print "Snack 2: Doritos - £0.75 "
print "Snack 3: J20 - £1.20"
print "Snack 4: Oreos - £0.99"
print "Snack 5: M&M's - £0.50"
print "Exit?"- how do I make this a Boolean 
expression, so the user can respond with either yes or no?


You don't. Better (as Alan suggested) use raw_input and treat users 
entries as character. There is no advantage to using input and integers 
and a lot of room for errors.



choice = input("Select your snack: ")
This does not agree with the specification - enter coin(s) first. The 
ensuing dialog also does not agree with the specification. You deposit 
one or more coins first, see the available credit. then choose a


if choice==1:
  print " "
  print "You have selected Snickers, which cost £0.40"
  print "Please insert £0.40"
  while currentCredit < snack1:
  print "Please select which of these coins to insert; 
A:10p,B:20p,C:50p and D:£1"

  insert_coins = input("Insert coins: ")
  currentCredit = insert_coins + currentCredit
Major problem here. As A user I'd enter (say) 20p. How does that get 
translated to a numeric value for adding?

What should happen if I enter 30p, or 20x, or foo?

  print "Your current credit is £",currentCredit
This assumes that credit less than £1 will be reported as a fraction of 
a £. How will you handle this fraction?

  else:
  change_given=currentCredit-snack1
  print " "
  print "Your change is £",change_given
  print "Your Snickers have been dispensed...Enjoy!"

elif choice==2:
 print "You have selected Doritos, which cost £0.75"
 print "Please insert £0.75"
 while currentCredit  print "Please select which of these coins to insert; 
A:10p,B:20p,C:50p and D:£1"

  insert_coins = input("Enter coins: ")
  currentCredit = insert_coins + currentCredit
  print "Your current 

Re: [Tutor] Range within a range

2014-04-11 Thread bob gailer

On 4/11/2014 1:13 PM, Andoni Gorostiza wrote:
Hi tutor. I need your help with something I don't understand. In the 
tutorial, it mentions an example of a range within a range. I'll keep 
it simplified. How exactly does this work? I'll provide a few examples.


>>> for x in range(0,5):
...for n in range(0,5):
...  print(x)

>>> for x in range(0,5):
...for n in range(0,5)
...  print(n)

This one comes from the tutorial:

>>>for  n  in  range(2,  10):
... for  x  in  range(2,  n):
... if  n  %  x  ==  0:
... print(n,  'equals',  x,  '*',  n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n,  'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
Can you explain what is going on?
We could but that will not help you learn. Instead I recommend with 
pencil and paper you play computer - "execute" (write) the code one step 
at a time and write down what happens. Very simple example:

execute:   change:
for x in range(0,2):  x == 0
  for n in range(0,2):   n == 0
print(x) output == 0
  next for n   n == 1
print(x) output == 0
next for x x == 1
  for n in range(0,2):   n == 0
print(x) output == 1
keep going - at each step write what executes and what changes or happens

When you run into an operation you don't understand stop and either
- look it up
- ask this list

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


Re: [Tutor] difference between expressions and statements

2014-04-10 Thread bob gailer

On 4/10/2014 5:48 PM, Jared Nielsen wrote:


Thanks for the thorough answer, Bob. I now understand the difference.


Thanks for the ACK. It helps me remember I have something to contribute.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] difference between expressions and statements

2014-04-10 Thread bob gailer
Caveat: I began this before there were any other responses. So this may 
be overkill - but I ike to be thorough.


On 4/9/2014 12:49 PM, Jared Nielsen wrote:

Hi Pythons,
Could someone explain the difference between expressions and statements?

I know that expressions are statements that produce a value.
No. Expressions are not statements. These are mutually exclusive. 
Expressions do produce values.

An attempt at a thorough answer:

In the language reference glossary under "expression" you will find:

"A piece of syntax which can be evaluated to some value. In other words, 
an expression is an accumulation of expression elements like literals, 
names, attribute access, operators or function calls which all return a 
value There are also statements which cannot be used as expressions, 
such as if. Assignments are also statements, not expressions."


Tthe above is a quote; I don't like some of the grammar.

In your examples print is a function. So all calls to print are expressions.

In the language reference you will also find:

7. Simple statements
7.1. Expression statements
7.2. Assignment statements
7.3. The assert statement
7.4. The pass statement
7.5. The del statement
7.6. The return statement
7.7. The yield statement
7.8. The raise statement
7.9. The break statement
7.10. The continue statement
7.11. The import statement
7.12. The global statement
7.13. The nonlocal statement
8. Compound statements
8.1. The if statement
8.2. The while statement
8.3. The for statement
8.4. The try statement
8.5. The with statement
8.6. Function definitions
8.7. Class definitions

With the exception of
- 7.1. Expression statements
- all of the above are either start with a keyword except 7.2 assignment 
which is indicated by an equal sign (=) .
- all of the above cause something to happen (except pass), and do not 
return a value.


7.1. Expression statement is either one expression or several separated 
by commas.

Used interactively to display value(s).
Used anywhere to make a function call.

I'm unclear on functions and especially strings.
Are any of the following expressions?

print(42)
print("spam")
spam = 42
print(spam)

Is the first example producing a value or simply displaying an integer?
All function calls return a value. In the case of print the return value 
is always None.

spam = 42 is a statement. (indicated by the = sign. 42 is a value.

Does a string count as a value?
Yes - however I suspect you are limiting "string" to something within quotes. Those are 
"string literals".
Is a variable assignment considered a value?

No

If I print a variable is that considered production of a value?

See above comment on print.

Long but comprehensive answer. Feel free to ask questions.

Note there are various subtleties here -some  keywords may be used to 
start a statement or in an expression - e.g. if, else, for yield.


This also raises the fact that else (inter ala) is neither an expression 
or a statement; rather it is part of a compound statement. Nothing is 
simple.


Oh there is more but I may never hit send

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


Re: [Tutor] Vending machine problem.

2014-04-02 Thread bob gailer

On 4/2/2014 5:06 PM, Sebastien Gomez wrote:

i am using python 3.2
windows vista

This is my last email to you. Communicating with you is way too time 
consuming; you consistently do not provide all the information I 
request, nor do you include the tutor list in your responses.


If you want any more help you will have to ask it from the tutor list.

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


Re: [Tutor] Vending machine problem.

2014-04-02 Thread bob gailer

On 4/1/2014 5:09 PM, Sebastien Gomez wrote:
I have started my code but there are some errors including indentation 
and syntax, please fix it if you can:


Did you miss my request that you send a copy to the tutor list 
(tutor@python.org)?


Were there any more specifications in the assignment?

Please take care of these; then I will respond. Also keep in mind that 
our goal is to help you think for yourself, so we may not fix it but 
rather help you understand and  fix the problems.


What tool did you use to discover multiple errors? If you try to run the 
program directly the Python interpreter will report the first error it 
finds and then stop.


In general it is a good idea to tell us (so please do so now)
- your operating system
- Python version
- what you use to edit and run the program

I am sorry to be so wordy and rigorous but we really need to know if we 
are to help.

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


[Tutor] Vending machine problem.

2014-04-01 Thread bob gailer

On 4/1/2014 3:26 AM, Sebastien Gomez wrote:

The vending machine must have 5 prices with items
it should accept 10p, 20p 50p and £1 coins
it should allow the user to purchase a item and give him a choice of 
purchasing something else. it should display the remaining credit once 
the item is purchased. i will let you know of anything else


Thank you. I am copying this to tutor@python.org where a bunch of us 
hang out and collectively help others. PLEASE in future always reply-all 
so a copy goes to the list.


I am changing the subject line to something meaningful.

This sounds like a homework assignment. We don't provide answers for 
homework. We will help you once you show some effort and tell us where 
you need a hand.


The requirements are kinda vague. I would have a hard time guessing 
exactly what the instructor is looking for.


Did you get any other information?

Did you get some sample of the expected input and output?

If no th the latter,  good starting place is to write down a sample 
dialog, then apply the Python functions you should have learned by now 
to make that dialog happen.


How do you plan to store the collection of items and their prices? What 
Python data types have you learned that you could use here?


How do you plan to look up an item to get its price?

Show us your answers to any of the above, tell us exactly where you are 
stuck, and we will see what we can do to help.

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


[Tutor] Vending machine problem.

2014-04-01 Thread bob gailer

I'm posting this to include you in this conversation.

Recently I got the following Request: can you write me a code in python 
please or if you have one already


my response:
 print('hello world')
what more can I do for you?

 (next two lines are best guesses as I can't find the relevant emails.
Request:  can you write me a code for a vending machine  in python 
please or if you have one already

Response: I need a lot more detail.

Request:
The vending machine must have 5 prices with items
it should accept 10p, 20p 50p and £1 coins
it should allow the user to purchase a item and give him a choice of 
purchasing something else. it should display the remaining credit once 
the item is purchased. i will let you know of anything else


Tutors: sounds familiar, eh?

Response: This sounds like a homework assignment. We don't provide 
answers for homework. We will help you once you show some effort and 
tell us where you need a hand.


The requirements are kinda vague. I would have a hard time guessing 
exactly what the instructor is looking for.


Did you get any other information?

Did you get some sample of the expected input and output?

If no to the latter,  good starting place is to write down a sample 
dialog, then apply the Python functions you should have learned by now 
to make that dialog happen.


How would you store the collection of items and their prices? What 
Python data types have you learned that you could use here?


How would you look up an item to get its price?

Show us your answers to any of the above, tell us exactly where you are 
stuck, and we will see what we can do to help.

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


Re: [Tutor] Slices of lists of lists

2014-03-28 Thread Bob Williams
On 28/03/14 09:42, Jose Amoreira wrote:
> Hello!
> Here is something that surprised me and I still didn't get it.
> 
> If we want to store a matrix in pure python (no numpy), the first thing
> that comes to (my) mind is to use a list of lists, like the list l below:
> In [1]: l=[
>...:[11,12,13],
>...:[21,22,23]
>...:   ]
> 
> We can access individual components of this object in a simple, to be
> expected way:
> 
> In [2]: l[0][1], l[1][0]
> Out[2]: (12, 21)
> 
> OK, that's fine. If we want to access individual rows of this matrix
> like object, the standard slice notation (on the second index) works as
> expected also:
> 
> In [3]: l[0][:]
> Out[3]: [11, 12, 13]
> 
> In [4]: l[1][:]
> Out[4]: [21, 22, 23]
> 
> Again, fine! But what if we want to access a particular row? My first
> guess was that standard slice notation on the first index would do it,
> but it doesn't! Instead, we get the rows again:
> 
> In [6]: l[:][0]
> Out[6]: [11, 12, 13]
> 
> In [7]: l[:][1]
> Out[7]: [21, 22, 23]
> 

Jose,

Just for clarity, are you trying to access a particular *column* in your
last example?

Bob
-- 
Bob Williams
System:  Linux 3.11.10-7-desktop
Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.3
Uptime:  06:00am up 4 days 19:51, 4 users, load average: 0.37, 0.18, 0.15
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to create a sqlite table schema dynamically

2014-03-20 Thread bob gailer

On 3/19/2014 8:19 AM, Toni Fuente wrote:

Hello everyone,

I am stack with a problem that I can't find a solution:

I need to create a sqlite schema dynamically, I've got a dictionary with
text keys: "RedHat", "CentOS", "SLES9",..., "etc", "etc"

My intention was at the time of creating the table schema run a loop
through the dictionary keys and incorporate them to the schema:

for os in osDict.items():
cur.execute('''CREATE TABLE mytable(week INTEGER NOT NULL, os TEXT NOT 
NULL, number INTEGER NOT NULL)''')
IMHO you are mixing data with column names. Usually the column name in 
this case would be just os.


What is your use case for this?

But I don't know how to pass the os key to the sqlite command.

Thank you in advance for any help,
Kind regards,




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


Re: [Tutor] improvements on a renaming script

2014-03-09 Thread bob gailer

On 3/9/2014 3:22 PM, street.swee...@mailworks.org wrote:

Hello all,

A bit of background, I had some slides scanned and a 3-character
slice of the file name indicates what roll of film it was.
This is recorded in a tab-separated file called fileNames.tab.
Its content looks something like:

p01 200511_autumn_leaves
p02 200603_apple_plum_cherry_blossoms

The original file names looked like:

1p01_abc_0001.jpg
1p02_abc_0005.jpg

The renamed files are:

200511_autumn_leaves_-_001.jpeg
200603_apple_plum_cherry_blossoms_-_005.jpeg

The script below works and has done what I wanted, but I have a
few questions:

- In the get_long_names() function, the for/if thing is reading
the whole fileNames.tab file every time, isn't it?  In reality,
the file was only a few dozen lines long, so I suppose it doesn't
matter, but is there a better way to do this?
The "usual" way is to create a dictionary with row[0] contents as keys 
and row[1] contents as values. Do this once per run. Then lookup each 
glnAbbrev in the dictionary and return the corresponding value.

- Really, I wanted to create a new sequence number at the end of
each file name, but I thought this would be difficult.  In order
for it to count from 01 to whatever the last file is per set p01,
p02, etc, it would have to be aware of the set name and how many
files are in it.  So I settled for getting the last 3 digits of
the original file name using splitext().  The strings were unique,
so it worked out.  However, I can see this being useful in other
places, so I was wondering if there is a good way to do this.
Is there a term or phrase I can search on?
I'm  sorry but I don't fully understand that paragraph. And why would 
you need to know the number of files?

- I'd be interested to read any other comments on the code.
I'm new to python and I have only a bit of computer science study,
quite some time ago.
Beware using tabs as indents. As rendered by Thunderbird they appear as 
8 spaces which is IMHO overkill.
It is much better to use spaces. Most Python IDEs have an option to 
convert tabs to spaces.


The Python recommendation is 4; I use 2.

#!/usr/bin/env python3

import os
import csv

# get longnames from fileNames.tab
def get_long_name(glnAbbrev):
with open(
  os.path.join(os.path.expanduser('~'),'temp2','fileNames.tab')
  ) as filenames:
filenamesdata = csv.reader(filenames, delimiter='\t')
for row in filenamesdata:
if row[0] == glnAbbrev:
return row[1]

# find shortname from slice in picture filename
def get_slice(fn):
threeColSlice = fn[1:4]
return threeColSlice

Writing a function to get a slice seems overkill also. Just slice in place.

# get 3-digit sequence number from basename
def get_bn_seq(fn):
seq = os.path.splitext(fn)[0][-3:]
return seq

# directory locations
indir = os.path.join(os.path.expanduser('~'),'temp4')
outdir = os.path.join(os.path.expanduser('~'),'temp5')

# rename
for f in os.listdir(indir):
if f.endswith(".jpg"):
os.rename(
os.path.join(indir,f),os.path.join(
outdir,

get_long_name(get_slice(f))+"_-_"+get_bn_seq(f)+".jpeg")
)

exit()

HTH - remember to reply-all so a copy goes to the list, place your 
comments in-line as I did, and delete irrelevant text.

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


Re: [Tutor] os.symlink can't find target

2014-02-26 Thread Bob Williams
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On 26/02/14 15:41, Bob Williams wrote:
On 26/02/14 05:31, Cameron Simpson wrote:
>>> linkName1 = pathList[j][0:-3] + "mp3"
>>> 
>>> Isn't this exactly the same as pathList[j] ?
>>> 
> Actually, no.

Actually, you are right. I've trimmed down that block now, thank you.

Bob
- -- 
Bob Williams
System:  Linux 3.11.10-7-desktop
Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2
Uptime:  18:00pm up 3:41, 5 users, load average: 2.73, 2.45, 1.92
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.22 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iEYEARECAAYFAlMObU0ACgkQ0Sr7eZJrmU5AhgCgpolM3vDLEDzEy8t1o4O+5zCA
B58AoJJC3IeyXqt3onBNnoaUaW833Lj3
=BhVn
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Editing values from a dictionary

2014-02-26 Thread Bob Williams
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On 26/02/14 17:29, Ben Finney wrote:
> Bob Williams  writes:
> 
>> In [3]: print metadata["artist"] [u'The Incredible String Band']
>> 
>> I now want to pass that string to another program, but I want to
>> strip off the leading [u' and the trailing '].
> 
> You may be assuming that ‘metadata["artist"]’ is a text string; I 
> suspect it is not.
> 
> Try ‘type(metadata["artist"])’, to get Python to tell you what the
> type of that object is.
> 
Aha! Sounds of pennies dropping ;-)

In [7]: type(metadata["artist"])
Out[7]: list

In [12]: print metadata["artist"][0]
The Incredible String Band

Gets me what I want. Thank you.

Bob
- -- 
Bob Williams
System:  Linux 3.11.10-7-desktop
Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2
Uptime:  12:00pm up 13 days 20:00, 6 users, load average: 0.10, 0.19, 0.26
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.22 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iEYEARECAAYFAlMOKP8ACgkQ0Sr7eZJrmU5a0ACdEH9kJPtHmbQ9w8YXrUc3NJT1
/t8AnitS+J4+kcM2z+Ai6Ak7cbe7Qnmk
=Sv8P
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Editing values from a dictionary

2014-02-26 Thread Bob Williams
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi List,

I have two problems, but it's possible that one solution will suffice.
I am using a module called mutagen to extract audio metadata from
.flac files. The output of mutagen is in the form of a dictionary, so

In [1]: import mutagen.flac

In [2]: metadata = mutagen.flac.Open("/home/bob/music/artists/The
Incredible String Band/1967 The 5000 Spirits Or The Layers Of The
Onion/08 The Hedgehog's Song.flac")

In [3]: print metadata["artist"]
[u'The Incredible String Band']

I now want to pass that string to another program, but I want to strip
off the leading [u' and the trailing ']. However, this doesn't work:

In [4]: artistName = metadata["artist"][3:-2]

In [5]: print artistName
[]

I was expecting The Incredible String Band, not []

What am I doing wrong? Or what have I misunderstood?

The other problem concerns the program that receives these arguments -
it complains (and stops with an error) if one the arguments is empty.
For example, the flac file may not have the date information:

Traceback (most recent call last):
  File "/home/bob/Documents/scripts/python/flac2mp3v2.py", line 81, in
 subprocess.call(['lame', '--add-id3v2',
'--ignore-tag-errors', '--tt', str(metadata['title']), '--ta',
str(metadata['artist']), '--tl', str(metadata['album']), '--ty',
str(metadata['date']), '--tn', str(metadata['tracknumber']), '--tg',
str(metadata['genre']), tempName1, tempName3])
  File "/usr/lib/python2.7/site-packages/mutagen/__init__.py", line
85, in __getitem__
else: return self.tags[key]
  File "/usr/lib/python2.7/site-packages/mutagen/_vorbis.py", line
184, in __getitem__
if not values: raise KeyError, key
KeyError: 'date'

If it's possible to edit the string value that gets passed to
subprocess.call('lame'...) - see problem #1 above, would it also be
possible to define a default value if the original field is empty?

Bob
- -- 
Bob Williams
System:  Linux 3.11.10-7-desktop
Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2
Uptime:  12:00pm up 13 days 20:00, 6 users, load average: 0.10, 0.19, 0.26
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.22 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iEYEARECAAYFAlMOH9sACgkQ0Sr7eZJrmU5ufACeILRlmiXt4CgDa6ZpdTI3Npm5
FToAn2+AcjNKGxJKU+9nE9IdsoEqlQdd
=JpdC
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.symlink can't find target

2014-02-26 Thread Bob Williams
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hi Cameron,

Many thanks for your helpful comments. I do still have some problems
with my script, but it's probably better to start a new thread with an
appropriate subject.

I'm a bit new to Python, so it still seems like magic sometimes
(someone else said the same in a different thread). A lot of my coding
is 'trial & error', and I'll admit that at the moment my main goal is
getting things to work; after that I can explore making my code more
efficient/readable etc. But I appreciate your suggestions.

On 26/02/14 05:31, Cameron Simpson wrote:
> Hi Bob,
> 
[...]
> 
> The other things are just script remarks, not directly related to
> your problem:
> 
> On 24Feb2014 16:07, Bob Williams 
> wrote:
>> if pathList[j][-3:] == "mp3":
> 
> This is often written (I've inserted a dot, assuming you don't
> want "foomp3", only "foo.mp3"):
> 
> if pathList[j].endswith(".mp3"):
> 
> More readable, and also more reliable because it doesn't rely on 
> you getting the "3" correct.
> 
Yes, and reduces the need for explanatory comments.

>> linkName1 = pathList[j][0:-3] + "mp3"
> 
> Isn't this exactly the same as pathList[j] ?
> 
Actually, no. pathList[j] can contain either .mp3 files or .flac
files. In fact the main function of the script is to run all the flacs
through lame to convert them into mp3s. If they are already mp3s, then
a symlink will suffice.

>> linkName2 = destPath + linkName1[len(sourcePath):]
> 
> You might want to spell this:
> 
> linkName2 = os.path.join(destPath, linkName1[len(sourcePath):])
> 
More good stuff. :-)

Bob
- -- 
Bob Williams
System:  Linux 3.11.10-7-desktop
Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2
Uptime:  12:00pm up 13 days 20:00, 6 users, load average: 0.10, 0.19, 0.26
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.22 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iEYEARECAAYFAlMOC0UACgkQ0Sr7eZJrmU77fwCeIAgFpOKEdt5C6Q/qzHPQglnm
91gAnRLHLs5u/369RNsBOMOFeZVhTiN5
=w7La
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.symlink can't find target

2014-02-24 Thread Bob Williams
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On 24/02/14 16:56, Mark Lawrence wrote:
> On 24/02/2014 16:36, Peter Otten wrote:
>> Bob Williams wrote:
>> 
[...]
>>> Thanks,
>> 
>> os.symlink(existing_file, symlink_to_create)
>> 
>> fails with that error if the directory that shall contain the new
>> symlink does not exist. You can create it before making the
>> symlink with
>> 
>> try: os.makedirs(os.path.dirname(symlink_to_create)) except
>> OSError as err: # Assume the directory exists. # A thorough coder
>> would check the errno here pass
>> 
> 
> Python 3.3+ allows finer grained error handling than that shown
> above, so you could catch FileExistsError, see 
> http://legacy.python.org/dev/peps/pep-3151/ for the details.
> 
I'm using a module (mutagen) elsewhere in this script, which only
works in Python 2 (so far). Also, I'm fairly new to this, so getting
things working takes precedence over 'good practice' like error
trapping. But I'm also aware that it's best to establish good habits
early on.

Bob
- -- 
Bob Williams
System:  Linux 3.11.10-7-desktop
Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2
Uptime:  12:00pm up 11 days 20:00, 5 users, load average: 0.14, 0.17, 0.22
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.22 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iEYEARECAAYFAlMLfOMACgkQ0Sr7eZJrmU4IgQCgn5MeqNsCOgiS3QY8g2jjMooR
65oAnjcWZaHrfe78C2WvHjMNlqZqjgo1
=CnnC
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.symlink can't find target

2014-02-24 Thread Bob Williams
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On 24/02/14 16:36, Peter Otten wrote:
> os.symlink(existing_file, symlink_to_create)
> 
> fails with that error if the directory that shall contain the new
> symlink does not exist. You can create it before making the symlink
> with
> 
Peter,

Many thanks. I was fixating on the existing_file, not realising I had
to create a home for the symlink first.

> try: os.makedirs(os.path.dirname(symlink_to_create)) except OSError
> as err: # Assume the directory exists. # A thorough coder would
> check the errno here pass

Regards

Bob
- -- 
Bob Williams
System:  Linux 3.11.10-7-desktop
Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2
Uptime:  12:00pm up 11 days 20:00, 5 users, load average: 0.14, 0.17, 0.22
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.22 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iEYEARECAAYFAlMLe3QACgkQ0Sr7eZJrmU6QmQCeLUSIh0l97T017KrIHXT92Xhd
YuQAn2To2AOXNpbA4fZ+4i6Swt4RdsMg
=NgLw
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] os.symlink can't find target

2014-02-24 Thread Bob Williams
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

My operating system is Linux (openSUSE 13.1).

I'm trying to create symlinks. The following code:

if pathList[j][-3:] == "mp3":
linkName1 = pathList[j][0:-3] + "mp3"
linkName2 = destPath + linkName1[len(sourcePath):]
print 'Creating link %s -> %s' % (linkName2, pathList[j])
os.symlink(pathList[j], linkName2)

fails with this error:


Creating link /pollux/music/portable/testing/artists/Death in
June/1995 Rose Clouds Of Holocaust/10 Lifebooks.mp3 ->
/home/bob/music/artists/Death in June/1995 Rose Clouds Of Holocaust/10
Lifebooks.mp3
Traceback (most recent call last):
  File "/home/bob/Documents/scripts/python/flac2mp3.py", line 101, in

os.symlink(pathList[j], linkName2)
OSError: [Errno 2] No such file or directory

The same thing happens in ipython, when I type the paths in manually.
I have tried escaping the spaces with '\', but the same error is
generated.

The file "/home/bob/music/artists/Death in June/1995 Rose Clouds Of
Holocaust/10 Lifebooks.mp3" definitely exists.

Thanks,

Bob
- -- 
Bob Williams
System:  Linux 3.11.10-7-desktop
Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2
Uptime:  12:00pm up 11 days 20:00, 5 users, load average: 0.14, 0.17, 0.22
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.22 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iEYEARECAAYFAlMLblkACgkQ0Sr7eZJrmU4qfACdGc7/U8dN6I/NcyJsHA7ILzcV
Ea4AoIHSbWLkg5eQ1Lo5rN7z0FTse+YM
=+wrZ
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] i dont understand this code

2014-02-22 Thread bob gailer

On 2/22/2014 7:26 AM, piyush joshi wrote:


Can anyone help me out in understanding this code


Your question is kinda vague. Exactly what do you not understand?


#

import os

rotationMatrix1 = [7, 1, 5, 3, 0, 6, 2, 5, 2, 3, 0, 6, 1, 7, 6, 1, 5, 
2, 7, 1, 0, 3, 7, 6, 1, 0, 5, 2, 1, 5, 7, 3, 2, 0, 6]


rotationMatrix2 = [1, 6, 2, 5, 7, 3, 0, 7, 1, 6, 2, 5, 0, 3, 0, 6, 5, 
1, 1, 7, 2, 5, 2, 3, 7, 6, 2, 1, 3, 7, 6, 5, 0, 1, 7]


keyboardDict = {  2: '1',  3: '2',  4: '3',  5: '4',  6: '5',  7: 
'6',  8: '7',  9: '8', 10: '9', 11: '0',


 16: 'q', 17: 'w', 18: 'e', 19: 'r', 20: 't', 21: 'y', 
22: 'u', 23: 'i', 24: 'o', 25: 'p',


 30: 'a', 31: 's', 32: 'd', 33: 'f', 34: 'g', 35: 'h', 
36: 'j', 37: 'k', 38: 'l',


 44: 'z', 45: 'x', 46: 'c', 47: 'v', 48: 'b', 49: 'n', 
50: 'm' }


def keyboardEncToAscii(inKey):

out = ""

for c in inKey:

if c == 0: return out

if c in keyboardDict: out += 
keyboardDict[c]


else: return ""

return out

def decryptHash(hash, key, rotationMatrix):

outhash = []

for i in range(0, len(hash)):

outhash.append(((hash[i] << (rotationMatrix[7*key+i])) & 0xFF) | 
(hash[i] >> (8-rotationMatrix[7*key+i])))


return outhash

print("")

print("hexa decimal code")

print("hexadecimal code from which the password can be calculated,")

print("07088120410C")

print("")

print("Please enter the code: ")

code = raw_input()

hash = []

for i in range(1, len(code) // 2):

hash.append(int(code[2*i]+code[2*i+1],16))

key = int(code[0:2], 16) % 5

password = keyboardEncToAscii(decryptHash(hash, key, rotationMatrix1))

if password == "":

password = keyboardEncToAscii(decryptHash(hash, key, 
rotationMatrix2))


if password == "":

print("The password could not be calculated. Bummer.")

else:

print("The password is: " + password)

if (os.name == 'nt'):

print("Press a key to exit...")

raw_input()




   

This email is free from viruses and malware because avast! Antivirus 
 protection is active.





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


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


Re: [Tutor] Recommendation For A Complete Noob

2014-02-12 Thread Bob Williams
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On 12/02/14 00:58, Dave Angel wrote:
> Bob Williams  Wrote in message:
> 
> 
>> to slice those lines to get the artist and album names into a
>> list.
>> 
>> So far, so good but my output contains duplicates, so my final
>> task is to work out how to get rid of them.
>> 
> 
> 
> Hint: a set will contain only one of each item. So if you have a 
> list of immutable items, the following will eliminate duplicates:
> 
> newlist = list (set (oldlist))
> 
> Sometimes a dict is better,  if only part of each item is to be 
> made unique.
> 
> This assumes that order doesn't matter.  If it does, perhaps an 
> ordered dict.
> 
Many thanks, Dave. That worked perfectly. Ordering doesn't matter in
this case, but I might try it as an exercise.

Bob
- -- 
Bob Williams
System:  Linux 3.11.10-7-desktop
Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2
Uptime:  06:00am up 2 days 10:01, 5 users, load average: 0.35, 0.31, 0.21
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.22 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iEYEARECAAYFAlL7QxsACgkQ0Sr7eZJrmU6I+gCffgK34BBSBPQ02ZjAKm/TwlUQ
VyoAn1etNjuywwWIa1e2fqx9YlGeXGu9
=NhPX
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Recommendation For A Complete Noob

2014-02-11 Thread Bob Williams
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On 09/02/14 22:37, Altrius wrote:
> Hi,
> 
> I’m completely new to programming in general and everything I have
> read so far has pointed me to Python. I’ll put this another way:
> All I know is that a programming language is a medium for a human
> to tell a computer what to do. After that I’m kinda lost. I was
> just hoping to get some input as to where I might start. I’m not
> completely computer illiterate but you can reply to me as if I am.
> What should I work on learning first. I’m good at doing my own
> research and teaching myself but I need to know what I’m
> researching and where to start. Any advice would be VERY much
> appreciated.
> 
> Thanks, Altrius
> 

Hi Altrius,

I'm also a noob. In addition to all the excellent recommendations
already posted, I would suggest setting yourself a task to solve in
python. It's far more interesting than working through the examples in
most books - the challenge is solving each problem as you come across
them. Google is excellent.

The task I set myself is to write a script that interrogates the
rsyncd.log file every day, to tell me if any new music has been added
to my collection by my son. My linux machine is on 24/7.

I have had to work out how to open the file, how to tell if it's been
altered in the last 24 hours, if so how to extract the lines of
interest, and how to slice those lines to get the artist and album
names into a list.

So far, so good but my output contains duplicates, so my final task is
to work out how to get rid of them.

You may find me popping up here again in a few days ;-)

Good luck.

Bob
- -- 
Bob Williams
System:  Linux 3.11.10-7-desktop
Distro:  openSUSE 13.1 (x86_64) with KDE Development Platform: 4.12.2
Uptime:  18:00pm up 1 day 22:01, 5 users, load average: 0.17, 0.17, 0.21
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.22 (GNU/Linux)
Comment: Using GnuPG with Thunderbird - http://www.enigmail.net/

iEYEARECAAYFAlL6sVAACgkQ0Sr7eZJrmU54NgCeP+v3YJk7LxFBkYraOGUL3p94
h8YAn22UWIHzfnIutkk1yUNeMcPtfkgg
=7Jq8
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Code runs in interpreter but won't output to stdout

2014-01-31 Thread bob gailer

On 1/29/2014 8:59 PM, scurvy scott wrote:

Please always reply to the tutor list so we can all play with your question.



On 1/28/2014 9:12 PM, scurvy scott wrote:

Hi guys, I'm trying to figure out why my code won't output to
terminal, but will run just fine in interpreter.
I'm using python 2.7.3 on Debian Linux/Crunchbang.

Here is my code.

import requests
from bs4 import BeautifulSoup as beautiful
import sys

def dogeScrape(username, password):
payload = {'username': username, 'password': password}
r = requests.post("http://dogehouse.org/index.php?page=login";,
data=payload)
soup = beautiful(r.text)
confirmed = str(soup.findAll('span',{'class':'confirmed'}))
print "Confirmed account balance: " + confirmed[86:98]

dogeScrape("", "")

It will output the "confirmed." part, just not the confirmed
variable. It will output the entire thing in the interpreter.


I am stuck at "import requests". Where did you get that module?

My guess is that you are getting a different response from the server. I 
suggest you write the entire response text to a file, then edit it 
looking for 'class="confirmed"'.


I signed up at Dogehouse. What the heck is it? There is no explanation 
as to what it does or what I'd do with it!


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


Re: [Tutor] Code runs in interpreter but won't output to stdout

2014-01-29 Thread bob gailer

On 1/28/2014 9:12 PM, scurvy scott wrote:
Hi guys, I'm trying to figure out why my code won't output to 
terminal, but will run just fine in interpreter.

I'm using python 2.7.3 on Debian Linux/Crunchbang.

Here is my code.

import requests
from bs4 import BeautifulSoup as beautiful
import sys

def dogeScrape(username, password):
payload = {'username': username, 'password': password}
r = requests.post("http://dogehouse.org/index.php?page=login";, 
data=payload)

soup = beautiful(r.text)
confirmed = str(soup.findAll('span',{'class':'confirmed'}))
print "Confirmed account balance: " + confirmed[86:98]

dogeScrape("", "")

It will output the "confirmed." part, just not the confirmed 
variable. It will output the entire thing in the interpreter.


Good reminder for everyone: be explicit about behavior. We wasted an 
iteration just to get this clarified.


The expression to be printed is the concatenation of "Confirmed account 
balance: " with a slice of confirmed. Therefore confirmed is less that 
86 characters (or the slice is blank), therefore no output appears. 
Print the entire value of confirmed; that will tell us a lot.

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


Re: [Tutor] code works in windows command but not ubuntu terminal

2014-01-25 Thread bob gailer

On 1/24/2014 10:28 PM, bob gailer wrote:

Sorry for misspelling parens.

My reason for requesting the various names is that it makes 
communication clear, explicit and terse.


When someone says just "brackets" what does he actually mean?

For more grins see 
http://www.codinghorror.com/blog/2008/06/ascii-pronunciation-rules-for-programmers.html

and http://www.theasciicode.com.ar/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] code works in windows command but not ubuntu terminal

2014-01-24 Thread bob gailer

On 1/24/2014 4:47 AM, Steven D'Aprano wrote:

Hi Tobias, and welcome.

On Thu, Jan 23, 2014 at 07:34:18PM -0700, Tobias Quezada wrote:

hello community,i am a newbie to python and program in general.
the script below works in python 2.7.3 on windows but not in the python 2.7.3 
ubuntu terminal.


fp=open("prez.dat","r")
x=fp.read
(print(x)

***i used fp for file pointer.I am using windows 7 and it works

Are you sure this is the *exact* same code you use on Windows 7? Because
it won't read the file, it will fail with a SyntaxError due to the
missing close bracket after the print.
This is Python 2.7.3, not 3.x. The error is due to a ( in front of the 
print statement.


And please call () parends and [] brackets, and{} braces. Saves a lot of 
confusion.


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


Re: [Tutor] Suggestion required on python as scripting language

2013-12-08 Thread bob gailer

On 12/8/2013 1:59 AM, Shankar Donepudi wrote:

Hi All,

I am working as test engineer in Networking in storage domain. We have 
decided to automate our testing and have chosen python for the same. 
We have basic knowledge on python so can anyone suggest good tutorials 
for writing automation scripts using python.
It might help if you were more specific. What are you testing? What in 
your domain does an automation script do?


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


Re: [Tutor] Automation

2013-11-03 Thread bob gailer

Always reply in such a way that a copy goes to the tutor list.

On 11/3/2013 5:56 PM, Renato Barbosa Pim Pereira wrote:

Solved:

for row in column:
   print row[0]

Sorry for my ignorance, by now, how can I locate the min/max value for 
the printed row?, thanks for patience.


Collect the elements in a list.
Apply min() and max() to the list.
Use list.index() to get the position of the value in the list.

Or write your own program to examine each value, tracking when it gets 
smaller (bigger) and also tracking the index where that change occurs,


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

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


Re: [Tutor] Help with converting a string into a integer

2013-10-31 Thread bob gailer

On 10/31/2013 2:51 PM, Carmen Salcedo wrote:

Thanks Bob! :) I'm very new at programming in Python. I appreciate your 
feedback.

Here are some improvements to consider:

import string
def main():
d = {"1" : phoneTranslator, "2" : backwardString}  # map user 
selection to corresponding function

while True:
selection = raw_input("Enter you choice. Enter 1 " +
   "for Phone Translator or 2 for Backward String.")
operation = d.get(selection, None) # retrieve corresponding 
function or None

if operation: # did we get something?
operation() # call it
break # out of the while loop
print "Invalid choice"

def phoneTranslator():
trans = string.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 
"222333444555666888")

print "Phone Translator "
phoneNumber = raw_input ("Please enter the phone number: ").upper()
phoneNumber = phoneNumber.translate(trans)
print phoneNumber[:3] + "-" + phoneNumber[3:]

def backwardString():
print "not implemented"

main()

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

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


Re: [Tutor] Help with converting a string into a integer

2013-10-31 Thread bob gailer

On 10/31/2013 10:11 AM, Carmen Salcedo wrote:

I'm just trying to figure out how to print the number across like a phone 
number 555- instead of downward. I'm stuck on that.
  On further thought:


print "%s%s%s-%s%s%s%s" % tuple(numberList)

The % operator does formatting. Each %s is replaced by the next string 
in the tuple.


Just be sure you have exactly 7 characters in the list or this will fail.

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

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


Re: [Tutor] Help with converting a string into a integer

2013-10-31 Thread bob gailer

On 10/31/2013 10:11 AM, Carmen Salcedo wrote:

Thanks Bob! :) A list is great idea. I'm just trying to figure out how to print 
the number across like a phone number 555- instead of downward. I'm stuck 
on that.


I repeat what I said before:


There are many ways to get the desired output.
One is:
   collect the characters in one list, say numberList
   Then use slicing to insert the "-" e.g. numberList[3:3] = "-"
   Then print "".join(numberList)



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

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


Re: [Tutor] Help with converting a string into a integer

2013-10-31 Thread bob gailer

On 10/31/2013 7:52 AM, Carmen Salcedo wrote:
I'm not able to post it right now. All I did to the previous program i 
emailed was changed isalpha() to str.isalpha.

That does agree with what you posted or got.

The part of your original program that should print a character already is
print (str.isalpha()
which raises this exception:

  File "N:\Script2.py", line 37, in phoneTranslator
print(str.isalpha())
TypeError: descriptor 'isalpha' of 'str' object needs an argument

it should be

print n

Exactly what did you type in response to
phoneNumber = raw_input ("Please enter the phone number: ")

Note you are not consistent in converting letters:
elif n == "G" or n == "H" or n == "I":
n = "4"
elif n == "J" or n == "K" or n == "L":
n = 5
all the numbers should be characters e.g.
n = "5"
etc.

There are many ways to get the desired output.
One is:
  collect the characters in one list, say numberList
  Then use slicing to insert the "-" e.g. numberList[3:3] = "-"
  Then print "".join(numberList)

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

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


Re: [Tutor] Help with converting a string into a integer

2013-10-31 Thread bob gailer

On 10/31/2013 6:49 AM, Carmen Salcedo wrote:

Hi,

I'm using python 2.7. I'm editing the program with idle. I use windows 8.

I finally got the string to convert to integers, however I can't 
figure out how to print them in this phone number format555-5678 
.


The numbers are printing out this way.
5
5
5
5
6



Please post the new program.

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

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


Re: [Tutor] Dictionary from a text file

2013-10-31 Thread bob gailer

On 10/31/2013 2:16 AM, Nitish Kunder wrote:

I have a dictionary which is in this format
for ex:

{
'5x' : {
'50' : {
'update' : {
'update-from-esxi5.0-5.0_update01' : {
'call' : Update,
'name' : 'Update50u1',
'release' : '15/03/12'
},
'update-from-esxi5.0-5.0_update02' : {
'call' : Update,
'name' : 'Update50u2',
'release' : '21/12/12'
},
},
'patch' : {
'ESXi500-201109001' : {
'call' : Patch,
'name' :'Patch_501',
'release' : '13/09/11'
},
'ESXi500-20001' : {
'call' : Patch,
'name' :'ExpressPatch501',
'release' : '13/09/11'
},
},
},

[snip]
Does it have to be in a dictionary format? I'd rather use sqlite to 
store the data.


Also please give us a use case. There is probably a much simper and more 
elegant solution.


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

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


Re: [Tutor] Help with converting a string into a integer

2013-10-31 Thread bob gailer

On 10/30/2013 10:00 PM, Carmen Salcedo wrote:

> Hi Everyone,

hi

some guidelines for this list.
  post in plain text not html.
  tell us what version of Python you are using, what OS, what you use 
to edit and run the program.

  when replying:
reply-all so a copy goes to the list
put your responses following the relevant text
delete irrelevant text
if you get an exception (error) post the entire traceback. example:

File "N:\foo.py", line 2, in 
2/0
ZeroDivisionError: division by zero

> I hope you're having a great week.  I'm working on this program that 
converts strings to integers. Can someone please help me out? :)


What kind of help do you want?
It is a lot easier for us and more profitable for you when you
  are specific
  tell us what kind of help you need
  did you run the program?
  what did you get and what did you expect?

>Below is the program:

> def main():
> selection = input("Enter you choice. Enter 1 " +
>"for Phone Translator or 2 for Backward String.")
> while selection != 1 and selection !=2:
> print "Invalid choice"
> selection = input("Please enter you selection. Enter 1 " +
>"for Phone Translator or 2 for Backward String.")
> if selection == 1:
> phoneTranslator()
> elif selection == 2:
> backwardString()
> def phoneTranslator():
> print "Phone Translator "
> phoneNumber = raw_input ("Please enter the phone number: ")
> phoneNumber = phoneNumber.upper()
> for n in phoneNumber:
> if str.isalpha(n):
> if n == "A" or n == "B" or n == "C":
> n = "2"
> elif n == "D" or n == "E" or n == "F":
> n = "3"
> elif n == "G" or n == "H" or n == "I":
> n = "4"
> elif n == "J" or n == "K" or n == "L":
> n = 5
> elif n == "M" or n == "N" or n == "O":
> n = 6
> elif n == "P" or n == "Q" or n == "R" or n == "S":
> n = 7
> elif n == "T" or n == "U" or n == "V":
> n = "8"
> else:
> n = "9"
> print str.isalpha()
> main()
> Thanks!! :)
> Carmen

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

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


Re: [Tutor] Geometric sequence

2013-10-30 Thread bob gailer

On 10/30/2013 1:08 PM, Peter O'Doherty wrote:

Hi List,

I know a geometric sequence can be produced by:

series = [2**x for x in range(7)]

But I would like to curtail the sequence before the last element 
excedes a certain value.

import itertools
series = [2**x for x in itertools.takewhile(lambda x: 2**x<60, range(7))]

if the limit is really large you could calculate it once:

import itertools
import math
limit =  int(math.log(60)) + 1
series = [2**x for x in itertools.takewhile(lambda x:xhttps://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python String Help

2013-10-29 Thread bob gailer

On 10/28/2013 4:55 PM, Alex Tenno wrote:

Hey everyone,

Hey back.


I'm encountering a problem with a python function that I am supposed 
to create.

What is the problem? You have not told us that!

What class is this for? I guess either the class is not the right one 
for you (over your head) or the class is just a dud, or you got behind. 
It will help us if you explain your circumstances.


Also we like to see any effort you have put into solving the problem.

What version pf Python? What Operating System? What do you use to write 
your programs? How do you run them?


I want my function to look at a string, and then replace each letter 
in the string with its relative position in the alphabet. for example, 
'abcde' would return '12345', 'zabd' would return '4123', and 'xpft' 
would return '4213'. I have been given hints that tell me "You may 
want to iterate over the letters ch in s as in the for loop above, and 
inside that for loop, count the number of letters that are in s and 
come before the loop variable ch. You will also need an accumulator to 
build the permutation the function will return."



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

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


Re: [Tutor] UnicodeDecodeError while parsing a .csv file.

2013-10-28 Thread bob gailer

On 10/28/2013 6:13 PM, SM wrote:
> Hello,
Hi welcome to the Tutor list

> I have an extremely simple piece of code

which could be even simpler - see my comments below

> which reads a .csv file, which has 1000 lines of fixed fields, one 
line at a time, and tries to print some values.

>
>   1 #!/usr/bin/python3
>   2 #
>   3 import sys, time, re, os
>   4
>   5 if __name__=="__main__":
>   6
>   7 ifd = open("infile.csv", 'r')

The simplest way to discard the first line is to follow the open with
8 ifd.readline()

The simplest way to track line number is

10 for linenum, line in enumerate(ifd, 1):

>  11 line1 = line.split(",")

FWIW you don't need re to do this split

>  12 total = 0
>  19 print("LINE: ", linenum, line1[1])
>  20 for i in range(1,8):
>  21 if line1[i].strip():
>  22 print("line[i] ", int(line1[i]))
>  23 total = total + int(line1[i])
>  24 print("Total: ", total)
>  25
>  26 if total >= 4:
>  27 print("POSITIVE")
>  28 else:
>  29 print("Negative")
>  31 ifd.close()

That should have () after it, since it is a method call.
>
> It works fine till  it parses the 1st 126 lines in the input file. 
For the 127th line (irrespective of the contents of the actual line), it 
prints the following error:

> Traceback (most recent call last):
>   File "p1.py", line 10, in 
> for line in ifd:
>   File "/usr/lib/python3.2/codecs.py", line 300, in decode
> (result, consumed) = self._buffer_decode(data, self.errors, final)
> UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 
1173: invalid continuation byte
Do you get exactly the same message irrespective of the contents of the 
actual line?


"Code points larger than 127 are represented by multi-byte sequences, 
composed of a leading byte and one or more continuation bytes. The 
leading byte has two or more high-order 1s followed by a 0, while 
continuation bytes all have '10' in the high-order position."


This suggests that a byte close to the end of the previous line is 
"leading byte"and therefore a continuation byte was expected but where 
the 0xe9was found.


BTWhen I divide 1173 by 126 I get something close to 9 characters per 
lne. That is not possible, as there would have to be at least 16 
characters in each line.


Best you send us at least the first 130 lines so we can play with the file.

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

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


Re: [Tutor] Want to keep to two decimal places for currency

2013-10-24 Thread bob gailer

On 10/24/2013 2:09 PM, Danny Yoo wrote:
Related: I saw a picture the other day on Google+ of an mailing 
envelope whose zip code was written in scientific notation.

That;s odd - since ZIP codes are character, not integer,

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

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


Re: [Tutor] [OT] Programming practice was: Re: string list in alphabetical!

2013-10-22 Thread bob gailer
I am glad we are having this discussion. It helps me understand the 
plight of some of our posters.


I had the benefit of a good school system, plus attending a technical 
high school and a college of engineering.


In the early 90's I was an adjunct professor at the University of 
Denver's "University College" - evening school for adults seeking an 
MBA. Each class met for 2 hours once a week for 5 weeks. No labs. My job 
was to teach Pascal as a first programming language. My students had 
taken one prerequisite - Introduction To Programming. I built my class 
based on the students' having met the prerequisite. One class of mine 
were struggling with certain fundamental concepts. Turns out the Intro 
class had failed to do its job! One outcome is that I was fired for 
failing to teach Pascal.


BTW Python did not exist then, and I have always disliked Pascal.

As adjunct professor for a similar program at Regis University (Denver) 
I was given an Analysis class to teach. My supervisor created a brand 
new course. The first time I saw the materials was the first night of 
the class! No one had a chance to examine the materials beforehand! That 
class was -`difficult for me and the students.


On the bright side in the 80's I taught daytime adult classes in 
computing for the Boeing company. I was free to change classes that had 
poor materials to (IMHO) good materials. It was almost always fun and I 
almost always got really good evaluations.


I recall one student struggling with his first Basic program. I 
recommended he walk thru it line by line, and I demonstrated that 
technique. Amazed he exclaimed "In that much detail?".


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

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


Re: [Tutor] Tutor] string list in alphabetical!

2013-10-21 Thread bob gailer

On 10/21/2013 12:16 PM, Siva Cn wrote:

Hi Sammy,

Try this this may help you !

--
def sort_file1_to_file2(file1, file2):
"""."""
input_content = []
with open(file1, 'r') as fp:
input_content = fp.read()

input_content = input_content.splitlines()

_dict = {ele[0].lower(): ele for ele in input_content}

out_content = "\n".join([_dict[chr(idx)]
 for idx in range(97, 123)
 if chr(idx) in _dict])

with open(file2, 'w') as fp:
fp.write(out_content)

sort_file1_to_file2('file1.txt', 'file2.txt')

I am surprised to see this program. It seems unnecessarily complex and 
somewhat hard to read.

Especially for a rank beginner (the OP)
Also has an unnecessary statement (input_content = [])

IMHO it is more customary and a lot simpler to process the  lines in a 
file thusly:


  for line in open(file1, 'r'):
process the line

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

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


Re: [Tutor] Cannot understand object initiation

2013-10-12 Thread bob gailer

On 10/12/2013 11:01 AM, Kush Goyal wrote:

[[snip]
"user = User.query.filter_by ( username = self.username.data ).first()"

now this I do not understand.

Can a object be create by using a method of a class instead of the
class consturctor? I

Without seeing the code you reference (User module) I can hazard a guess:

This code is not creating an object - it is returning a reference to an 
existing object.


The key to the object is username, and first() returns the first 
instance should there be more than one,


User is some objectimported from myapplication.models.
query is a callable object that is an attribute of User.
filter_by is a callable object that is an attribute of query.
first is a callable object that is an attribute of filter_by.
Nothing in the above suggests object creation.

HTH

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

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


Re: [Tutor] Parsing Rhino Sightings - Python

2013-10-06 Thread bob gailer

On 10/6/2013 12:11 PM, Mason Majors wrote:

Dear Bob,

I just came across your email address on the following website:

https://mail.python.org/pipermail//tutor/2011-November/087044.html

I was wondering, if you were able to provide any help and slove this 
Pythn coding problem, as I am working on a similar coing script 
without much success.


Just wondering if yo umight be able to help please?
I am copying this to the tutor list, as that gives you access to more 
helpers.


In the above link I said:

"Welcome to the Tutor List.

We are a few volunteers who enjoy tutoring folk on specific Python
learning issues.

We like posts that are in plain text rather than HTML. Please post plain
text in future. Also your code has a blank line between every LOC,
Please remove these in future posts

I failed to see any specific request in your post so all I can say is
welcome and how can we help you. Did you run the code? Did you get
errors or unexpected results? Please report these.

Errors usually appear as a traceback. Include the entire traceback
(after putting in some effort to figure out the error on your own).

unexpected results? Tell us what you expected and how the results differ.

Good luck!"

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

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


Re: [Tutor] sqlite3 place holder problem

2013-10-03 Thread bob gailer

On 10/3/2013 9:52 PM, Alex Kleider wrote:

The following class method
"""

def insert(self, DataBase=DataBase, Table=Table):
"""
Insert instance of ClassMate into  .
"""
with sqlite3.connect(DataBase) as con:
cur = con.cursor()
row = \
('NULL', self.first, self.last, self.partner,
self.address, self.phone, self.email, )
directive = "INSERT INTO %s VALUES ?;" % (Table, )
cur.execute(directive, row)
"""
gives the following error:

"""
Traceback (most recent call last):
  File "./v_temp.py", line 155, in 
go_on.insert()
  File "./v_temp.py", line 70, in insert
cur.execute(directive, row)
sqlite3.OperationalError: near "?": syntax error
"""
(explanation: 'go_on' is an instance of my class in the __main__)

It was working fine when I was using string formatting but I can't 
seem to get the syntax right using the qmark method which the 
documentation suggests is the better way to do it.


Can anyone spot what should be changed?

Try: directive = "INSERT INTO %s VALUES (?,?,?,?,?,?,?);" % (Table, )

(Python 2.7 on Ubuntu )

Thanks in advance.
Alex
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor




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

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


Re: [Tutor] how to generate random numbers in Python

2013-10-03 Thread bob gailer

On 10/3/2013 12:31 PM, Joe Jacques wrote:
Hi and welcome to the tutor list.
Be aware that we are a few volunteers who enjoy assisting when you have 
tried something and are stuck.
As you may have gathered from Mark's response - we don't do homework for 
you. Were you expecting that, or if not what did you expect?
We also enjoy a bit more human interaction. "Problems in the link" is a 
bit terse and uninviting.
Also there are 3 problems on the web, but one mentioned in the subject, 
so I am not even sure what you want help with.
Take a stab at writing the programs; show us your work; tell us where 
you are stuck.

Problems in the link

http://home.manhattan.edu/~ankur.agrawal/cmpt101/assgn5.txt

Sent from my iPhone
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor




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

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


Re: [Tutor] Arbitrary-argument set function

2013-10-02 Thread bob gailer

On 10/1/2013 6:43 PM, Spyros Charonis wrote:


Dear Pythoners,


I am trying to extract from a set of about 20 sequences, the 
characters which are unique to each sequence. For simplicity, imagine 
I have only 3 "sequences" (words in this example) such as:



s1='spam'; s2='scam', s3='slam'


I would like the character that is unique to each sequence, i.e. I 
need my function to return the list [ 'p', 'c', ',l' ]. This function 
I am using is as follows:



def uniq(*args):

""" FIND UNIQUE ELEMENTS OF AN ARBITRARY NUMBER OF SEQUENCES"""

unique = []

for i in args[0]:

if:

   unique.append(i)

return unique


and is returning the list [ 's', 'p', 'a', 'm' ]. Any help much 
appreciated,



Problems with the above.
1 - where is the call to the function? (we can only guess what you fed it.)
2 - for i in args[0]: tests each character in only the first argument
3 - i not in args[1:] will always be True. Why?
4 - "characters which are unique to each sequence" is hard to translate. 
Did you mean

"characters which appear in exactly one sequence"?

BTW this sounds like homework; we are willing to give some assistance 
with HW but we need you to put more effort into your design and testing.


I suggest you either run the program in some tool that will show you 
clearly what happens at each step or "desk check" it - pretend you are 
the computer and go step by step, making sure you know what each line 
does. No guessing. You always have the interactive prompt to test 
things, and the documentation to explain things.


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

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


Re: [Tutor] Help on class

2013-09-27 Thread bob gailer

On 9/27/2013 10:07 AM, bharath ks wrote:

> Hello,
>
Hi welcome to the tutor list.
Please post in plain text rather than tiny hard-to-read formatted text.

> May i know why object 'c' does not prompt for employee name and 
employee id in the following code

You may - see comment below

> i get out put as
>
> Enter employee name:john
> Enter employee id:56
> Employee name is: john
> Employee id is: 56
> 
> Employee name is: test
> Employee id is: 1003
> 
> Employee name is: john
> Employee id is: 56
>
> class employee:
> emp_name=""
> emp_id=0
> def collect_name():
> return(input("Enter employee name:"))
>
>
> def collect_id():
> return(input("Enter employee id:"))
>
> def show(self):
> print("Employee name is:",self.emp_name)
> print("Employee id is:",self.emp_id)
>
> def __init__(self,name=collect_name(),id=collect_id()):

name=collect_name() and id=collect_id() are executed when the def is 
executed.

The values are saved as the default values of name and id.
That happens once, and the default values are used whenever __init__ is 
called without arguments.


> self.emp_name=name
> self.emp_id=id
>
>
>
> a=employee()
> a.show()
> print("----")
> b=employee("test",1003)
> b.show()
> print("")
> c=employee()
> c.show()

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

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


Re: [Tutor] HELP Please!!!....How Do I Make a Graph Chart Generate in Python Based on my Code

2013-09-24 Thread bob gailer

In addition to Alan's comment:
Saying "it work properly" is totally uninformative. Tell us what is 
happening that you want different.


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

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


Re: [Tutor] Field Width

2013-09-19 Thread bob gailer

On 9/18/2013 12:50 PM, Jenny Allar wrote:

I'm only a few days in to learning Python, so please bear with me.

That's what we are here for.


I need to line up the decimals on the printed information but I cannot 
get the text to look uniform at all.

Suggestions to help us help you.
- post only the relevant code. In this case that is:

print("The cost of the carpet is $", format(subtotal,'9,.2f'))
print("The flat fee is $", format(fee,'9,.2f'))
print("The tax is $", format(tax_rate,'9,.2f'))
print("The total due is $", format(total_due,'9,.2f'))

- When you get unexpected results post them as well.
- what OS are you using, version on Python, what are you using to write 
and run your code?


Now for the answer:

You have used tabs to align the text. This will often fail, as each 
output "window" has its own way of interpreting tabs.

Convert the tabs to spaces.

Even better provide formatting directives for the text as well as the 
number. I prefer Python's original format (%):

print("%-30s$%9.2f" % ("The cost of the carpet is ", subtotal))

% start of first format specification
- = left justify
30 = field length
%s = treat value as string
$ = itself
% start of seconb format specification
9.2f = same meaning as in format()
% - format operator
("The cost of the carpet is ", subtotal) = tuple of values to be formatted.

HTH


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

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


[Tutor] fit data to equation

2013-09-05 Thread bob gailer

On 9/5/2013 3:13 PM, I. Alejandro Fleischer wrote:

Dear Friends,
Hi and welcome to the tutor list. Since you are new bear with me while I 
offer some important guidelines to effective communication with us.


1 - don't "hijack" some other email as a quick way to get our email address.
2 - when communicating delete all irrelevant text. We don't need to see 
all the digest.

3 - always use a meaningful subject
4 - when starting a new subject start a new email. Otherwise our thread 
trackers bury the (to you new) message.


I have a set of data to fit to a custom equation, y=a+b*exp(k*x), 
would you advice me on the how to, or tutorial?


Curve fitting is not my strength. Perhaps someone else on the list will 
come to your aid.


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

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


Re: [Tutor] [Python-Help] Please help replace Long place-names with short place-names in many files with Python

2013-09-01 Thread bob gailer
Welcome. We are a few volunteers who like to help you when you have 
tried something and are stuck.


It is best to post to just one email list. Most of us monitor tutor and 
help.


We don't write programs for you. Some of us would be happy to do that 
for a consulting fee.


Why Python?

What other programming experience do you have?

Do you know the basics:
  getting a list of filenames in a directory?
  loops?
  opening and reading / writing files?
  searching for strings in larger strings?
  replacing strings?

OMG I just wrote the outline of your program!

Try writing a program to do some of the above then come back with questions.

Start with something simple - process just one file.

Or hire me as a consultant and I will write it for you.

[snip]

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

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


Re: [Tutor] Comparison Textboxes

2013-08-26 Thread bob gailer

On 8/26/2013 5:26 PM, taserian wrote:
I'm attempting to gather the pieces I need for a simple project I'd 
like to do for my job, but I'm having a difficult time finding 
something, and I'm appealing to the hive mind at Tutor for wisdom.


My project needs to compare two or more large textboxes (each one 
containing a file or a large amount of text) and point out their 
differences, establishing one textbox as the canonical one to which 
the other textboxes are compared. This functionality is done in many 
text editors (Notepad++ can install a plug-in that allows comparison 
between two files), so I would think that the code behind this is 
pretty common, yet I can't seem to find any reference to it. My 
searches for "python text comparison code" points to Python IDEs that 
include that functionality, but no indication as to how to include it 
into my own code. I think I'm missing something else to search by, but 
I can't determine what it is.


Does anyone have an idea of what I'm talking about, and can you point 
me in the right direction?
If you have diff available (e.g. on *nix) write a subprocess to pass the 
texts to diff and retrieve the results. There is NO need to re-invent 
the wheel.


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

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


[Tutor] Comment on http://www.catb.org/esr/faqs/smart-questions.html

2013-08-26 Thread bob gailer
Hi fellow tutors and helpers. I have a reaction to 
http://www.catb.org/esr/faqs/smart-questions.html and I'd like your 
feedback. Perhaps I will then send revised comments to the authors of 
the site.


Before reading my comments pretend you are a newbie asking your first 
question and getting directed to this site.  Go to the site and try it 
get the answer to "how do I ask a good question?"


 proposed comments 

I participate in several Python Help lists. We frequently refer newbies 
to the above site. I decided to take another look at it today.


I found myself a bit disappointed. Here' s why:

All I see at first is email links and Revision History. If I did not 
know to scroll down I might have just figured I was at the wrong page.


Reading translations and disclaimer is not why I'd come here. I also 
would not have come here to be potentially labeled an "idiot".


There's a lot of words to wade thru to get to the heart of the matter - 
how to ask good questions.


What I'd prefer is a page that starts out with a brief summary of a what 
a good question. I think many newbies will read that and get the idea.


Followed by more detail about "how to ask good questions"

Then all the other stuff.

With contact names and email at the bottom preceded by a neutrally 
worded disclaimer. Only those who seek the contact info would need to 
read that.


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

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


Re: [Tutor] i need help with the following question

2013-08-26 Thread bob gailer

On 8/26/2013 4:29 AM, isaac Eric wrote:

describe different ways of displaying output using python!

I am glad you are asking for help. We encourage that.

I agree with the other responses.

Your question is clear to you, but not to us. We could play the guessing 
game and eventually discover what you want - but that is not efficient.


Better is for you to read the article on how to ask questions, then 
re-send your question.


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

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


Re: [Tutor] Convert SOAP response (ArrayOfInt) to Python list

2013-07-10 Thread bob gailer

On 7/4/2013 3:47 PM, Robert Winkler wrote:


Thanks to the OSA library, which works for SOAP requests with Python 
3.x, I can now use SOAP services at http://www.chemspider.com.


The result is a list of accession numbers (which correspond to 
chemical compounds) and I get them in the following format:


(ArrayOfInt){int[]=[5744,69182,292,68027,3404131,82616,18280,11200,704646,543430...]}

How could I transform this to a simple python list?

[5744, 69182, 292,68027, 3404131, 82616, 18280, 11200, 704646, 543430 ...]

Conversion to a numpy array

How did you do that?

[snip] since the structure is maintained; the numpy.shape returns ().

Huh? Makes no sense to me. Please explain.

I assume "the following format" is a character string.

How do you convert characters to integers - hint - int()

So try applying int() to each accession number and collecting the 
results in a list.


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

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


Re: [Tutor] Error in Game

2013-07-03 Thread bob gailer

On 7/2/2013 4:22 PM, Jack Little wrote:

I know the code is correct

As Joel said- how could it be, since you do not get the desired results?

When posting questions tell us:
- what version of Python?
- what operating system?
- what you use to edit (write) your code
- what you do to run your code
copy and paste the execution


, but it doesn't send the player to the shop. Here is the code:

def lvl3_2():
print "You beat level 3!"
print "Congratulations!"
print "You have liberated the Bristol Channel!"
print "[Y] to go to the shop or [N] to advance."
final1=raw_input(">>")
if final1.lower()=="y":
shop2()
elif final1.lower()=="n":
lvl4()
It is a good idea to add an else clause to handle the case where the 
user's entry does not match the if or elif tests.


It is not a good idea to use recursion to navigate a game structure. It 
is better to have each function return to a main program, have the main 
program determine the next step and invoke it.




Help?
Since we are volunteers, the more you tell us the easier it is for us to 
do that.


--
Bob Gailer
919-636-4239
Chapel Hill NC
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with Python in ArcGIS 10.1!

2013-06-23 Thread bob gailer

On 6/17/2013 10:26 AM, Jacobs, Teri (CDC/NIOSH/DSHEFS) (CTR) wrote:


Hi,


Hi - welcome to the tutor list. Be aware that we are a few volunteers.

Your question is one very long line. Please in future ensure it is 
wrapped so we don't have to scroll.


I have wrapped it here.


I have a command line

What is a "command line"?

to spread geoprocessing operations across multiple processes
to speed up performance. However, I do not
know how to import the command line (or at least import it properly)
in Python 2.7.2. Here's the script example given on ArcGIS 10.1 Help:
  
import arcpy


# Use half of the cores on the machine.

arcpy.env.parallelProcessingFactor = "50%"

I tried typing it


What is "it". You show 3 lines of code above. Do you mean all 3 lines?


into the command line


What is "the command line"? Do you mean Command Prompt or Python shell?


but nothing happened.


What did you expect?
Did you hit enter after each line?
Did the cursor move to the next line?
Did you get another prompt?
What did the prompt look like?

I think you get the idea - you need to tell us more, since we did not 
watch you try the above.


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

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


Re: [Tutor] Python and Symbolic Math for beginners

2013-06-16 Thread bob gailer

On 6/15/2013 5:53 AM, Amit Saha wrote:

  Symbolic math?

What is that?

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

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


Re: [Tutor] when is a generator "smart?"

2013-06-03 Thread bob gailer

On 6/1/2013 11:58 PM, Jim Mooney wrote:


 squarelist = (c**2 for c in range(x,y) if c%2 != 0)


can be simplified to:

squarelist = (c**2 for c in range(x,y,2))

as long as x is odd.

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

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


<    2   3   4   5   6   7   8   9   10   11   >