Re: [Tutor] REQUIRED SUPPORT FOR CODE

2019-07-25 Thread john fabiani

Dabo has an AutoComplete method.  You review how it was done.

Johnf

On 7/25/2019 4:26 PM, Alan Gauld via Tutor wrote:

On 25/07/2019 16:58, NITESH KUMAR wrote:

I want to make Autocomplete searchbox using database .Please suggest me the
code for this.

Since you tell us next to noting we can only make wild suggestions.
Try to find a project that does the same thing - ideally one written
in Python (assuming that you are using python?) and see how it does it.

Failing that provide us with a lot more detail.
What kind of application is it? - Desktop? GUI? command line? Web based?
Mobile app?

What tools are you using - specifically any web or GUI toolkits.

What OS and python versions are you using?

What kind of database?

How do you anticipate this would work? Give us some examples?
#

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


[Tutor] Download audios & videos using web scraping from news website or facebook

2019-06-14 Thread Sijin John
Hello Sir/Mam, 
I am trying to Download audios & videos using web scraping from news website 
(eg: https://www.bbc.com/news/video_and_audio/headlines) or Facebook & I 
could't. So in real scenario is it really possible to download audios/videos 
using python code ? 

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


[Tutor] Broadcasting using sockets over adhoc wifi

2019-06-11 Thread John Hoeksema
Hello!

Summer researcher using Raspbian and Python 3.5.

I'm trying to use a Raspberry Pi 3 B+ to broadcast a message using the
sockets library to other Pis (same model) over their shared ad-hoc network.
All of the Pis can ping the others over the ad hoc network. The Pis can
also communicate using pretty standard client-server code and the python
socket library <https://docs.python.org/3.4/library/socket.html>. However,
when I try to *broadcast* a message, the Pis give a "Network is
unreachable" message (full error down below). A grad student I'm working
with said that the script he provided me expects the server to be run in
infrastructure mode, and configuration for ad-hoc mode is required to make
it work correctly. This is confirmed, as I have successfully run the code
on a desktop. I have poured over man pages and stackoverflow, and can't
seem to find resources for how to configure socket broadcasts for ad-hoc
networks. Any thoughts?

The function is supposed to broadcast a message to a specific port after
every [frequency] seconds, and any machines on the same network and
connected to the same port should receive the message. The function is the
only method of the *Server* class.

*Broadcast function:*
def broadcast(self, frequency, port):

server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
socket.IPPROTO_UDP)
server.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
server.settimeout(0.2)

while True:
server.sendto("GET OUT OF MY SWAMP", ('', port))
print("message sent...")
time.sleep(frequency)

*Error message:*
Traceback (most recent call last):
  File "myServer.py", line 31, in 
s.broadcast(float(frequency),int(port))
  File "myServer.py", line 22, in broadcast
server.sendto("GET OUT OF MY SWAMP", ('', port))
socket.error: [Errno 101] Network is unreachable

Thank you for your time. Please let me know any information you think would
be useful!

Best,
John

-- 
*John Hoeksema*
Computer Science
University of Notre Dame '21
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Two Scripts, Same Commands, One Works, One Doesn't

2019-05-15 Thread John Collins
Probably not applicable, but before deleting the original post, I 
distinctly remember seeing in amongst the text of the post, ".pfd"

as part of a larger string of text, and as distinct from ".pdf". I
wondered then if the OP's problem might be a typographical error?
I am a student not a tutor - this is wild speculation!
Best Regards,
John Collins.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to get the weeks of a month

2019-03-04 Thread john fabiani



On 3/4/19 2:47 PM, David Rock wrote:

On Mar 4, 2019, at 16:30, Ben Finney  wrote:

john fabiani  writes:


My understanding is - a week starts on Monday and ends on Sunday.

That's behaviour specific to a timezone. Which one are you using, and
does your program know to consult the timezone data for when a week
begins and ends?


That’s why I said "Which I’m sure is just a question of “defining the start of 
the week” properly.”  “Properly” is in the eye of the beholder.  As long as it’s 
performing the way you expect it to perform, you should be fine.  If all I saw was 
the output you had, I’d think something was broken because I think in terms of first 
day being Sunday, so maybe include a note in the output what the First day of the 
week is if that’s appropriate?


—
David Rock
da...@graniteweb.com



I didn't think about that.  I will in the future.
Thanks,
Johnf
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to get the weeks of a month

2019-03-04 Thread john fabiani



On 3/4/19 1:35 PM, David Rock wrote:

On Mar 4, 2019, at 15:28, john fabiani  wrote:

I knew there was a simple why to get it done!  But where is it off my a day?


comparing

$ cal
  March 2019
Su Mo Tu We Th Fr Sa
 1  2
  3  4  5  6  7  8  9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31

to

import calendar as cal
cal.monthcalendar(2019,3)
[[0, 0, 0, 0, 1, 2, 3], [4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16,
17], [18, 19, 20, 21, 22, 23, 24], [25, 26, 27, 28, 29, 30, 31]]

I see the first element of the array is
[0, 0, 0, 0, 1, 2, 3]

where I would have expected
[0, 0, 0, 0, 0, 1, 2]

Which I’m sure is just a question of “defining the start of the week” properly, 
but if you just took it as-is, Mar 1 would be Thursday, not Friday if you 
translated literally.


—
David Rock
da...@graniteweb.com
My understanding is - a week starts on Monday and ends on Sunday. So 
that looks correct.  Below I use a max function but I wonder if I should 
use a min function too.  Recall I am looking for the string of the dates 
for the week.


Here is my code:
import datetime
import calendar


#get the weeks of a month to get the dates to display
tday = datetime.datetime(2020,03,01)

weeksInMonth =calendar.monthcalendar(tday.year, tday.month)
lastdayof1stweek = weeksInMonth[0][6]
firstweek = tday.strftime("%m-%d_%Y")+ " - "+ 
datetime.datetime(tday.year, tday.month, 
lastdayof1stweek).strftime("%m-%d-%Y")

print firstweek
for i in range(len(weeksInMonth)):
    if i == 0:
    continue
    firstday = weeksInMonth[i][0]
    lastday =  max(weeksInMonth[i])
    weekstr = datetime.datetime(tday.year, tday.month, 
firstday).strftime("%m-%d-%Y") + ' - ' + datetime.datetime(tday.year, 
tday.month, lastday).strftime("%m-%d-%Y")

    print weekstr

def max(arr):
    max_ = arr[0]
    for item in arr:
    if item > max_:
    max_ = item
    return max_
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to get the weeks of a month

2019-03-04 Thread john fabiani



On 3/4/19 1:15 PM, David Rock wrote:

On Mar 4, 2019, at 13:19, Alan Gauld via Tutor  wrote:

On 04/03/2019 18:54, john fabiani wrote:


I need to print out the weeks of the month - given any month and any year.

I'm not totally clear how you define a week.

EDIT: OK I see the comment at the end now.


For example this month would have:

3/1/2019 - 3/3/2019   # notice that this a short week
3/4/2019 - 3/10/2019
3/11/2019 - 3/17/2019
3/18/2019 - 3/24/2019
3/25/2019 - 3/31/2019  # also this can be a short week as in April 2019
last week would be 4/29/2019 - 4/30-2019

What I think he’s shooting for is something similar to cal output

$ cal
  March 2019
Su Mo Tu We Th Fr Sa
 1  2
  3  4  5  6  7  8  9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31



So what I think you want is to

start with the first day and print each day up to Sunday.
Newline
print the current date up to sunday
newline
repeat until you run out of days in the month.



import calendar as cal
cal.monthcalendar(2019,3)

[[0, 0, 0, 0, 1, 2, 3], [4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16,
17], [18, 19, 20, 21, 22, 23, 24], [25, 26, 27, 28, 29, 30, 31]]
That looks close to what you want?


That seems close, but off by a day?


—
David Rock
da...@graniteweb.com

I knew there was a simple why to get it done!  But where is it off my a day?

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


[Tutor] how to get the weeks of a month

2019-03-04 Thread john fabiani

Hi everyone,

I'm not exactly a newbie but I can't seem to solve this problem.

I need to print out the weeks of the month - given any month and any year.

For example this month would have:

3/1/2019 - 3/3/2019   # notice that this a short week
3/4/2019 - 3/10/2019
3/11/2019 - 3/17/2019
3/18/2019 - 3/24/2019
3/25/2019 - 3/31/2019  # also this can be a short week as in April 2019 
last week would be 4/29/2019 - 4/30-2019


I have tried using isocalendar, dateutil, and just plain datetime.

I get close but no real solution. Google wasn't much help either.  So I 
thought I'd ask here - you have been helpful in the past.  And no at my 
age I am not attending school - so this not my homework.


Johnf

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


[Tutor] Problem using termcolor and colorama

2018-11-15 Thread John Blower
I try to create colour text by using these two  modules , only returns the 
colour code, no colour text.
How to solve this problem.

>>> import termcolor
>>> import colorama
>>> colorama.init()
>>> termcolor.cprint('Hello World','red')
[31mHello World[0m


Sent from Mail for Windows 10

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


Re: [Tutor] I have a problem with def

2018-02-23 Thread john fabiani

I don't what you are doing but

it should be at least

def func():

notice the colon at the end.

Johnf


On 02/22/2018 02:16 PM, David Bauer wrote:

it doesn't work, you are suppsed to declare a function as def func() and it
comes back as:

File "", line 1
 def func()
  ^
SyntaxError: invalid syntax

that is not expected I would also expect def to turn red because it is a
keyword in Python, but that doesn't happen, anyone else having this
problem Anyone know what I should do or look for
___
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


[Tutor] Need help fixing some code for a project

2017-11-27 Thread John Cocks
The task is broken down into three sections.
Section 1 - User Input
Section 2 - loop through the grocery list
Section 3 - provide output to the console
'''

#Task: Create the empty data structure
grocery_item = {}

grocery_history = []

#Variable used to check if the while loop condition is met
stop = 'go'

while stop == 'go' :

#Accept input of the name of the grocery item purchased.
item_name = "Item name:\n"
#Accept input of the quantitiy of the grocery item purchased.
quantity = "Quantity purchased:\n"
#Accept input of the cost of the grocery item input (this is a per-item
cost).
cost = "Price per item:\n"
#Create a dictionary entry which contains the name, number and price
entered by the user.
grocery_item = {'name': item_name, 'number': int(quantity), 'price':
float(cost)}  -- errors usually occur here because of "quantity
purchased:\n line
#Add the grocery_item to the grocery_history list using the append
function
grocery_history.append(grocery_item)
#Accept input from the user asking if they have finished entering
grocery items.
print("Would you like to enter another item?\n Type 'c' for continue or
'q' to quit:\n")

# Define variable to hold grand total called 'grand_total'
grand_total = 0
#Define a 'for' loop.

for grocery_item in grocery_history:

  #Calculate the total cost for the grocery_item.
  item_total = number * price
  #Add the item_total to the grand_total
  item_total = grand_total
  #Output the information for the grocery item to match this example:
  #2 apple @ $1.49 ea $2.98
  print('number', 'name', 'price', 'cost')
  #print(name)
  #print(price: %6.2f) -- errors happen here
  #print(item_total: %6.2f) -- errors happen here too

  #Set the item_total equal to 0
  item_total = 0
#Print the grand total
print(grand_total)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python programming for the absolute beginner

2017-09-29 Thread Larocca, John B
Hi Peter

My company primarily uses 2.7, but as I understand it 2.x flavors are 
compatible with each other.
2.x scripts are generally not compatible with 3.x versions and vice versa 
So, keep that in mind.

Regards, 

-John


-Original Message-
From: Tutor [mailto:tutor-bounces+john.b.larocca=intel@python.org] On 
Behalf Of Peter Collidge
Sent: Friday, September 29, 2017 12:51 AM
To: tutor@python.org
Subject: [Tutor] Python programming for the absolute beginner

I have borrowed the above book from my local library but I believe it was
written in 2010 and as a result I am having difficulty in deciding which
version of Python to download.
Can anyone help?
Thanks
Peter Collidge
___
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


[Tutor] sub-modules and python3

2017-05-31 Thread john

Hi folks,

In the past I used a simple "import filename" for sub-modules in python 
2.  With python 3 I have run into errors reported (file not found) using 
python 2 import statements.  But I'm not asking how to correct the 
import as I am able to change the way I write the import as a work 
around - but I'm importing all the files at once.  What I want to know 
is what is the best practice for my situation.


Is there a simple way using python 3  to emulate python 2 imports?

Is there a standard python 3 import tool for sub-modules (files)?

Is it acceptable to add/change the os path to allow my app to find the 
modules/files?


Any help or thoughts on the matter is welcome.


Johnf


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


[Tutor] Could anyone provide a complex data processing automation testing example

2017-04-20 Thread John R
Hi All,

Most of the examples in google are looking simple in automation so I am not
getting an understanding of  how a complex data processing application is
to be tested using python. Can anyone please provide some real time
examples for my
understanding?

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


[Tutor] What are the few senarios of data science testing using Python

2017-04-20 Thread John R
Hi All,

I am just trying to understand that how it is possible to
frame test cases on data science projcets using python! could anyone
provide few sample real time senarios? I searched in google but couldnot
find anything suitable to my need. If anyone works on this type
of projects they can help me out


Thanks in advance,

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


Re: [Tutor] Basic Tutorial for Python

2017-02-06 Thread Larocca, John B
I like this one...
https://learnpythonthehardway.org/book/
It can be done all online

-John

-Original Message-
From: Tutor [mailto:tutor-bounces+john.b.larocca=intel@python.org] On 
Behalf Of Hüseyin Ertugrul
Sent: Monday, February 06, 2017 8:14 AM
To: tutor@python.org
Subject: [Tutor] Basic Tutorial for Python

Hello all,
I am a system engineer and I want to learn python language. I don't know any 
program language and I need tutorial for beginner or for dummies.
By the way I want to see basic example codes for practice.

What is your suggestion for that case.

Thank you for your interest.
___
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] Book recommendation

2016-08-01 Thread John Wong
On Sun, Jul 31, 2016 at 7:14 PM, D Wyatt <fiberfo...@gmail.com> wrote:

> Hello.  I've been a member of this group for a very long time and have
> played with Python for years, but have never gotten past being a beginner
> for various reasons.  I just discovered a very good, free book, that is
> answering many of the questions I have had in the past that I never got
> answers I could understand from you all.  While I appreciate the time and
> effort you put in helping us out, most of you do not remember what you
> didn't used to know, and are often less than helpful because of this.  This
> is not meant as a criticism, but just my observation.
>
>
I think that's a constructive feedback. There are two problems. One is
often the question itself is not well-phrased. The other is remote
communication is a known challenge. I could spend a whole hour doing pair
programming or whiteboarding a solution with someone next to me physically,
but I can't do that over the Internet easily. The person asking the
question may not respond to my reply the next day (timezone difference).
It's a hard problem. I often ask my questions on IRC, and my experience is
also not quite as good as I would hope, although there are enough people to
chime in.

A lot of learning is practice, and then having a mentor available.


> Anyway, this book I found, Learning Python, is well-written and easy to
> understand.  Here is a url to it.https://www.packtpub.com/tech/python.
>
>
Great. I am glad you found one that's helping you. I share the view that
any book is a good book as long as the book is giving correct information.

A few other ones:
* Think Python: How to Think Like a Computer Scientist
* Learning Python by Mark Lutz - I started my journey with this, many years
ago
* Dive Into Python - quite good for beginnger
* Google's Python Class - very gentle introduction
* Python classes online (e.g. the ones available on MIT OCW) - pretty good
if you like slow, lecture-based.
* Python documentation
* Python Essential Reference (for intermediate -> advanced)
* Learn Python the Hard Way (not so much into this, just personal
preferences)

Just my 3.1415 cents.

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


Re: [Tutor] wiped file

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

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


On Thu, Jul 14, 2016 at 11:13 AM, Alan Gauld via Tutor 
wrote:

> On 14/07/16 05:06, Noah Stickel wrote:
> > i open a python file in IDLE (python 3.5.1) and then my computer froze
> > after displaying an error 40 message (i have a DELL PC) and when i
> > restarted it i discovered that the file had been completely wiped clean.
> So
> > i still have the file but there is nothing in it. is there anyway i can
> > restore the contents of this python file?
>
> If you stored the file on the cloud (Dropbox, Google drive etc)
> you may be able to recover old versions. If you run Linux you
> may have a journalling file-system that can recover previous
> versions.
>
> Alternatively you may have committed the file to a version
> control system? In that case simply check out the old version.
>
> And of course if you regularly backup your disks then your
> backup programme can probably retrieve the last saved version.
>
> If none of the above applies then now you know why they should! :-(
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> ___
> Tutor maillist  -  Tutor@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] Hello everybody

2016-06-14 Thread Joseph John
On Mon, Jun 13, 2016 at 11:55 PM, Влад <79099012...@yandex.ru> wrote:

>Hi. I've just begin with Python? I'm 34. Is it late or what? If it is -
> I
>will cut it out. What you think guys?
>**
>
Here  myself 48 crossed, just started taking python step by step
Welcome to the herd


>--**
>** **,
>, PR- Rich PR
>+79099012930
>**
> ___
> 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


[Tutor] Python ODBC driver for Oracle 9

2016-06-13 Thread Joseph John
Hi All,
I am trying to connect Python to Oracle 9 DB, checked for python ODBC
driver for oracle.
What I could find point out to http://cx-oracle.sourceforge.net/ , but this
driver supports from Oracle 11 on wards.
What I need is driver for Pyhton to get connected to Oracle 9.
Did lots of google search, did not find any proper links which is leadeing
to the Oracle9i driver.
And now I am trying to post here to get advice or url on how to get oracle
9 python driver.

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


Re: [Tutor] Command statement work well on interactive mode, which running as pf file it throws error object has no attribute '__getitem__'

2016-06-09 Thread Joseph John
On Thu, Jun 9, 2016 at 12:49 PM, Joseph John <jjk.s...@gmail.com> wrote:

>
>
> On Thu, Jun 9, 2016 at 12:07 PM, Alan Gauld via Tutor <tutor@python.org>
> wrote:
>
>> On 09/06/16 08:33, Joseph John wrote:
>>
>> > Now when I create a *.py  file with all the above steps and run it, I am
>> > getting error
>> > Traceback (most recent call last):
>> >   File "./ReadingDataFrom1X.py", line 10, in 
>> > c = sheet['A1']
>> > TypeError: 'Worksheet' object has no attribute '__getitem__'
>> >
>> >
>> > The contents of  “ReadingDataFrom1X.py” is as follows
>> >  #!/usr/bin/python
>> > import openpyxl
>> > wb = openpyxl.load_workbook('MyTutor.xlsx')
>> > wb.get_sheet_names()
>> > sheet= wb.get_sheet_by_name('SQL Results')
>> > sheet.title
>> > print sheet.title
>> > print sheet['A1']
>>
>> Not according to the error message. It says the error
>> is on the line:
>>
>> c = sheet['A1']
>>
>> But you don't have such a line.
>>
>> So the code you sent us is not the code you are running.
>> Why that may be is the puzzle.
>> Do you have more than one file called ReadingDataFrom1X.py?
>>
>> How are you running the code? Is it from an IDE such as IDLE?
>> Or from the OS command line? That might make a difference.
>>
>> Hi Alan,
> Thanks for the reply.
> I have only the same file, what happened is that I was editing the file in
> a editor for troubleshooting  and when I run the file it was not saved, I
> was trimming the code to the minimum
> Now the program file has only the
> #!/usr/bin/python
> import openpyxl
> wb = openpyxl.load_workbook('MyTutor.xlsx')
> wb.get_sheet_names()
> sheet= wb.get_sheet_by_name('SQL Results')
> sheet.title
> print sheet.title
> print sheet['A1']
>
> and when I run it from the command line, it gets this error
> Traceback (most recent call last):
>   File "./ReadingDataFrom1X.py", line 8, in 
> print sheet['A1']
> TypeError: 'Worksheet' object has no attribute '__getitem__'
>
> I also suspect that my  user python installation has issues.   I will test
> it
> I will test it on another user environment and see how it comes and give
> the feedback on a separate thread
>
>
Tired it on a fresh install of Ubuntu 14.04 64 bit ,
Python version 2.7.6
Same error I am getting
  File "./ReadingDataFrom1X.py", line 8, in 
print sheet['A1']
TypeError: 'Worksheet' object has no attribute '__getitem__

for the code

itsupport@Server-A:~$ cat ReadingDataFrom1X.py
#!/usr/bin/python
import openpyxl
wb = openpyxl.load_workbook('1XDataUserMDN.xlsx')
wb.get_sheet_names()
sheet= wb.get_sheet_by_name('SQL Results')
sheet.title
print sheet.title
print sheet['A1']
#sheet['A1'].value
#c = sheet['A1']
#'The user id is ' + c.value

Thanks
Joseph John




> Thanks a lot
> Joseph John
>
>
>
>>
>>
>> --
>> Alan G
>> Author of the Learn to Program web site
>> http://www.alan-g.me.uk/
>> http://www.amazon.com/author/alan_gauld
>> Follow my photo-blog on Flickr at:
>> http://www.flickr.com/photos/alangauldphotos
>>
>>
>> ___
>> Tutor maillist  -  Tutor@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] Command statement work well on interactive mode, which running as pf file it throws error object has no attribute '__getitem__'

2016-06-09 Thread Joseph John
On Thu, Jun 9, 2016 at 12:07 PM, Alan Gauld via Tutor <tutor@python.org>
wrote:

> On 09/06/16 08:33, Joseph John wrote:
>
> > Now when I create a *.py  file with all the above steps and run it, I am
> > getting error
> > Traceback (most recent call last):
> >   File "./ReadingDataFrom1X.py", line 10, in 
> > c = sheet['A1']
> > TypeError: 'Worksheet' object has no attribute '__getitem__'
> >
> >
> > The contents of  “ReadingDataFrom1X.py” is as follows
> >  #!/usr/bin/python
> > import openpyxl
> > wb = openpyxl.load_workbook('MyTutor.xlsx')
> > wb.get_sheet_names()
> > sheet= wb.get_sheet_by_name('SQL Results')
> > sheet.title
> > print sheet.title
> > print sheet['A1']
>
> Not according to the error message. It says the error
> is on the line:
>
> c = sheet['A1']
>
> But you don't have such a line.
>
> So the code you sent us is not the code you are running.
> Why that may be is the puzzle.
> Do you have more than one file called ReadingDataFrom1X.py?
>
> How are you running the code? Is it from an IDE such as IDLE?
> Or from the OS command line? That might make a difference.
>
> Hi Alan,
Thanks for the reply.
I have only the same file, what happened is that I was editing the file in
a editor for troubleshooting  and when I run the file it was not saved, I
was trimming the code to the minimum
Now the program file has only the
#!/usr/bin/python
import openpyxl
wb = openpyxl.load_workbook('MyTutor.xlsx')
wb.get_sheet_names()
sheet= wb.get_sheet_by_name('SQL Results')
sheet.title
print sheet.title
print sheet['A1']

and when I run it from the command line, it gets this error
Traceback (most recent call last):
  File "./ReadingDataFrom1X.py", line 8, in 
print sheet['A1']
TypeError: 'Worksheet' object has no attribute '__getitem__'

I also suspect that my  user python installation has issues.   I will test
it
I will test it on another user environment and see how it comes and give
the feedback on a separate thread

Thanks a lot
Joseph John



>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> ___
> Tutor maillist  -  Tutor@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


[Tutor] Command statement work well on interactive mode, which running as pf file it throws error object has no attribute '__getitem__'

2016-06-09 Thread Joseph John
Dear All,
I am taking my initial steps to interact Python with excel  files.
I was success in importing the needed modules, and executing steps in
interactive mode .
All my initial commands such as
import openpyxl
wb = openpyxl.load_workbook('MyTutor.xlsx')
wb.get_sheet_names()
sheet= wb.get_sheet_by_name('SQL Results')
sheet.title
print sheet.title
print sheet['A1']

All worked fine
Now when I create a *.py  file with all the above steps and run it, I am
getting error
Traceback (most recent call last):
  File "./ReadingDataFrom1X.py", line 10, in 
c = sheet['A1']
TypeError: 'Worksheet' object has no attribute '__getitem__'


The contents of  “ReadingDataFrom1X.py” is as follows
 #!/usr/bin/python
import openpyxl
wb = openpyxl.load_workbook('MyTutor.xlsx')
wb.get_sheet_names()
sheet= wb.get_sheet_by_name('SQL Results')
sheet.title
print sheet.title
print sheet['A1']

If the statement worked in the interactive mode, it should all work while
executing the file created.
Did some google search, did not come across any valid reason why the error
message is showing.

Would like to request for guidance and feed back, please let me know why
all my  command statements  work on interactive mode and when I run it in a
py file some commands throws error
Thanks
Joseph John
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] import openpyxl throws error in-spite I have python-openpyxl installed.

2016-06-09 Thread Joseph John
Like to give the status
I have messed up my  Python installation, now I remember there was the
default python installation from the OS installed and "Canopy" version
which I had setup in my home directories. Because of this reason import
openpyxl was not working for the shell ( I tested it by logging in as
another user)
In my my user space,I solved it by  giving
pip install openpyxl
Thanks
Joseph John




On Thu, Jun 9, 2016 at 8:51 AM, Joseph John <jjk.s...@gmail.com> wrote:

> Hi All,
> I am trying to explore python, trying to read from excel file.
> I am using Ubuntu 16.04
> As a first step  I mae sure that  I have the package installed
> “python-openpyxl”
> Now in the python command line  when I tried to import openpyxl it throws
> error.
> >>> import openpyxl
> Traceback (most recent call last):
>   File "", line 1, in 
> ImportError: No module named openpyxl
> >>>
> My environment are
> OS Ubuntu 14.04 LTS
> Python 2.7.9 --  64-bit
> python-openpyxl version 1.7.0+ds1-1
>
> I am not able to find why the system throws error when I am importing
> openpyxl, since I have python-openpyxl installed.
>
> Like to request guidance and feedback
> Thanks
> Joseph John
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] import openpyxl throws error in-spite I have python-openpyxl installed.

2016-06-08 Thread Joseph John
Hi All,
I am trying to explore python, trying to read from excel file.
I am using Ubuntu 16.04
As a first step  I mae sure that  I have the package installed
“python-openpyxl”
Now in the python command line  when I tried to import openpyxl it throws
error.
>>> import openpyxl
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named openpyxl
>>>
My environment are
OS Ubuntu 14.04 LTS
Python 2.7.9 --  64-bit
python-openpyxl version 1.7.0+ds1-1

I am not able to find why the system throws error when I am importing
openpyxl, since I have python-openpyxl installed.

Like to request guidance and feedback
Thanks
Joseph John
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] UPDATE, pyhthon+postgre

2016-06-01 Thread john

cursor1.execute("""UPDATE employee SET
name=%s,
add=%s,
add1=%s,
city=%s,
state_county=%s,
country=%s,
basic=%s,
WHERE group_code = %s""" %
(name,add,add1,city,state_county,country,basic,grpCode))

It appears that you are not required to provide any time or date since you 
created a default.  Of course that assumes you want today and now.

If that assumption is wrong then lookup "datetime".  To make life a little easier lookup 
the module "dateutil".  You would use either of those modules to convert your python 
input to the correct output for postgres (actually for any sql database).

Hint:  if the field requires a string you should place quotes around the 
placeholder as in '%s'.

Johnf




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


Re: [Tutor] Best tool for programming interactive games in Python

2016-03-30 Thread john

On 03/30/2016 04:27 AM, wolfrage8...@gmail.com wrote:

I have a few students who are interested in creating interactive games in
Python. We have learned how to use tkinter but we are looking for
something more robust. I tried using pygame 

I recommend Kivy; because then it is easy to take the app from
computer to Phone; which opens the world of touch devices!
Though not specifically made for games it works very well for my
purposes which are a game.


I believe Kivy requires pygame so he would get the same error.

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


Re: [Tutor] Noob: nested if-clauses

2016-01-29 Thread John Wong
On Fri, Jan 29, 2016 at 3:13 PM, Alan Gauld <alan.ga...@btinternet.com>
wrote:

>
> When I first heard that python was white-space sensitive I
> thought, oh no! But now I see it as a huge strength of the
> language. Once you get used to it you will find it helps
> far more than it hinders - just avoid tabs and/or map your
> tab key to spaces.
>
>
Just want to emphasize: use a tool that actually works for you and for the
programming tool. In general, any modern IDE is capable of doing the right
thing. NotePad++ is also capable, but avoid anything like WordPad or
NotePad, if they are still around...
Lastly, most projects I encounter do use 4-space, but some projects (and
notably Google projects internally) would use 2-space, so you almost never
have to worry about mixing 4-space and 2-space in your code. It just happen
that sometimes some people publish code under tab or 2 space and if you
just copy-paste you can run into issues, just FYI for the beginners.

Thanks.

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


[Tutor] How to call the path of an input file

2016-01-21 Thread John Villarraga
I would like to know what is the syntax to call the path of the input file.
Below, my code is calling the input file, but not the path.

Sorry for the inconvenience and thank you for your time.


import sys


path = sys.argv[1]


y = map(str.lower, path.split())
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] how to debug python script which is a parameter of first

2015-11-18 Thread John Spitz
Hi,


Python 3.4

CentOS 6.5


Using IDE eclipse with pydev, how do I debug a python script which is
the parameter of the first script?

For example I'm writing selenium web driver tests in the cloud with
BrowserStack and they have a parallel testing script which is the
first python script following my script and a json file like this:

python3.4  run_parallel_tests.py clickurl.py browsers.json

So in Eclipse, on the run_parallel_tests.py, I have the "Debug
Configurations" > Arguments tab with:
clickurl.py browsers.json


but when adding a breakpoint to the clickurl.py it doesn't work???

Please help,

thanks,

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


Re: [Tutor] Debugging in Python

2015-11-17 Thread John Wong
On Mon, Nov 16, 2015 at 12:48 PM, Alan Gauld <alan.ga...@btinternet.com>
wrote:
>
>
> The correct fix is to exit() from the python3 shell and start it again.
>>
>
> He's tried that and didn't find it satisfactory. That's why
> he wants a "better" workflow.
>
> Alternatively, add some main code at the end of your file and use
>> `python3 hlibert.py`:
>>
>> if __name__ == '__main__':
>>  hilbert(3)
>>
>
> That depends on the nature of his module and the type of testing he wants
> to do. He could, I agree, create a new test file that imports hilbert and
> then add his test code there but that loses the interactivity of a shell
> prompt which may be important.


Yeah, the only way you can actually keep trying is to write some kind of
test script. It doesn't have to be using any testing library. i.e. whatever
code you throw at the console for testing can be written down in another
python file. I call that a scratch pad. Obviously a proper test is
desirable. I too recommend investing time in that.

Doesn't matter whether you use a scratch pad or not, you can use PDB as
your debugger. I often use it to step into my code and hold on the
execution. I often do this when I need to inspect what an object instance
can do...

for example:

main.py

def main():
import pdb; pdb.set_trace()
file_object = some_complex_code_written_by_someone_else()
do_stuff_with_file_object(file_object)

main()


Now when I run main.py, I get an interpreter session inside the PDB
debugger (it's similar to GDB if you have written C/C++ code). I can now
type  dir(file_object), play with file_object, or step inside code to
inspect errors. Hope this helps.

Thanks.

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


Re: [Tutor] Python excel filter

2015-10-26 Thread john

take a look at python-excel

xlwt is what I use. BTW there are others Johnf



On 10/26/2015 05:21 AM, Lucas Mascia wrote:

Hello,

I would like some guidance in a way to filter data from an excel sheet
(.xlsx)

I will be exporting an extensive table from a website with 400x20 infos. In
this sheet, I need to apply 3 or 4 filters and collect the amount of info
it shows then. Eg.:

1 - Export .xlsx from website
2 - Run python to filter
2.1 - Filter by client A
2.2 - Filter by task A
2.3 - Filter by Person A
3 - Repeat filter for different clients, tasks and persons
4 - Collect the amount each person does inside each client.


Please Help guide my through a starting poing

Thank you,

Lucas R. Mascia

 | VIEW MY | 

"It is not the strongest of the species that survives, nor the most
intelligent that survives. It is the one that is most adaptable to change."
  - Darwin.
___
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


[Tutor] Is context manager the answer to synchronous function calls?

2015-09-16 Thread John Wong
Hi

Here is the code:

def create_vm(.):
# returns vm object

def modify_vm(.):
return new vm object

def get_vm_status(.):
return status
# Constraints:
# I cannot modify vm until vm is finished,
# I also cannot modify VM while the VM is being updated.
# Obviously it looks ugly and wrong to include the while
# in my functio. Those are user APIs.

# Straight-forward option
create_vm(...)
status = get_vm_status(...)
while status != "ready":
time.sleep(10)
status = get_vm_status(...)
modify_vm()
while status != "ready":
time.sleep(10)
status = get_vm_status(...)
print("done!")


I was thinking about context manager. But I feel like that's not the
right choice. If you can guess cloning a vm in my program will require
several more function calls. What's your recommendation to accomplish
this?

Thank you.

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


Re: [Tutor] who makes FOR loop quicker

2015-08-06 Thread John Doe

Thank You, Alan.

This is THE FIRST time, when I've got a pleasure from the opponent.
You're maintain status of a thinking human and, as a humble DAOist, I 
always say THANK YOU, when I talk to such a Man.

'Cause wisdom bring us the beauty.

So, what else I can add.
Just a little bit.

It would be great to work with You.
You know, life is so shot..
And any talks don't make it better, alas.

Just we can do.



Alan Gauld 於 08/06/2015 09:54 PM 寫道:

On 06/08/15 14:28, John Doe wrote:

Well, I think, both of us understands that any reference isn't about any
sort of a language. It's about REGISTER = [ALU, FPU, ...]



No thats about the implementation.
The language and implemewntation are completely searate.
There can be many different implementations of a single
language and they all have to follow the semantics defined
by the language but are free to build those semantics
any way they like. (And indeed the different versions
of Python do just that!)


While You're talking about Python - You're talking ONLY about
interpreter for a BYTEcode
Alas, CPU don't speak BYTEcode but BITcode.


Some do. Some speak higher level things. For example
some CPUs speak Forth. And still others don't use binary
at all but use tri-state values. There werte even some
in the early days that used 4-state values. But these
are all implementation details that the programmer
doesn't need to care about.


So, Python can't allocate memory for CPU only for interpreter, which
will ask allocation through underlying-C-language.


Not necessarily. The interpreter could get C to allocate
a huge pool of memory at startup and then use that for
its own allocation/deallocation purposes.


CPU have compiler for Python?


Not yet but it is theoretically possible.
And python would not change if someone built one.


As well as multithreading, for instance, in Python goes to a single
interpreter, but in C - to multiple cores of CPU.


That depends on the implementation. I have a C compiler
that does not do multi-core/thread working. It's an
implementation detail and the C language does not
specify that it must. It all depends on the code that
the compiler generates.


 So Python doesn't have
REAL multithreading, but C - does.


Python does. But not all of its implementations do.
The emulate it instead.  But so far as the programmer is
concerned his code is using threading/concurrency.
He may need to be aware that the implementation is not
honoring his request fully but that doesn't change his
code.


And in my case by means of C-rules Python allocates FOR-loop's list as a
reference.


No, the C implementation might do that. Python as a language
does not. High level languages exist to stop us thinking about
the low level details. The implementation may change, that's not our
problem. Python specifies how the Python execution model works
not how the CPU or the assembler, or the compiler or the
implementer interprets that.

Even C has many different implementations. Some are more efficient
than others. Should we be worrying about which C compiler was used
to build our interpreter? Should we care about whether the CPU
implements multiplication in hardware or in microcode? Or whether it
caches local variables on on-chip cache or uses main memory?

And what about the I/O routines. Do we need to worry about
whether our chosen C compiler is using it's own I/O library,
or calling the BIOS directly?  or using the OS system calls?
These are all implementation details that regular
programmers can, and should, ignore.


And that mistake wastes each iteration of FOR-loop in
unnecessary RE-evaluation of initial-list IN LOGIC STATEMENT, which must
be created only once. Any INITIATIONS make once. 'Cause it sucks
CPU-memory-allocation-cycle.


In the modern world of fast CPUs and memory and where the vast majority
of applications run in virtual machines(JVM, .Net) and the vast majority
of servers run inside virtualized environments (VMWare etc)
none of that is of the slightest concern to me.

If I was writing code for an embedded system it might be more worrisome,
but then I'd probably not be using Python for that.


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


Re: [Tutor] who makes FOR loop quicker

2015-08-06 Thread John Doe
Can You, please, elaborate this ..Passing in Python is different than 
in C or other languages...


'Cause as far as I know - default major Python's implementation CPython 
is written in C.





Joel Goldstick 於 08/05/2015 03:44 PM 寫道:

On Wed, Aug 5, 2015 at 3:53 AM, John Doe z2...@bk.ru wrote:

To pass by reference or by copy of - that is the question from hamlet.
(hamlet - a community of people smaller than a village
python3.4-linux64)

xlist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
i = 0
for x in xlist:
 print(xlist)
 print(\txlist[%d] = %d % (i, x))
 if x%2 == 0 :
 xlist.remove(x)
 print(xlist, \n\n)
 i = i + 1

So, catch the output and help, PLEASE, me improve the answer:
Does it appropriate ALWAYS reevaluate the terms of the list on each
iteration?
But if I want to pass a copy to FOR instead of a reference (as seen
from an
output) and reduce unreasonable reevaluation, what I must to do for
that?


You aren't passing anything.  the for statement is in the same
namespace as the rest of the code.  Passing in python is different
than in C or other languages.

A couple of comments:

setting i = 0, then incrementing at the end of the loop would more
pythonically be done with the enumerate function.
Its generally a bad idea to remove items from and iterable while
interating over it.  I'm guessing that this is what is confusing you.
One way to remove items from a list is to create a new list, and
append items you want to it, skipping the ones you don't.  You don't
really need the index at all since python interation protocol will
walk through the list for you without worrying about index values


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


Re: [Tutor] who makes FOR loop quicker

2015-08-06 Thread John Doe



Well...
Try this look. But I'm just a human and can make mistakes.:))

Passing value - allocates stack and creates NEW memory position.
Passing reference - makes stack pointer pointing to any position.
Dereference - makes stack pointer pointing to any position AND TAKES VALUE.

So, You can count how much in every case does CPU make steps.
And now add to this BIG ARRAY as input for calculation.

Always must keep in mind, that the NAME of variable exists for SCOPE of
You code, but VALUE - for CPU.

So, reference will be always, unless CPU have reached quantum-mechanics



Steven D'Aprano 於 08/06/2015 05:21 PM 寫道:

On Thu, Aug 06, 2015 at 08:57:34AM -0400, Joel Goldstick wrote:

On Thu, Aug 6, 2015 at 4:34 AM, John Doe z2...@bk.ru wrote:

Can You, please, elaborate this ..Passing in Python is different than in C
or other languages...


I hesitate, because this question is usually the fuel of flaming wars.


Very wise :-)

But since I'm not so wise, here are some more comments.



So in short:

C can pass a value or a reference to a value (the address of the place
in memory where the value is stored)


You are correct that C can pass a reference to a value, namely a
pointer. But from the perspective of the C compiler, that pointer *is*
the value, not the thing being pointed at. So passing a pointer as
argument is no different from passing an int or a float or a bool, it's
just a value, and the C compiler will use pass by value on the pointer
itself.

In C, one can use pointers to *simulate* pass by reference. But this is
not the same thing as actual pass by reference. In pass by reference,
you don't pass (a pointer to the variable you want), you pass (the
variable you want), and the compiler does all the magic needed to make
it work.




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


Re: [Tutor] who makes FOR loop quicker

2015-08-06 Thread John Doe
Well, I think, both of us understands that any reference isn't about any 
sort of a language. It's about REGISTER = [ALU, FPU, ...]


That's why reference inevitable.

While You're talking about Python - You're talking ONLY about 
interpreter for a BYTEcode

Alas, CPU don't speak BYTEcode but BITcode.

So, Python can't allocate memory for CPU only for interpreter, which 
will ask allocation through underlying-C-language.


Do I wrong?
CPU have compiler for Python?
As well as multithreading, for instance, in Python goes to a single 
interpreter, but in C - to multiple cores of CPU. So Python doesn't have 
REAL multithreading, but C - does.


And in my case by means of C-rules Python allocates FOR-loop's list as a 
reference. And that mistake wastes each iteration of FOR-loop in 
unnecessary RE-evaluation of initial-list IN LOGIC STATEMENT, which must 
be created only once. Any INITIATIONS make once. 'Cause it sucks 
CPU-memory-allocation-cycle.


Does this point make sense for You?

Joel Goldstick 於 08/06/2015 03:57 PM 寫道:

On Thu, Aug 6, 2015 at 4:34 AM, John Doe z2...@bk.ru wrote:

Can You, please, elaborate this ..Passing in Python is different than in C
or other languages...


I hesitate, because this question is usually the fuel of flaming wars.
So in short:

C can pass a value or a reference to a value (the address of the place
in memory where the value is stored)
Python passes an object -- everything in python is an object.  If the
object is mutable, and the function mutates it, those results will be
seen outside the function.  If the object is immutable, and the
function tries to change its value, a new object is created with the
new value.  Its name is the name given in the parameter list -- not
the name that the function was called with.  When the function
completes, that object is lost since the outer scoped named object
wasn't changed.


'Cause as far as I know - default major Python's implementation CPython is
written in C.


What language is used for its implementation has nothing to do with
its own specification.


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


Re: [Tutor] who makes FOR loop quicker

2015-08-06 Thread John Doe

Thank You, Steven.

I've already written to Your colleague, so You will can see about.

And when I'm saying 'ALLOCATION' I keep in mind the REGISTER, not a 
glossary or thesaurus. Language is created for us, not for CPU.

Do You agree?

Passing VALUE is a time-expensive procedure. Python can't reach 
processor, so any Python's memory allocations don't have sense.


Language always was, is and will be the ONE - compiled bitcode.
Others - just syntax + specially-sphere-applied variations for Your 
pleasure.


Isn't it?

Steven D'Aprano 於 08/06/2015 04:45 PM 寫道:

On Thu, Aug 06, 2015 at 11:34:51AM +0300, John Doe wrote:


Can You, please, elaborate this ..Passing in Python is different than
in C or other languages...


Argument passing in Python is:

- different to Perl, C, Scala, Algol and Pascal;

- the same as Ruby, Lua, Applescript and Javascript;

- the same as Java boxed values (object);

- different to Java unboxed values (machine types).


In C, all values are passed by value. When you pass an argument to a
function, the C compiler makes a copy of that value and passes the
value.

In Pascal, values can be passed by value (like C), or by reference.

The simplest demonstration of pass-by-reference is to write a swap
procedure. In Python terms:


# This does not actually work in Python.
def swap(a, b):
 tmp = a
 a = b
 b = tmp

x = 23
y = 42
swap(x, y)
print x, y  # prints 42 23

z = 19
swap(x, z)
print x, z  # prints 19 42


You *cannot* write a swap procedure like this in Python. The closest you
can do is write a function that returns the two values, then assign
them:

def swap(a, b):
 return b, a

x, y = swap(x, y)  # this works

but that is not pass by reference.

In Pascal, you can write such a swap procedure.

Scala and Algol use pass by name, and pass by value. This page explains
pass by name in Scala, and how it differs from pass by value:

http://alvinalexander.com/source-code/scala/simple-scala-call-name-example

In Java, unboxed values (not objects, low-level machine ints and floats)
are passed by value, like C.

Python, Ruby, Javascript, Lua, Java boxed values (objects), and many
other languages, all use the same passing style. This has a number of
names:

- pass by object;
- pass by sharing;
- pass by object sharing;

Some people (especially Ruby programmers) call it pass by reference
but that is wrong. Others (especially Java programmers) call it call by
value, where the value is a reference which is technically correct but
too long. Another name is call by value/pass by reference, which is
just confusing.

See also:

https://en.wikipedia.org/wiki/Evaluation_strategy

In pass by object sharing, the argument is evaluated but *not* copied.
Since the argument is not copied, it is not pass-by-value. Inside the
function, you can modify the object, and since it is not a copy, the
original sees the changes. But *assignment* to the local variable inside
the function does not affect the caller's variable, so it is not
pass-by-reference.

To summarise:

Pass by value:
- Argument is copied? YES
- Assignment inside function affects original? NO
- Mutation of argument inside function affects original? NO

Pass by reference:
- Argument is copied? NO
- Assignment inside function affects original? YES
- Mutation of argument inside function affects original? YES

Pass by object sharing:
- Argument is copied? NO
- Assignment inside function affects original? NO
- Mutation of argument inside function affects original? YES




'Cause as far as I know - default major Python's implementation CPython
is written in C.


That is irrelevent. The argument passing strategy of a language is part
of the language itself, not the implementation language.

C does not allow variables to change type. But Python does. You cannot
do this in C:

x = 23  # x is an integer
x = foo  # and now it is a string

so clearly the behaviour of a programming language is not always the
same as that of the implementation language.




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


[Tutor] who makes FOR loop quicker

2015-08-05 Thread John Doe
To pass by reference or by copy of - that is the question from hamlet. 
(hamlet - a community of people smaller than a village python3.4-linux64)


xlist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
i = 0
for x in xlist:
print(xlist)
print(\txlist[%d] = %d % (i, x))
if x%2 == 0 :
xlist.remove(x)
print(xlist, \n\n)
i = i + 1

So, catch the output and help, PLEASE, me improve the answer:
Does it appropriate ALWAYS reevaluate the terms of the list on each 
iteration?
But if I want to pass a copy to FOR instead of a reference (as seen from 
an output) and reduce unreasonable reevaluation, what I must to do for that?

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


Re: [Tutor] about the gui development

2015-06-13 Thread john

Interesting question - what will be the end platform.

If you really want a python solution:
Tablets. phones, desktops - Kivy (very promising)
Tablets. phones, desktops - PyQt
Desktops - wxPython, tk, Dabo (python 2.7 at the moment)

All the other GUI frameworks either have a very small following or are 
dying (my opinion of course).


If you are not concerned with what language is used:
Consider all the web frameworks.
Several of the web frameworks work on the desktops, and are browser 
friendly.  Atom/electron (not sure about the name)

but in general web frameworks (no matter which one) is all about browsers.

Johnf

On 06/13/2015 10:15 AM, Laura Creighton wrote:

The final thing to consider is, do you really want to do gui programming
at all, or would you be happier developing something that runs in a browser?
If that has appeal, well, you guessed it, we have lots of browser
frameworks, as well.


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


[Tutor] How to do a PyQt VTK application in Python26

2015-02-19 Thread John R
Is it possible to make a PyQt VTK application using Python26?

My first sample Qt VTK application is not running!! And my VTK compiled Bin
folder is python 26 compiled dll files and Win32 bit

The error is


Traceback (most recent call last):
  File EmbedInPyQt.py, line 5, in module
from PyQt4 import QtCore, QtGui
ImportError: DLL load failed: %1 is not a valid Win32 application.


Due to this bug I searched in internet for PyQt4 Installer downloading
versions and those are supporting
Python34 and higher as PyQt4 exe
(http://www.riverbankcomputing.com/software/pyqt/download)

 Is there any way can I run my sample QT-VTK application using python 26?
OR should I go after python 34??

could anyone please help me soon?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to do a PyQt VTK application in Python26

2015-02-19 Thread John R
Thanks Alan for suggesting Python 3.4, that seems to be correct but I am
searching for any possibilities with python 2.6

Thank you guys for responding, I should try some other forum.
On 19 Feb 2015 16:37, Alan Gauld alan.ga...@btinternet.com wrote:

 On 19/02/15 09:54, John R wrote:

 Is it possible to make a PyQt VTK application using Python26?


 No idea. What is a PyQt VTK application?
 I know what PyQt is but never heard of VTK

 Is there a web site? Does it have a support area?
 Perhaps they can help?

  The error is

 Traceback (most recent call last):
File EmbedInPyQt.py, line 5, in module
  from PyQt4 import QtCore, QtGui
 ImportError: DLL load failed: %1 is not a valid Win32 application.


 It sounds like you may have a dependency issue and need to
 install something. But since its not Python or its standard
 library I can't guess what. The best place to ask will be
 a PyQt and/or a VTK forum.

  Due to this bug I searched in internet for PyQt4 Installer downloading
 versions and those are supporting
 Python34 and higher as PyQt4 exe
 (http://www.riverbankcomputing.com/software/pyqt/download)

   Is there any way can I run my sample QT-VTK application using python 26?
 OR should I go after python 34??


 Its unlikely that a version for 3.4 will work on 2.6. There are too many
 incompatible differences. Try using Python 3.4.


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


 ___
 Tutor maillist  -  Tutor@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


[Tutor] Michael Dawson Chapter 6 Challenge 4

2014-11-23 Thread John Feleppa
Dear all,

Has anyone solved the fourth challenge in Chapter 6 of Michael Dawson's
book, 'Python Programming for the absolute beginner'?

The challenge: 'Write a new *computer_move()* function for the Tic-Tac-Toe
game to plug the hole in the computer's strategy.  See if you can create an
opponent that is unbeatable!'

The function is as follows:

def computer_move(board, computer, human):
Make computer move.
# make a copy to work with since function will be changing list
board = board[:]
*# the best positions to have, in order*
*BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7)*

print(I shall take square number, end= )

# if computer can win, take that move
for move in legal_moves(board):
board[move] = computer
if winner(board) == computer:
print(move)
return move
# done checking this move, undo it
board[move] = EMPTY

# if human can win, block that move
for move in legal_moves(board):
board[move] = human
if winner(board) == human:
print(move)
return move
# done checkin this move, undo it
board[move] = EMPTY

*# since no one can win on next move, pick best open square*
*for move in BEST_MOVES:*
*if move in legal_moves(board):*
*print(move)*
*return move*

I believe a solution lies in the final lines, which I put in bold, and in
the BEST_MOVES tuple, which is also in bold.  As in, it looks through the
list of best moves in order regardless of what move the opponent has made.
So it just dumbly selects the next item in the tuple instead of responding
to the opponent's move.  So, for example, the following sequence shows the
computer's weakness:

a. the opponent goes first in a corner, in Square 0
b. the computer picks the centre, in Square 5
c. the opponent picks the opposite corner, Square 8
d. the weakness - the computer picks the corner, Square 2, which will be
easily countered by the opponent going in Square 6, instead of the smarter
Square 1, which will result in a draw, and not a loss.

HAS ANYONE SOLVED THIS?  I'd much appreciate help here.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Iterating Lines in File and Export Results

2014-10-03 Thread John Doe
Alan, Peter, et al:

Thank you all very much! Staring at this problem for hours was driving
me crazy and I am very appreciative for your guys' time in looking
into my silly error -- I have thoroughly reviewed both the responses
and it makes perfect sense (*sigh of relief*).



On Thu, Oct 2, 2014 at 6:08 PM, Peter Otten __pete...@web.de wrote:
 John Doe wrote:

 Hello List,
 I am in need of your assistance. I have a text file with random words
 in it. I want to write all the lines to a new file. Additionally, I am
 using Python 2.7 on Ubuntu 12.04:

 Here is my code:

 def loop_extract():
 with open('words.txt', 'r') as f:
 for lines in f:

 The name `lines` is misleading, you are reading one line at a time.

 #print lines (I confirmed that each line is successfully
 #printed)
 with open('export.txt', 'w') as outf:
 outf.write(lines)
 #outf.write(lines)
 #outf.write('{}\n'.format(lines))
 #outf.write('{}\n'.format(line for line in lines))


 For some reason, the second file only contains the last line from the
 original file -- I have tried multiple variations (.read, .readlines,
 .writelines, other examples preceded by comment from above and many
 more) and tried to use the module, fileinput, but I still get the same
 results.

 Every time the line

 with open('export.txt', 'w') as outf:

 is executed the file export.txt is truncated:

 https://docs.python.org/dev/library/functions.html#open

 To avoid the loss of data open the file once, outside the loop:

 with open(words.txt) as infile, open(export.txt, w) as outfile:
 for line in infile:
 outfile.write(line)


 I do understand there is another way to copy the file over, but to
 provide additional background information on my purpose -- I want to
 read a file and save successful regex matches to a file; exporting
 specific data. There doesn't appear to be anything wrong with my
 expression as it prints the expected results without failure. I then
 decided to just write the export function by itself in its basic form,
 per the code above, which the same behavior occurred;

 That is a good approach! Reduce the code until only the source of the
 problem is left.

 only copying the
 last line. I've googled for hours and, unfortunately, at loss.

 I do that too, but not for hours ;)

 I want to read a file and save successful regex matches to a file;
 exporting specific data.

 An experienced user of Python might approach this scenario with a generator:

 def process_lines(infile):
 for line in infile:
 line = process(line) # your line processing
 if meets_condition(line): # your filter condition
 yield line

 with open(words.txt) as infile:
 with open(export.txt, w) as outfile:
 outfile.writelines(
 process_lines(infile))


 ___
 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


[Tutor] Iterating Lines in File and Export Results

2014-10-02 Thread John Doe
Hello List,
I am in need of your assistance. I have a text file with random words
in it. I want to write all the lines to a new file. Additionally, I am
using Python 2.7 on Ubuntu 12.04:

Here is my code:

def loop_extract():
with open('words.txt', 'r') as f:
for lines in f:
#print lines (I confirmed that each line is successfully printed)
with open('export.txt', 'w') as outf:
outf.write(lines)
#outf.write(lines)
#outf.write('{}\n'.format(lines))
#outf.write('{}\n'.format(line for line in lines))


For some reason, the second file only contains the last line from the
original file -- I have tried multiple variations (.read, .readlines,
.writelines, other examples preceded by comment from above and many
more) and tried to use the module, fileinput, but I still get the same
results.

I do understand there is another way to copy the file over, but to
provide additional background information on my purpose -- I want to
read a file and save successful regex matches to a file; exporting
specific data. There doesn't appear to be anything wrong with my
expression as it prints the expected results without failure. I then
decided to just write the export function by itself in its basic form,
per the code above, which the same behavior occurred; only copying the
last line. I've googled for hours and, unfortunately, at loss.

Thank you in advance for your help!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] printing all text that begins with 25

2014-10-02 Thread John Doe
Hello,

If you want to accomplish what you are looking for within linux
(perhaps a bash script, instead?):

$ hamachi list | grep -oP '25\.\d+\.\d+\.\d+'
25.0.0.0
25.255.255.255

For your python script, you want to group your regex:
reg = re.compile(r'(25\.\d+\.\d+\.\d+)', re.MULTILINE)

So when you call group(1) or group(0), it'll grab just the addresses.


On Thu, Oct 2, 2014 at 12:33 PM, David Rock da...@graniteweb.com wrote:
 * Bo Morris crushe...@gmail.com [2014-10-02 11:41]:
 Hello all, hope everyone is doing well.

 When I run the linux command hamachi list i get something along the lines
 of the following output

087-888-279   Pandora25.x.x.xxx   alias: not 
 set
096-779-867   AM1LaptopBD-PC25.x.x.xxx   alias: not set
097-552-220   OWS-Desktop 125.0.0.0  alias: not set
099-213-641   DESKTOP 25.0.0.0  alias: not set

 I am trying to write a python script that will run the above command and
 only print out the IP's that begin with 25. How do I strip out all other
 text except for the IP's that begin with 25?

 There are a few assumptions that need to be made, for starters.

 Is the format always the same (ie, is the IP address always in column 3
 separated by whitespace)?  Looking at the line with OWS-Desktop 1, the
 answer is no.  That complicates things a bit.  If it was true, you could
 use the string split method to get column 3.  Maybe the fields are
 separated by a tab?

 A regex may be possible, but you will have similar issues to using
 split.

 I'm also assuming it's possible for there to be IP addresses that do not
 start with 25. Are you looking to isolate those?

 It's not necessary to write out to a file first.  You can get the output
 from commands and work on it directly.

 Another approach would be to change the command you are running.  I've
 never heard of hamachi list before; does it have any commandline options
 to display only IP addresses?

 --
 David Rock
 da...@graniteweb.com
 ___
 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] GUI development with Python 3.4.1

2014-09-18 Thread john

On 09/18/2014 06:07 AM, Juan Christian wrote:
On Wed, Sep 17, 2014 at 2:01 PM, Juan Christian 
juan0christ...@gmail.com mailto:juan0christ...@gmail.com wrote:


I need to develop a GUI for my Python pogram, I already read the
GuiProgramming page (https://wiki.python.org/moin/GuiProgramming).
For me, the best so far was 'gui2py'.

The problem is that I need a simple C#/Java-ish GUI builder,
that is easy and simple, coding all the GUI by hand is boring, I
prefer to focus on the logic, on the actual program code, than
coding the GUI.

Anyone here already used 'gui2py'
(https://github.com/reingart/gui2py)? Any other good alternatives?


Anyone?


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Dabo has a designer (currently moving to support wxPython 3.x). That 
said, the link you first provided suggested there was a designer for 
gui2py?


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


Re: [Tutor] How to Create Webpage with Python

2014-07-25 Thread John Cast
Hey everyone,

So against all of your better judgement I went ahead and implemented my
server through the simpleHTTPServer in python and used win32com to hook up
to excel to widen the existing excel columns and then call SaveAs() into
.htm format (basically programmatically doing the save as webpage format
in excel that you can do by hand) and then opening the server up in the
directory that I save these output HTML files.
This is a side project at work and the people that gave it to were quite
pleased with how it looked.  However, their enthusiasm led them to want
even more functionality.  This functionality includes making a couple of
graphs for each sheet in the excel workbook and serving these graphs up as
well as being able to store/edit comments for each row of each sheet in the
workbook once it's served up (each row of each sheet is basically a work
task with some information for it found in the columns).

Now the tricky part...
This script will eventually be used to routinely pull down information
found on some website (which it can already do), probably in a cron job.
 Doing this will find the most recent information for each excel sheet.  I
have to be able to keep track of this information over time and update the
graphs for each sheet accordingly (some rows may be deleted, some rows may
have edited comments (always last column) and some rows maybe completely
new, maybe even whole sheets will be gone or added as well). All of the
information in the excel sheets is text.  I would be counting text
occurrences for the graphs.

Since I cheated and used win32com to access excel and have it do the dirty
work of saving the excel workbook into HTML format I don't really have
direct access to the HTML creation and don't have a good way of storing
data pertaining to each sheet (i.e. graph information and comments for each
row of each sheet).  So I am thinking I am going to have to backtrack in my
work and take a new approach.

Here come my questions/ideas and I'd like to hear all of your thoughts on
them if you have time:

1) What are your ideas on how best to accomplish all of this given where I
have stated my project is at?

2) My current idea is to investigate some kind of database, probably mysql
so that I can store the information for each excel sheet.  Is this
smart/easy/possible/efficient?  I am guessing it might be possible to store
each excel sheet (or instead maybe the two graphs for each sheet and the
row/comment relations so as to only keep around what I really need) under a
name identifier as separate entities in the mysql database.  Is this
smart/easy/possible/efficient to do?

3) I am guessing I have to go back and redo how I generate my HTML.  Right
now I generate an index.html file that simply displays some text and then
has a hyperlink to the excel generated webpage version of the original
excel workbook.  The index.html is generated in python by printing it to a
new index.html file every time the script is run.  I would like to keep the
look of how excel generates each sheet into HTML (basically it just looks
like the exact excel sheet but on the web) while displaying two graphs for
each each sheet.  I was thinking I could simply insert the links for the
graphs into the index.html page or insert the links for the graphs into
their respective sheet's HTML page or simply display the graphs directly on
their respective sheet's HTML page.  What sounds reasonable/easiest here?

4) I need to somehow allows the comment cell in each row to be interactive
in the sense that it needs to be editable when it is displayed as well as
be persistent (stored).  I am at a bit of a loss as where to begin with
this.

5) Will I need to switch to a new server? e.g. Django, apache?  Or can I
keep doing things in the simpleHTTPServer within python?

Mind you that other than this project I have very little experience with
any of this.  That said I am looking for a fair balance of efficiency and
ease to accomplish all of this.  My time frame is about 3 weeks.

I welcome any help/tips/opinions that you all can offer.

Thanks


On Tue, Jul 15, 2014 at 12:46 PM, Alan Gauld alan.ga...@btinternet.com
wrote:

 On 15/07/14 17:48, John Cast wrote:

  1) How does one automate the save as webpage from python?


 It is possible using COM objects and the pywin32 library.
 However that's rarely the best way to approach things.
 But if you insist...

 Here is a short example of opening a FileOpen dialog...

 import win32com.client as com
 filepath = rD:\Whatever\You\want
 fileopen = 1  # change to whatever code you need of 1-4
 app = com.Dispatch(Excel.Ap[plication)
 app.Visible = True
 fd - app.FileDialog(fileopen)
 fd.InitialFileName = filepath
 fd.Title = Open a file
 if fd.Show() == -1:
fd.Execute()

 I'll let you use your imagination (and the MSDN web site?) to
 work out how to do a SaveAs dialog and populate it with the
 right values.

 The last 2 lines check if the user actually hit the Open or OK
 button

Re: [Tutor] How to Create Webpage with Python

2014-07-15 Thread John Cast
Hey everyone,

I really appreciate all of the help you given me.
I am making progress, however I have reached a problem I'm not sure how
best to tackle and would like someone with more experience with excel and
python to lend their knowledge/opinion before I dive in further.

I have two questions:
1) I'd like to be able to do a 'save-as web page' in python for my excel
workbook.  I tried this by hand and everything looks good EXCEPT that the
header cells sometimes were too narrow (because the person who created the
workbook didn't expand out each column enough sometimes) and thus blocked
some of the text in them occasionally.
Is it possible to do a 'save-as web page' for the workbook in python?

2)  So (assuming I can do this 'save-as webpage' in code) I need to go
through each sheet in the workbook and change each column's width so that
it can hold all of its text.  I realize that xlrd is for reading and xlwt
is for writing and there is xutils for particular combinations of both
reading and writing.  However, nothing to do quite what I've stated as far
as I can tell (so far).  I currently open the workbook I want to modify
using the open_workbook functionality in the xlrd module.  As I understand
it I need the xlwt module to write to this workbook, but since it's opened
in xlrd do I just open the same workbook in xlwt again?  If so does each
module simply have a handle to the same file?

NOTE: I'm basically just trying to present my excel workbook on the web as
it's shown in excel (retaining as much formatting as possible).

Thanks again,
John


On Sat, Jul 12, 2014 at 4:32 PM, Danny Yoo d...@hashcollision.org wrote:

 Hi Chris,

 Yikes.  I need to say that as, for disclosure: I work at Google.  I do
 not work on the App Engine team, but I need to acknowledge my
 potential conflict-of-interest, and I apologize for not stating this
 in my reply.
 ___
 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] How to Create Webpage with Python

2014-07-15 Thread John Cast
Yes, that's exactly what I'm trying to do.  However, when testing this out
manually like I pointed to above, the output of the save as feature freezes
the column widths.  This would be fine except that not all of the column
widths are expanded so that all of the text can be seen (at the moment I
don't have any control over how the sheets are made, just access to them),
so when the save as feature does its thing, some text is blocked.
That's why I need a way to go through each sheet and adjust the widths and
then programmatically do a save as webpage for all of them from python.

So I guess this brings me back to my previous post's questions:

1) How does one automate the save as webpage from python?

2) What is the most straightforward way to adjust the column widths of the
existing excel sheets?

Any hints/guidance/answers are greatly appreciated.

Thanks again


On Tue, Jul 15, 2014 at 1:20 AM, Chris “Kwpolska” Warrick 
kwpol...@gmail.com wrote:


 On Jul 15, 2014 3:17 AM, John Cast jdc...@stanford.edu wrote:
 
  Hey everyone,
 
  I really appreciate all of the help you given me.
  I am making progress, however I have reached a problem I'm not sure how
 best to tackle and would like someone with more experience with excel and
 python to lend their knowledge/opinion before I dive in further.
 
  I have two questions:
  1) I'd like to be able to do a 'save-as web page' in python for my excel
 workbook.  I tried this by hand and everything looks good EXCEPT that the
 header cells sometimes were too narrow (because the person who created the
 workbook didn't expand out each column enough sometimes) and thus blocked
 some of the text in them occasionally.
  Is it possible to do a 'save-as web page' for the workbook in python?
 
  2)  So (assuming I can do this 'save-as webpage' in code) I need to go
 through each sheet in the workbook and change each column's width so that
 it can hold all of its text.  I realize that xlrd is for reading and xlwt
 is for writing and there is xutils for particular combinations of both
 reading and writing.  However, nothing to do quite what I've stated as far
 as I can tell (so far).  I currently open the workbook I want to modify
 using the open_workbook functionality in the xlrd module.  As I understand
 it I need the xlwt module to write to this workbook, but since it's opened
 in xlrd do I just open the same workbook in xlwt again?  If so does each
 module simply have a handle to the same file?
 
  NOTE: I'm basically just trying to present my excel workbook on the web
 as it's shown in excel (retaining as much formatting as possible).
 
  Thanks again,
  John

 If you want to have output that's very close to Excel’s, why not just use
 Excel’s save as webpage capabilities? You can automate that, with Python or
 something else (like Excel macros or Windows-specific automation software).
 It's much easier to do it this way, and it guarantees good output without
 much effort.

 --
 Chris “Kwpolska” Warrick http://chriswarrick.com/
 Sent from my SGS3.


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


Re: [Tutor] How to Create Webpage with Python

2014-07-15 Thread John Cast
Yes, that pretty well sums up what I would like to do.  I can't show the
input here, but it is saved as an xlsx file (this is proving problematic
for me already since I'm using python 3.4 and it doesn't fully support this
format yet...I may have to switch to python 2 for better support).
I don't think this will require very much code, but since I am new to the
language and having trouble finding documentation on methods such as
saveAs, it's proving difficult.

Thanks again


On Tue, Jul 15, 2014 at 10:39 AM, Joel Goldstick joel.goldst...@gmail.com
wrote:




 On Tue, Jul 15, 2014 at 12:48 PM, John Cast jdc...@stanford.edu wrote:

 Yes, that's exactly what I'm trying to do.  However, when testing this
 out manually like I pointed to above, the output of the save as feature
 freezes the column widths.  This would be fine except that not all of the
 column widths are expanded so that all of the text can be seen (at the
 moment I don't have any control over how the sheets are made, just access
 to them), so when the save as feature does its thing, some text is blocked.

 That's why I need a way to go through each sheet and adjust the widths
 and then programmatically do a save as webpage for all of them from python.

 So I guess this brings me back to my previous post's questions:

 1) How does one automate the save as webpage from python?

 2) What is the most straightforward way to adjust the column widths of
 the existing excel sheets?

 Any hints/guidance/answers are greatly appreciated.

 Thanks again


 I see you have received guidance as to web hosting, but I have questions
 about the excel side.

 Does the program that creates the spreadsheet produce an xls formatted
 file, or a csv file?

 You seem to indicate that want to write python to actually perform the
 steps you would do if you were editing the spreadsheet in person:
   1. open the file in excel
   2. click on the various columns to make them expand to see the data
 properly
   3. Save as some file in html format.
   4. put that file in some location to be read by your web server.

 If your files are csv you can use python csv file to read them, then
 create the web page by inserting each value in an appropriately created
 html template (with table markup).

 Can you show the actual input file here? and the markeup for your output
 file as well?

 If you are doing this on a windows machine, there may be a module that
 manipulates .xls files directly using something they used to call .com
 objects, I can't help you there except to say that seems like a bad way to
 go.  Computer programs are best written to solve a problem, but not usually
 to act as a stand in for the steps that would be used to solve that problem
 as a user by hand.





 ___

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




 --
 Joel Goldstick
 http://joelgoldstick.com

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


Re: [Tutor] How to Create Webpage with Python

2014-07-10 Thread John Cast
Thanks everyone for the tremendous and speedy support!

Here's a bit more information that I think would be useful:

I will be hosting this (for the foreseeable future at least) on my desktop.
There is another python script already written that generates the excel
spreadsheets (I did not write this).  That script will be ran on a fairly
frequent basis so the webpage will constantly have its information updated.

I'm in unfamiliar territory with the web stuff, but it sounds so far like I
will generate an HTML doc every time I run my script and then somehow turn
that HTML doc into a static site?  (My terminology is weak here I'm sure)
I use the term wiki very loosely.  I'm basically just wanting to write my
excel information (possibly with some formatting) to one page (or maybe one
page per excel sheet...not really sure...more worried about getting the
basics for right now) that others can then navigate to.  Interaction with
this page, is at the moment, unnecessary.

So this is what I have gathered from all of your input so far:

Excel - I didn't have a module in mind just yet, but it looks like xlrd is
my best bet

Web - Currently it looks like maybe static HTML page(s) generated every
time my script is run is the right way to go?
  It sounds like I need a server on my desktop?
  I need to create a site and host/serve this somehow using my
server?
  I don't need a webframework to do this?
  Need some mechanism to get these HTML page(s) to my site?


I welcome any further input anyone is willing to give!

Thanks


On Wed, Jul 9, 2014 at 3:16 PM, Mark Lawrence breamore...@yahoo.co.uk
wrote:

 On 09/07/2014 19:26, John Cast wrote:

 First, please forgive any ignorance in my post here as I am not good
 with HTML and new to python.

 I have a bunch of excel spreadsheets (all in the same format) that I am
 writing a python script to go through and pick out some information and
 post to a wiki page. I'm new to python and have gone through some basic
 tutorials. I feel confident that I can figure out how to read an excel
 spreadsheet in python. However, I am feeling a bit overwhelmed with
 figuring out how to do the web stuff in python. The webpage doesn't
 exist yet and I have envisioned that the wiki webpage is created once
 and then simply update it every time the script is run. However, I don't
 know much about how persistence works with webpages.

 I have two main questions:

 1) Considering the webpage doesn't exist yet, do I need to 'serve' or
 'post' a webpage (as was brought up below)?

 2) How do I create this wiki webpage? and does this happen in python
 every time the script is run?

 3) How do I send my data to this webpage?

 I don't have to have full blown answers here, just a link or advice or
 anything to help me with navigating all of the information out there on
 Google.

 Thanks


 For the excel side see http://www.python-excel.org/

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

 Mark Lawrence

 ---
 This email is free from viruses and malware because avast! Antivirus
 protection is active.
 http://www.avast.com



 ___
 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] How to Create Webpage with Python

2014-07-10 Thread John Cast
Thanks everyone again for the great support.

Right now I have a very basic server running using the http module (I'm
using python 3).  My next step is to generating the HTML pages so that the
formatting of the excel docs stays pretty much the same except that it gets
shown on the web.

For future reference (assuming everything else goes well) how do I procure
a more permanent server (i.e. one that doesn't run on my machine so that I
can turn it off and still be able to visit my pages)?  I'm hearing Apache
and so forth being thrown around (I've read up a little on it) but it seems
those would still run on my local computer.
What am I missing?

I'll keep everyone posted on how the excel parsing turns out.

Thanks again


On Thu, Jul 10, 2014 at 10:24 AM, Chris “Kwpolska” Warrick 
kwpol...@gmail.com wrote:

 On Thu, Jul 10, 2014 at 6:40 PM, Alex Kleider aklei...@sonic.net wrote:
  If all you want is to check how your 'site' looks perhaps it'd be much
  simpler to simply point your browser to your parent html file rather than
  set up a server machine to serve it:
  file:///home/yourusername/yoursubdirectory/index.html
  It'll look exactly the same as it would if you were running it on a
 server.
  (or am I missing something?)

 JavaScript may not work.  The same might also happen with links and
 resources using the // scheme (//example.com/ instead of
 http://example.com/)

 For local testing, use

 python -m SimpleHTTPServer

 or, if you’re on Python 3,

 python3 -m http.server

 --
 Chris “Kwpolska” Warrick http://chriswarrick.com/
 PGP: 5EAAEA16
 stop html mail | always bottom-post | only UTF-8 makes sense
 ___
 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


[Tutor] How to Create Webpage with Python

2014-07-09 Thread John Cast
First, please forgive any ignorance in my post here as I am not good with
HTML and new to python.

I have a bunch of excel spreadsheets (all in the same format) that I am
writing a python script to go through and pick out some information and
post to a wiki page. I'm new to python and have gone through some basic
tutorials. I feel confident that I can figure out how to read an excel
spreadsheet in python. However, I am feeling a bit overwhelmed with
figuring out how to do the web stuff in python. The webpage doesn't exist
yet and I have envisioned that the wiki webpage is created once and then
simply update it every time the script is run. However, I don't know much
about how persistence works with webpages.

I have two main questions:

1) Considering the webpage doesn't exist yet, do I need to 'serve' or
'post' a webpage (as was brought up below)?

2) How do I create this wiki webpage? and does this happen in python every
time the script is run?

3) How do I send my data to this webpage?

I don't have to have full blown answers here, just a link or advice or
anything to help me with navigating all of the information out there on
Google.

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


Re: [Tutor] Storing dictionary value, indexed by key, into a variable

2014-04-05 Thread John Aten
I read the article on data driven programming that Danny linked too, and did 
some additional looking around. I couldn't find anything directly using Python, 
but I got an idea of the concept and went crazy with it. This may still be off 
the mark, but I created a complex combination of lists and dictionaries to 
represent each individual instance of each demonstrative (starting only with 
one): 

that_those = [ [ [ {'nom': 'ille', 'clue': 'That/Those, Singular, Masculine 
Nominative'},
{'gen': 'illīus', 'clue': 'That/Those, 
Singular, Masculine Genitive'},
{'dat': 'illī', 'clue': 'That/Those, Singular, 
Masculine Dative'},
{'acc': 'illum', 'clue': 'That/Those, Singular, 
Masculine Accusative'},
{'abl': 'illō', 'clue': 'That/Those, Singular, 
Masculine Ablative'} ], [{'nom': 'illī', 'clue': 'That/Those, Plural, Masculine 
Nominative'},
{'gen': 'illōrum', 'clue': 'That/Those, Plural, Masculine 
Genitive'},
{'dat': 'illīs', 'clue': 'That/Those, Plural, Masculine 
Dative'},
{'acc': 'illōs', 'clue': 'That/Those, Plural, Masculine 
Accusative'},
{'abl': 'illīs', 'clue': 'That/Those, Plural, Masculine 
Ablative'} ] ], [ [ {'nom': 'illa', 'clue': 'That/Those, Singular, Feminine 
Nominative'},
{'gen': 'illīus', 'clue': 'That/Those, Singular, Feminine 
Genitive'},
{'dat': 'illī', 'clue': 'That/Those, Singular, Feminine 
Dative'},
{'acc': 'illam', 'clue': 'That/Those, Singular, 
Feminine Accusative'},
{'abl': 'illā', 'clue': 'That/Those, Singular, 
Feminine Ablative'} ], [ {'nom': 'illae', 'clue': 'That/Those, Plural, Feminine 
Nominative'},
{'gen': 'illārum', 'clue': 'That/Those, Plural, 
Feminine Genitive'},
{'dat': 'illīs', 'clue': 'That/Those, Plural, Feminine 
Dative'},
{'acc': 'illās', 'clue': 'That/Those, Plural, 
Feminine Accusative'},
{'abl': 'illīs', 'clue': 'That/Those, Plural, Feminine 
Ablative'} ] ]
, [ [ {'nom': 'illud', 'clue': 'That/Those, Singular, Neuter Nominative'},
{'gen': 'illīus', 'clue': 'That/Those, Singular, Neuter 
Genitive'},
{'dat': 'illī', 'clue': 'That/Those, Singular, Neuter 
Dative'},
{'acc': 'illud', 'clue': 'That/Those, Singular, Neuter 
Accusative'},
{'abl': 'illō', 'clue': 'That/Those, Singular, Neuter 
Ablative'} ], [ {'nom': 'illa', 'clue': 'That/Those, Plural, Neuter 
Nominative'},
{'gen': 'illōrum', 'clue': 'That/Those, Plural, Neuter 
Genitive'},
{'dat': 'illīs', 'clue': 'That/Those, Plural, Neuter 
Dative'},
{'acc': 'illa', 'clue': 'That/Those, Plural, Neuter 
Accusative'},
{'abl': 'illīs', 'clue': 'That/Those, Plural, Neuter 
Ablative'} ] ] ]

Now, this is a big mess, for sure, but it seems possible that it is abstract 
enough that I could reuse the same logic and just switch out the data to make 
different types of similar programs. Also, I can write a script to populate 
this structure to construct a program to drill any type of word that is 
declined by gender, number and case. I can call each item pretty easily like 
this: 

question_to_be_dispalyed_to_user = 
that_those[gender][number][q_and_a][clue]
answer_to_that_question = that_those[gender][number][q_and_a][case]

Where gender, number, q_and_a, and case follow Peter's suggestion:

cases = ['nom', 'gen', 'dat', 'acc', 'abl']
case = random.choice(cases)

The complete code will follow, but I have a spooky new problem. When I try to 
run the following code, I intermittently get the following error:

Traceback (most recent call last):
  File ./latDemTest.py, line 59, in module
answer = that_those[gender][number][q_and_a][case]
KeyError: 'abl'

I looked this error up online, and it seems the key error is generated when one 
attempts to retrieve a value from a dictionary with a key that does not exist. 
The problem is, it seems to me that the keys should in fact exist. The odd 
thing is, the code returns this error sometimes, and sometimes it doesn't. I 
did a bunch of trials, keeping track of which particular entries in the data 
structures worked and which failed, and I discovered that they overlap. The 
dictionary  {'gen': 'illōrum', 'clue': 'That/Those, Plural, Neuter Genitive'} 
for example, happily spits out the proper question and answer sometimes, other 
times it shoots out the previously mentioned error. I cannot understand how 
this could happen! 


THE FULL CODE: 

#!/Library/Frameworks/Python.framework/Versions/3.2/bin/python3.2
#  Don't forget ./ before filename to run from cmnd 

Re: [Tutor] Storing dictionary value, indexed by key, into a variable

2014-04-03 Thread John Aten
I apologize for the omissions, I thought that I had isolated the problem, but I 
was way off the mark. The problem was, as suggested by Danny and Peter, in the 
function where the dictionary is assigned. I ran the type function, as Alex 
advised, and lo and behold the function was returning a string. In researching 
this, I learned that a function can return multiple values, so I expanded 
things a bit. Now, the function that randomly selects which demonstrative to 
drill also selects which a string to present as the clue (the first part, 
anyway), and returns the dictionary and the first part of the clue in a tuple. 
I then unpack that tuple into variables and work with those. 

The thing is, this looks really messy Could anyone give me some pointers on how 
this could be more elegantly done?

Here's the full code:
import random
import os

# ille, that/those masculine
that_those_Masculine_Singular = {'nom': 'ille', 'gen': 'illīus', 'dat': 'illī', 
'acc': 'illum', 'abl': 'illō'}
that_those_Masculine_Plural = {'nom': 'illī', 'gen': 'illōrum', 'dat': 'illīs', 
'acc': 'illōs', 'abl': 'illīs'}

# the rest of the dictionaries are empty. I wanted to get it working before 
putting everything in. 
# ille, that/those feminine
that_those_Feminine_Singular = {'nom': '', 'gen': '', 'dat': '', 'acc': '', 
'abl': ''}
that_those_Feminine_Plural = {'nom': '', 'gen': '', 'dat': '', 'acc': '', 
'abl': ''}

# ille, that/those neuter
that_those_Neuter_Singular = {'nom': '', 'gen': '', 'dat': '', 'acc': '', 
'abl': ''}
that_those_Neuter_Plural = {'nom': '', 'gen': '', 'dat': '', 'acc': '', 'abl': 
''}

# hic, this/these masculine
this_these_Masculine_Singular = {'nom': '', 'gen': '', 'dat': '', 'acc': '', 
'abl': ''}
this_these_Masculine_Plural = {'nom': '', 'gen': '', 'dat': '', 'acc': '', 
'abl': ''}

# hic, this/these feminine
this_these_Feminine_Singular = {'nom': '', 'gen': '', 'dat': '', 'acc': '', 
'abl': ''}
this_these_Feminine_Plural = {'nom': '', 'gen': '', 'dat': '', 'acc': '', 
'abl': ''}

# hic, this/these neuter
this_these_Neuter_Singular = {'nom': '', 'gen': '', 'dat': '', 'acc': '', 
'abl': ''}
this_these_Neuter_Plural = {'nom': '', 'gen': '', 'dat': '', 'acc': '', 'abl': 
''}

# iste, that (near you/of yours) masculine 
that_near_you_Masculine_Singular = {'nom': '', 'gen': '', 'dat': '', 'acc': '', 
'abl': ''}
that_near_you_Masculine_Plural = {'nom': '', 'gen': '', 'dat': '', 'acc': '', 
'abl': ''}

# iste, that (near you/of yours) feminine
that_near_you_Feminine_Singular = {'nom': '', 'gen': '', 'dat': '', 'acc': '', 
'abl': ''}
that_near_you_Feminine_Plural = {'nom': '', 'gen': '', 'dat': '', 'acc': '', 
'abl': ''}

# iste, that (near you/of yours) neuter
that_near_you_Neuter_Singular = {'nom': '', 'gen': '', 'dat': '', 'acc': '', 
'abl': ''}
that_near_you_Neuter_Plural = {'nom': '', 'gen': '', 'dat': '', 'acc': '', 
'abl': ''}


guess = ''
score = 0
tries = 0

while guess != 'exit':

def chooseDemonstrative():
# N = random.randint(1,18)
N = 1 # This line will be removed so that it will pick any one 
of the dictionaries to be filled in above. This is just to get it working.
Demonstrative = {} 
Clue1 = ''
if N == 1:
Demonstrative = that_those_Masculine_Singular
Clue1 = 'That/Those, Masculine Singular Demonstrative 
Pronoun/Adjective'
elif N == 2:
Demonstrative = 'that_those_Masculine_Plural'
elif N == 3:
Demonstrative = 'that_those_Feminine_Singular'
elif N == 4:
Demonstrative = 'that_those_Feminine_Plural'
elif N == 5: 
Demonstrative = 'that_those_Neuter_Singular'
elif N == 6:
Demonstrative = 'that_those_Neuter_Plural'
elif N == 7:
Demonstrative = 'this_these_Masculine_Singular'
elif N == 8:
Demonstrative = 'this_these_Masculine_Plural'
elif N == 9:
Demonstrative = 'this_these_Feminine_Singular'
elif N == 10:
Demonstrative = 'this_these_Feminine_Plural'
elif N == 11:
Demonstrative = 'this_these_Neuter_Singular'
elif N == 12:
Demonstrative = 'this_these_Neuter_Plural'
elif N == 13:
Demonstrative = 'that_near_you_Masculine_Singular'
elif N == 14:
Demonstrative = 'that_near_you_Masculine_Plural'
elif N == 15:
Demonstrative = 'that_near_you_Feminine_Singular'
elif N == 16:
Demonstrative = 'that_near_you_Feminine_Plural'
elif N == 17:
Demonstrative = 

[Tutor] Storing dictionary value, indexed by key, into a variable

2014-03-31 Thread John Aten
Hey all,

I am writing a program to drill the user on Latin demonstrative pronouns and 
adjectives (DPA). It displays a description, and the user has to enter the DPA 
that corresponds to the description. DPA vary for gender, number and case, and 
there are 3 separate DPA. I have these stored in a bunch of dictionaries, with 
the DPA, gender and number in the dictionary name and the cases as keys. Of 
course, the values are the DPA themselves. Like so:

that_those_Masculine_Singular = {'nom': 'ille', 'gen': 'illīus', 'dat': 'illī', 
'acc': 'illum', 'abl': 'illō'}

I have a function that randomly selects one of these dictionaries, and another 
that randomly selects strings corresponding to the keys ('nom', 'gen', etc.). 
The trouble begins somewhere along here:

D = chooseDict()
c = chooseCase()

print(D, c)

guess = ''
# code to get the guess
# then,
answer = D[c]

if guess == answer:
# Do stuff, change score, continue, etc. 

This doesn't work, and I get this error:

TypeError: string indices must be integers

So my question is, why does Python think that D is a string? When I type the 
actual names (i.e., that_those_Masculine_Singular[nom]) the answer is 
returned just fine. I have tried D['c'] and D[c] also, and got the same 
error. I searched the web, and I can find no explanation on how to do what I am 
doing, and I can find nothing that indicates why this doesn't work. I'd really 
appreciate any help!

Thank you,

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


[Tutor] mixing 64 bit and 32 bit

2014-03-19 Thread John Fabiani

Hi,

At my office we have a mix of XP (32bit) and Window 7 (64 bit).  I 
installed python 64 bit on the windows 7 machines and 32 bit on the XP 
machines.  The question is can the different version run the same code 
without causing issues.  Can the 64 bit use the same byte code as the 32 
bit?  It seems to be working but I thought best to check.


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


Re: [Tutor] mixing 64 bit and 32 bit

2014-03-19 Thread John Fabiani

Thanks
Johnf
On 03/19/2014 11:01 AM, Reuben wrote:


Hi John,

The generated bytecodes will be different - but both version can run 
same code without issues


Regards,
Reuben

On 19-Mar-2014 11:28 PM, John Fabiani jo...@jfcomputer.com 
mailto:jo...@jfcomputer.com wrote:


Hi,

At my office we have a mix of XP (32bit) and Window 7 (64 bit).  I
installed python 64 bit on the windows 7 machines and 32 bit on
the XP machines.  The question is can the different version run
the same code without causing issues.  Can the 64 bit use the same
byte code as the 32 bit?  It seems to be working but I thought
best to check.

Johnf
___
Tutor maillist  - Tutor@python.org mailto: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


[Tutor] Finding the latest file in a dir

2014-01-05 Thread Joseph John
Hi All,
Even though I am a old user in the mailing list, my skills in Python are
not impressive.
I have restarted doing python for some small task.
I am trying to find the latest file in a dir, I have searched and found out
I shoulld do in this way

#!/usr/bin/python

import os
newest = max(os.listdir(/opt/AlfDB/.), key = os.path.getctime)
print newest
---
but when I run it I am getting error message such as
./FindingLatestFileInDir.py
Traceback (most recent call last):
  File ./FindingLatestFileInDir.py, line 4, in module
newest = max(os.listdir(/opt/AlfDB/.), key = os.path.getctime)
  File /usr/lib64/python2.7/genericpath.py, line 64, in getctime
return os.stat(filename).st_ctime
OSError: [Errno 2] No such file or directory: 'alfresco20140104-.sql'

--
I get results if I do it without giving the dir location such as
---
#!/usr/bin/python

import os
newest = max(os.listdir(.), key = os.path.getctime)
print newest
-
This gives the result for the directory from where it runs, but when I
change the dir location to /opt/AlfDB , It does not. I am not able to
apprehend how it is not working

Guidance and advice requested
Thanks
Joseph John
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] basic function concept

2013-11-17 Thread John Aten
Too bad that doesn't work.

On Nov 16, 2013, at 11:16 PM, Alex Kleider wrote:

 On 2013-11-16 13:20, Byron Ruffin wrote:
 def main(x, y, z):
 print (x, y, z)
 def funct():
 x = 1
 y = 2
 z = 3
 return x, y, z
 main()
 Can someone tell me why main is not being given any arguments?
 
 Because you didn't give it any.
 Try
 main(funct())
 instead.
 
 
 ___
 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

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


Re: [Tutor] Reading CSV files in Pandas

2013-10-20 Thread John Steedman
I have in front of me a copy an (unread, borrowed) copy of Python for
Data Analysis.  Well, on page 104, there is the start of an answer.

Pandas : has two useful functions: read_csv and read_table
Numpy : see np.loadtxt and np.genfromtxt

There is an example for using the first numpy function:

arr = np.loadtxt ( fileName, delimiter = ','  )

This information from Python for Data Analysis , author: Wes McKinney
published by O'Reilly - a succinct, useful-looking book.





On Sun, Oct 20, 2013 at 7:05 PM, Alan Gauld alan.ga...@btinternet.com wrote:
 On 20/10/13 11:30, Matthew Ngaha wrote:

 Does pandas do the same thing numpy does?


 Pandas is more about analysis of big data volumes rather than complex
 calculations. eg statistical analysis and data mining.

 As such it's closer to R than to numpy in its function, so far as I can
 tell. (Although it uses numpy under the covers).


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

 ___
 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


[Tutor] Python Programming for the absolute beginner 3e, Ch3 Challenge 4

2013-08-11 Thread John Feleppa
Thanks for getting back to me...

I am using Python 3.3.2.

The challenge is as follows:

# Chapter 3 Challenge 4
#
# Write the psudocode for a program where the player and the computer
# trade places in the number guessing game.  That is, the player picks a
# random number between 1 and 100 that the computer has to guess.
# Before you start, think about how you guess.  If all goes well, try
# coding the game.

It builds on the previous challenge, where the user guesses the number - I
coded that OK, as below.

import random

print(\tWelcome to 'Guess My Number'!)
print(\nI'm thinking of a number between 1 and 100.)
print(Try to guess it in as few attempts as possible.\n)

# set the initial values
the_number = random.randint(1, 100)
guess = int(input(Take a guess: ))
tries = 1

# guessing loop

while guess != the_number and tries  10:
if guess  the_number:
print(Lower...)
else:
print(Higher...)

guess = int(input(Take a guess: ))
tries += 1

if guess == the_number:
print(You guessed it!  The number was, the_number)
print(And it only took you, tries, tries!\n)
else:
print(Huh - you took , tries, tries and still never got it.)
print(It was , the_number,  - but why tell you, you'll forget it,
won't you.)

input(\n\nPress the enter key to exit.)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python Programming for the absolute beginner 3e Ch3 Challenge 4

2013-08-08 Thread John Feleppa
Hello,

I am working through Michael Dawson's book, Python Programming for the
absolute beginner 3rd edition.

Have just completed Chapter 3, but cannot solve Challenge 4.

Has anyone solved this yet - and be willing to share this code?

I would much appreciate..

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


[Tutor] Test Question

2013-07-01 Thread John Steedman
Good morning all,

A question that I am unsure about.  I THINK I have the basics, but I am not
sure and remain curious.

1. What does this mean?
 if my_object in my_sequence:
...

2. What can go wrong with this? What should a code review pick up on?

I believe that my_sequence might be a either container class or a
sequence type. An effective __hash__ function would be required for each
my_object.  I HTINK you'd need to avoid using floating point variables
that might round incorrectly.

Are there other issues?

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


Re: [Tutor] Test Question

2013-07-01 Thread John Steedman
Many thanks, everyone.  Great answers. I decided to read the manual
properly.  May take some time but well worth it.


On Mon, Jul 1, 2013 at 2:40 PM, Steven D'Aprano st...@pearwood.info wrote:

 On 01/07/13 19:58, John Steedman wrote:

 Good morning all,

 A question that I am unsure about.  I THINK I have the basics, but I am
 not
 sure and remain curious.

 1. What does this mean?

 if my_object in my_sequence:

 ...



 Others have already answered this, but for completion, it is testing
 whether my_object can be found as an element of the sequence, iterable,
 or container my_sequence.



  2. What can go wrong with this? What should a code review pick up on?


 Depends on context. Without context, nearly anything could go wrong:

 NameError -- perhaps one or both of the names are undefined;

 TypeError -- perhaps the names are misleading, and my_sequence is not a
 sequence at all;

 Perhaps my_sequence is an infinite iterator and the above will never
 complete;

 etc.


  I believe that my_sequence might be a either container class or a
 sequence type. An effective __hash__ function would be required for each
 my_object.


 Correct, if my_sequence is in fact a dict or other mapping that relies on
 hashing.

 But in fact it's not just the presence of a __hash__ method on my_object
 which is required, but that the __hash__ method can actually return. E.g.
 tuples have a __hash__ method, but that relies on every element of the
 tuple being hashable:

 py (1, 2, 3) in {}
 False
 py (1, 2, [3]) in {}
 Traceback (most recent call last):
   File stdin, line 1, in module
 TypeError: unhashable type: 'list'



  I HTINK you'd need to avoid using floating point variables
 that might round incorrectly.


 No, Python floats are not rounded when doing containment testing. They may
 have been rounded earlier, but `x in container` will use the full precision
 of the float.


  Are there other issues?


 Nothing obvious to me.





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

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


[Tutor] Function Return Values (or References)

2013-06-24 Thread John Steedman
Hi Tutors,

I'm confused by the following possible contradiction. Would someone please
explain or point me to the right docs.

FACT 1

Variables in python hold references to objects.
http://en.wikipedia.org/wiki/Python_syntax_and_semantics

FACT 2

def Increment ( x ) :
// return x + 1
x = x + 1
return x

y = 1
z = Increment ( y )
y
1
z
2

By FACT 1  x should be a reference parameter...?
By Fact 2 x would seem to be a copy...?

What in the world of dynamic typing is going on?

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


Re: [Tutor] Function Return Values (or References)

2013-06-24 Thread John Steedman
Thanks for all these clear and knowledgeable answers.  I'm much clearer on
this now and will read up a bit more around these subjects.

John


On Mon, Jun 24, 2013 at 10:59 AM, Peter Otten __pete...@web.de wrote:

 John Steedman wrote:

  Hi Tutors,
 
  I'm confused by the following possible contradiction. Would someone
 please
  explain or point me to the right docs.
 
  FACT 1
 
  Variables in python hold references to objects.
  http://en.wikipedia.org/wiki/Python_syntax_and_semantics
 
  FACT 2
 
 def Increment ( x ) :
 // return x + 1
 x = x + 1
 return x
 
 y = 1
 z = Increment ( y )
 y
  1
 z
  2
 
  By FACT 1  x should be a reference parameter...?
  By Fact 2 x would seem to be a copy...?
 
  What in the world of dynamic typing is going on?

 There's a big confusion in terminology. Does

 http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing

 help? Here's a more detailed explanation:

 
 http://learntofish.wordpress.com/2012/01/09/call-by-object-reference-call-by-sharing/
 



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

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


Re: [Tutor] 2 basic problems

2013-06-23 Thread John Harris
Hi Charles,

I have added some comments below explaining why you are not getting the
results you expect:

 4+4
8

The above is an expression, when you hit enter python will evaluate it and give
the answer.

 3+3=4
SyntaxError: can't assign to operator
 3=1
SyntaxError: can't assign to literal

I thought the last 2 lines should return False

This is an assignment statement, the single '=' means when you hit enter
python will try to set the value of one side to the other. Hence the
assignment error. Instead try:

 3+3==4
False
 3==1
False




lot=('1'+'6'+'8')
print(lot)
a=open(acc,w)
a.write(lot)
a.close
b=open(acc,r)
b.read()
print (b)
b.close


returns

168
open file 'acc', mode 'r' at 0xb6f9a650


Firstly your file.close methods need to have parens to actually call the
method. So instead of a.close we need a.close()

Then your b.read() line will work, I get the output '168' when I call
b.read().

Lastly, the line b = open(acc, r) creates a new file object (b). From
the docs: Open a file, returning an object of the file type.
Therefore when you print(b) python will call the __repr__() method of the
file object which is why you see the line open file 'acc', mode 'r' at
0xb6f9a650.

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


Re: [Tutor] a little loop

2013-05-28 Thread John Steedman
Some other tools, if you haven't come across them yet.

You already know about str.join ()

Slicing

b=['s','p','a','m']
b [ : 1 ]
['s']
b [ : 2 ]
['s', 'p']

Also, consider

len ( b)
4

range ( 4 )
[ 0, 1, 2, 3, 4]
# which I can iterate over.












On Tue, May 28, 2013 at 4:54 AM, Tim Hanson tjhan...@yahoo.com wrote:

 Okay, so I made it to FOR loops in the Lutz book.  A couple of days ago I
 was
 helped here with the .join method for creating strings from lists or
 tuples of
 strings.  I got to wondering if I could just, for the sake of learning, do
 the
 same thing in a FOR loop, since that's today's chapter:

 x=0; ham=''; b=['s','p','a','m'] #or, b=('s','p','a','m')
 for t in b:
 ham=ham+b[x]
 print(ham);x+=1


 s
 sp
 spa
 spam

 Alright, it works, eventually.  Can someone help me find a little more
 elegant
 way of doing this?  I'm sure there are several.

 Incidentally, I put the print statement within the FOR loop so I could
 watch
 progress.
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] Random Number Game: Returns always the same number - why?

2013-05-20 Thread John R Jones
You need to move this line:

Random_Number = random.randint(1, 100)

into the loop body, like this:


while Count = 100:
 Random_Number = random.randint(1, 100)
 print (Random_Number)
 Count = Count + 1

 Hope this helps.



On Mon, May 20, 2013 at 9:31 AM, Rafael Knuth rafael.kn...@gmail.comwrote:

 Hello,

 I wrote a simple program, and I was expecting that I would get 100
 different random numbers. Instead, I am getting 100 times exactly the same
 random number. Can anyone advise how I should alter my program?

 Thank you!

 All the best,

 Rafael
 PS. I am using Python 3.3.0

 print (

 This game will return 100 random numbers between 1 and 100.

 )

 import random

 Count = 0

 Random_Number = random.randint(1, 100)

 while Count = 100:
 print (Random_Number)

 Count = Count + 1


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




-- 
John R Jones   n71...@gmail.com
10814 Des Moines Ave,  Porter Ranch, CA 91326
818-378-6206 cell/text,  310-531-8300 work, 424-234-9213 voicemail
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] model methods in Django

2013-05-19 Thread John Steedman
For the benefit of others,I believe the full class (from the Django
Tutorial) is

class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')

def was_published_recently(self):
return self.pub_date = timezone.now() - datetime.timedelta(days=1)
#

was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'


Source:
https://docs.djangoproject.com/en/dev/intro/tutorial01/
https://docs.djangoproject.com/en/dev/intro/tutorial02/


I find the Django (and this fragment) very elegant UP TO the comment.


On Sat, May 18, 2013 at 8:16 PM, Matthew Ngaha chigga...@gmail.com wrote:

  im following the official docs and after learning Python im sure of
 how methods work, but the model example on the beginners guide has me
 really confused.

 The model definition is omitted but can anyone explain how this methed
 (was_published_recently) is given these attributes:

 class Poll(models.Model):
 # ...
 def was_published_recently(self):
 return self.pub_date = timezone.now() - datetime.timedelta(days=1)
 was_published_recently.admin_order_field = 'pub_date'
 was_published_recently.boolean = True
 was_published_recently.short_description = 'Published recently?'

 are the names of the attributes already attached to these
 functions/methods, or are they being created on the fly with whatever
 name you want? As i am unable to comprehend what is going on, i dont
 really have a clue as to what each definition is doing and how it
 affects the model, even after reading this section of the docs over
 and over again im still lost.
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

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


[Tutor] Fwd: Pi xels

2013-05-09 Thread John Steedman
I once dabbled with wxPython.  The code below may not run straight off as
I've cut it out of a bigger routine, but it may give you a flavour of a
basic (very basic) set up.

import wx

import math

def drawCircle (radius, canvas, strCol):

  centre = (100,100)
  cX = centre[0]
  cY = centre[1]

  dc = canvas
  dc.SetPen(wx.Pen(strCol, 5))

  x1 = 0
  y1 = math.sqrt ( math.pow (radius,2) - math.pow(x1, 2) )

  for x2 in range ( 1, radius + 1 , 1 ):

y2 = math.sqrt ( math.pow (radius,2) - math.pow(x2, 2) )
dc.DrawLine ( cX+ x1 , yCorr ( cY + y1 ), cX + x2, yCorr (cY + y2) )
dc.DrawLine ( cX+ x1 , yCorr ( cY - y1 ), cX + x2, yCorr (cY - y2) )
dc.DrawLine ( cX- x1 , yCorr ( cY + y1 ), cX - x2, yCorr (cY + y2) )
dc.DrawLine ( cX- x1 , yCorr ( cY - y1 ), cX - x2, yCorr (cY - y2) )

y1 = y2
x1 = x2


def on_paint(event):
  dc = wx.PaintDC(event.GetEventObject())
  dc.Clear()
  drawCircle ( 50, dc, 'GREEN')


app = wx.App(False)


frame = wx.Frame(None, title=Draw on Panel)
panel = wx.Panel(frame)
panel.Bind(wx.EVT_PAINT, on_paint)
#panel.Bind(wx.EVT_LEFT_DOWN, on_mouseClick)

panel.SetFocusIgnoringChildren()
panel.Bind(wx.EVT_KEY_DOWN, on_KeyDown )

frame.Show(True)
app.MainLoop()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Issue With a Python Game

2013-04-14 Thread John Bochicchio
I have a question about a game I am making. I finished the overall code,
but keep getting errors when I try to play. This is my most common error:
C:\Users\John\Documents\Python Games\Noahpython nickeladventuredemo.py
Traceback (most recent call last):
  File nickeladventuredemo.py, line 451, in module
main()
  File nickeladventuredemo.py, line 78, in main
levels = readLevelsFile('levels.txt')
  File nickeladventuredemo.py, line 371, in readLevelsFile
assert startx != None  and starty!= None, 'Level %s (around line %s) in
%s i
s missing a @ or + to mark the start point.' % (levelNum+1, lineNum,
filenam
e)
AssertionError: Level 1 (around line 10) in levels.txt is missing a @ or
+ t
o mark the start point.

The error has something to do with the levels. I will attach the code and
levels, as they are fairly long.

-- 
A computer without a Microsoft operating system is like a dog without
bricks tied to its head.
; Starting demo level:
 
##  #
#   .   #
#   $   #
# .$@$. #
$   #
   #.   #
   #   ##
   #

; 1

   ###
  ## # 
 ##  ###  #
## $  #
#   @$ #  #
### $###  #
  #  #..  #
 ## ##.# ##
 #  ##
 # ##
 ###

; 2

 ## #
## ## . #
# ## $. #
 ## $   #
## $@ ###
# $  ##
#.. ## ##
#   # ##
# #

; 3

   #
  ##   #
  ##
  # $ ##
#  $ $#
# $ $ #
   ## ## $ $ $#
   #  .#  $ $ #
   #  .#  #
# #
# @  #
##
##  ##
 

; 4

  ###
 ## #  @#
### $ $$#   #
# ##$$$ #
#  #  $ #   #
## ##
#.. ..$ #*##
# ..###
#  ..#
#

; 5

  ###
 #####
### $ $#$ $ ###
# #$ $ # $ $# #
# $  ..#..  $ #
#  $...#...$  #
# $ .. * .. $ #
## @ ##
# $ ..   .. $ #
#  $...#...$  #
# $  ..#..  $ #
# #$ $ # $ $# #
### $ $#$ $ ###
 #####
  ###

; 6

  ###
###.  .$.  .###
 ## $  $  $ ##
  ## ..$.. ##
   ##$#$#$##
#.$ $.#
#  @  #
### ###
   ## $ $ ##
   #.  $  .#
   ### . ###
 #

; 7

   ##
  ###
  ###  #  #  ## ###
### #   $ #
#  $ @ ...*..  $  #
# $ $  ## ###   ###
### ###   # #
 #  ###
 #   
 #

; 8

###
# ##
# ###  ##
#   #  ##
#@$***. ##$ #
#  ### .#
##  ##  # $ #
 ##  .$.#
  ###
   ##  ##


; 9

#
#. .#
#.$. .  #
## ###@ #
 #  $  ##
 # $$ ##
 #  $ #
 #  ###
 

; 10

  ##
  ##
  # @  ###
  #  #
#  ..#.#$#
# $ $ ##...  #
# .#$$   #
## ##$## #
 #  $#
  
   #  #
   #  #
 ### $#
 #  $ $   #
 # #$# 
 # #
 ###

; 11

  
###  
#   @   ##
# #. .#.###
# $$$ $$$ #
###.#.#.# #
 ##   #
    ###
 

; 12

  #
  #   #
# #   ###
#   # #   . #
# # ##  # # # # #
# $ $ $ $ $ # ##   ## $ #
# # ##.. ### $$ ###
#  ## * ## #  $$  #
##+$$   ## #  #
 #.$ $# #  
 #.##   #
 

; 13

   ###
 ### ##
 #   ###  #
 #  # #
###$#@  # #
#   # #
#   #  *. #
##$$#  *.##
 # *..#
  #...##
# #$$$ #
#   $  #
#  #


; 14

 ###
## # #
#  *.$.#
#  *.#.###
# #$@$$  #
#   ## # #
##   #
 #

; 15

   
   #@ #
  ##  #
  # .$#
  #$. #
###..$###
#  ..$  #
# $ $ # #
# # #
#   #
#

; 16

  ##
 ## #  ###
## #   # ##
# #   $.# #
##  $ $.# #
# #. ##
# $. @#
# $. 
### # #*# # ###
   .$ #
#  .$ #
## .# #
# #.$ $  ##
# #.$   # #
## #   # ##
 ###  # ##
   ##

; 17

###
   ## . . . . ###
   #  $$ $ $ $  #
   #    # #
  ##  $ # #   #
 ##  $ $ #  ### # #
##  # #    $  #
#...  # $   ###
#... @ $ ##
#... $  $ #
#  #  #
   

; 18


#  #
#  #
#$ $ $ #
#.*.*.*#
#*.*.*.#
# $ $ $#
#..#
#.*.*.*#
#$ $ $ #
# $ $ $#
#$ $ $ #
#  #
#@ #


; 19

#
#   ###
#  $  ##
## ##  ##
 # ## # 
 # # ##$   ##
 # #.   #@## $  ##
 # #.#  ##### $  ##
 # #.#  ## $  ##
 # #.#   #  ##   ## $  ##
## #.#  ##  ###   ## $  #
#  #.#   #  #*##   ##   #
#   .# # #  ##*##   #
##   #  ##
 #

; 20

 
 #  #
##$.#
#   $ $.#
# $@$...#
# $$$..##
#  $ ..#


; 21

# 
#   ### . $  #
#   $ *.. #$ ##
## $# ..* $  @#
 #  $ . ###   #
  #

; 22

   # 
   #@ .###  ###
  $$ $#
#   # . . ##  #
#  $ # . . ## #
## .  $ $$  # #
 # #  ###.  # #
 #  # #
 #   ##
 ### # 
   # .$ #
    #
 ## #
  ###

; 23

[Tutor] Issue With a Python Game

2013-04-14 Thread John Bochicchio
I have a question about a game I am making. I finished the overall code,
but keep getting errors when I try to play. This is my most common error:
C:\Users\John\Documents\Python Games\Noahpython nickeladventuredemo.py
Traceback (most recent call last):
  File nickeladventuredemo.py, line 451, in module
main()
  File nickeladventuredemo.py, line 78, in main
levels = readLevelsFile('levels.txt')
  File nickeladventuredemo.py, line 371, in readLevelsFile
assert startx != None  and starty!= None, 'Level %s (around line %s) in
%s i
s missing a @ or + to mark the start point.' % (levelNum+1, lineNum,
filenam
e)
AssertionError: Level 1 (around line 10) in levels.txt is missing a @ or
+ t
o mark the start point.

The Code:

import random, sys, copy, os, pygame

from pygame.locals import *



FPS = 30

WINWIDTH = 800

WINHEIGHT = 600

HALF_WINWIDTH = int(WINWIDTH / 2)

HALF_WINHEIGHT = int(WINHEIGHT / 2)



TILEWIDTH = 50

TILEHEIGHT = 85

TILEFLOORHEIGHT = 45



CAM_MOVE_SPEED = 5



OUTSIDE_DECORATION_PCT = 20



BRIGHTBLUE = ( 0, 170, 255)

WHITE  = (255, 255, 255)

BGCOLOR = BRIGHTBLUE

TEXTCOLOR = WHITE



UP = 'up'

DOWN = 'down'

LEFT = 'left'

RIGHT = 'right'





def main():

global FPSCLOCK, DISPLAYSURF, IMAGESDICT, TILEMAPPING,
OUTSIDECOMAPPING, BASICFONT, PLAYERIMAGES, currentImage



pygame.init()

FPSCLOCK = pygame.time.Clock()



DISPLAYSURF = pygame.display.set_mode((WINWIDTH, WINHEIGHT))



pygame.display.set_caption('Noah Nickel Adventure!')

BASICFONT = pygame.font.Font('freesansbold.ttf', 18)



IMAGESDICT = {'uncovered goal': pygame.image.load('RedSelector.png'),

  'covered goal': pygame.image.load('Selector.png'),

  'star': pygame.image.load('Star.png'),

  'corner': pygame.image.load('Wall Block Tall.png'),

  'wall': pygame.image.load('Wood Block Tall.png'),

  'inside floor': pygame.image.load('Plain Block.png'),

  'outside floor': pygame.image.load('Grass Block.png'),

  'title': pygame.image.load('star_title.png'),

  'solved': pygame.image.load('star_solved.png'),

  'princess': pygame.image.load('princess.png'),

  'boy': pygame.image.load('boy.png'),

  'catgirl': pygame.image.load('catgirl.png'),

  'horngirl': pygame.image.load('horngirl.png'),

  'pinkgirl': pygame.image.load('pinkgirl.png'),

  'rock': pygame.image.load('Rock.png'),

  'short tree': pygame.image.load('Tree_Short.png'),

  'tall tree': pygame.image.load('Tree_Tall.png'),

  'ugly tree': pygame.image.load('Tree_Ugly.png')}



TILEMAPPING = {'X': IMAGESDICT['corner'],

   '#': IMAGESDICT['wall'],

   'o': IMAGESDICT['inside floor'],

   ' ': IMAGESDICT['outside floor']}



OUTSIDECOMAPPING = {'1': IMAGESDICT['rock'],

'2': IMAGESDICT['short tree'],

'3': IMAGESDICT['tall tree'],

'4': IMAGESDICT['ugly tree']}

#Super important to remember:

#DEAR GOD REMEMBER THIS IS AN INDEX OF PLAYER IMAGES.

currentImage = 0

PLAYERIMAGES = [IMAGESDICT['princess'],

IMAGESDICT['boy'],

IMAGESDICT['catgirl'],

IMAGESDICT['horngirl'],

IMAGESDICT['pinkgirl']]

startScreen()



levels = readLevelsFile('levels.txt')

currentLevelIndex = 0



while True:

result = runLevel(levels, currentLevelIndex)



if result in ('solved', 'next'):

currentLevelIndex += 1

if currentLevelIndex = len(levels):

currentLevelIndex = 0



elif result == 'back':

currentLevelIndex -= 1

if currentLevelIndex 0:

currentLevelIndex = len(levels)-1



elif result == 'reset':

pass





def runLevel(levels, levelNum):

global currentImage

level0bj = levels[levelnum]

map0bj = decorateMap(level0bj['map0bj'],
level0bj['startState']['player'])

gameState0bj = copy.deepcopy(level0bj['startState'])

mapNeedsRedraw = True

levelSurf = BASICFONT.render('Level %s of %s' % (level0bj['levelNum']
+1, totalNumOfLevels), 1, TEXTCOLOR)

levelRect = levelSurf.get_rect()

levelRect.bottomleft = (20, WINHEIGHT - 35)

mapWidth = len(map0bj) * TITLEWIDTH

mapHeight = (len(map0bj[0]) - 1) * (TITLEHEIGHT - TILEFLOORHEIGHT) +
TILEHEIGHT

MAX_CAM_X_PAN = abs(HALF_WINHEIGHT - int(mapHeight / 2)) + TILEWIDTH

MAX_CAM_Y_PAN = abs(HALF_WINWIDTH - int(mapWidth / 2)) + TILEHEIGHT



levelIsComplete = False

camera0ffsetX = 0

camera0ffsety = 0

cameraUp = False

cameraDown = False

cameraLeft = False

cameraRight = False



while True

[Tutor] A Text Adventure Problem

2013-03-24 Thread John Bochicchio
I've been trying to write a simple test text adventure, but have been
running into serious problems. Here is the error I get when I run it. It
will give me the opening text and lets me make my first choice. Then I get
this.

error Traceback: (Most recent call last)
file game1.py, line 104, in module
RUNNER (ROOMS, shack_front)
file game1.py, line 100 in runner
room = map[next]
keyerror= none

And here is my code.

from sys import exit

from random import randint



def death():

quips = [You've become a zombie and eat you pals. Douche.

 You've died and left your comrades to fend for themselves.
Douche

 Your whole group dies because of you. Douche.

 You've got terrible planning skills, and ruined the teams
chances of survival. Douche.]



print quips[randint(0, len(quips)-1)]

exit(1)





def shack_front():

print The year is 2062, and the zombies have risen. You're not a
doctor, and you have no training. You're just a guy trying to survive.

print .. * 8

print You stand in front of a broken down shack, you here gurgles and
screams from inside. There is a window to the side of the house that you
can see through, or a door you can burst into.

print .. * 8

print Window or door?



action = raw_input()



if action == window:

print You silently walk over to the dirty window. You look inside
to see a man held captive by 2 marauders. The marauders are armed with
bats, and don't seem to know what they're doing. You have 1 9mm glock with
12 bullets.



elif action == door:

 print You burst through the door with your shoulder. You see only
one marauder. You shoot him in the chest and notice a man tied up in a
chair. You walk over to him but feel a sharp pain in the back of your head.
You never saw the second marauder coming.

 return 'death'



else:

print Not a valid command

return 'shack_front'



def shack_window():

print Do you burst through the door or try to fire through the window
at the marauders?



action = raw_input()



if action == window:

print You fire off three shots through the window. Two in the
chest of the first marauder, one in the neck of the other. They fall to the
ground, dead. You walk inside to see if the man is okay.



elif action == door:

print You burst through the door and fire two shots into the first
marauder. You remember seeing two, so you turn around and put one bullet
through the head of the one behind you. You walk over to the man to see if
he's okay.



else:

print Not a valid command

return 'shack_window'



def shack_interior():

print You ask the man if he is okay.

print He says that he will be fine, and that his name is Carmicheal.

print He says he is an ex marine, but was ambushed by five of them. He
believes that three went out on a scavenging party.

print Carmicheal believes that if you wait for them to come back and
ambush them, you will be able to get food, ammo, and perhaps even a gun.

print Do you tell him yes, or no?



action = raw_input()



if action == yes:

print You tell Carmicheal yes. You both hide in the back of the
shack. Carmicheal takes a cleaver and you pull out your glock. 30 minutes
pass.

print .. * 10



elif action == no:

print Carmicheal looks at you puzzled. You ask if he wants to come
with you, but he only gets mad. He screams at you for not following the
plan, but you walk out.

print You hear a rush of sound as the cleaver hits the back of
your skull. You are dead.

return 'death'



else:

print Not a valid command

return 'shack_interior'



def shack_back():

print You hear the sound of boots in the next room. Carmicheal and you
stand up, ready to attack. Do you go in first, or him?



action = raw_input()



if action == him:

print Carmicheal goes in first. His cleaver tearing through the
neck of the first marauder. You see one trying to pull the gun from his
waist. You fire two shots into the marauder, killing him. The third
marauder grabs you from behind. You elbow him in the abdomen, leaving
Carmicheal just enough room to throw his cleaver into the marauder's head.

print You have both survived. Do you scavenge the dead bodies?



elif action == me:

 print You go in first. You see the three marauders lined up like
bowling pins. You let off six shots. Killing first the marauder with the
gun, then the two with knives and bats. You easily killed these men without
even breaking a sweat. Their bodies lay before you. Do you want to scavenge
them?



else:

print Not a valid command.

return 'shack_back'



ROOMS = {

'death': death,

'shack_front': shack_front,

'shack_window': shack_window,

'shack_interior': shack_interior,

'shack_back' : shack_back

}





def 

Re: [Tutor] A Text Adventure Problem

2013-03-24 Thread John Bochicchio
1. I'm using the terminal to run the code. Using the command - (cd python
 python2 game1.py)
2. Using python 2.6 I believe.
3. I'm running Arch Linux at the moment.
4. I'm new to python, but I assume the error must have something to do with
not having a way for the program to move to the next area of the code.


On Sun, Mar 24, 2013 at 4:58 PM, bob gailer bgai...@gmail.com wrote:

  On 3/24/2013 3:41 PM, John Bochicchio wrote:

 I've been trying to write a simple test text adventure, but have been
 running into serious problems. Here is the error I get when I run it. It
 will give me the opening text and lets me make my first choice.

 What did you enter? I will bet is was 'window'.

  Then I get this.

  error Traceback: (Most recent call last)
 file game1.py, line 104, in module
 RUNNER (ROOMS, shack_front)
 file game1.py, line 100 in runner
 room = map[next]
 keyerror= none

   [snip]

 Questions:
 1 - what are you using to run your code?
 2 - Version of Python?
 3 - Operating system?
 4 - Did you think about what the error might mean?

 Observations:

 1 - The traceback does not match your code, so either you retyped it or
 you are using some unusual way of running the program.

 Compare
 RUNNER (ROOMS, shack_front)
 with
 runner (ROOMS, 'shack_front')

 2 - the error normally would look like KeyError: None rather than keyerror=
 none

  3 - The various room functions have at least one way out of them with no
 return statement. The value returned in that case is None.

 4 - There are many many blank lines in the program making it much harder
 to read. In future eliminate most or all of them.

 5 - Most of us do not have the patience to count down 100 lines. In future
 flag the line with something like:
 room = map[next]  line 100

 6 - quips = [You've become a zombie and eat you pals. Douche.

  You've died and left your comrades to fend for themselves.
 Douche
  Your whole group dies because of you. Douche.
  You've got terrible planning skills, and ruined the teams
 chances of survival. Douche.]
 quips is a list with one element, consisting of one string or 244
 characters.
 print quips[randint(0, len(quips)-1)]
 will always print the entire string.
 Perhaps you meant to put a comma at the end of each line?

 HTH and good luck.

 --
 Bob Gailer919-636-4239
 Chapel Hill NC




-- 
A computer without a Microsoft operating system is like a dog without
bricks tied to its head.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Overriding equality tests in Python

2013-03-23 Thread John Steedman
It is also good to know that  overriding the comparison magic methods in
your class can be very useful if you wish to apply sorting/searching
procedures available in python.

If you also implement __gt__, __lt__, __ge__, __le__  in your class, then
you can append each of your objects to a list and successfully use the
sorted () function on that list.  It will enable you to have your list
sorted by some other variables within your class, such as the number
scored.

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


[Tutor] Python's OOP-Inheritance make me confuse.

2013-01-18 Thread Moore John
Hi, I am new to Python language.
I have only 10 days experience on it.
When I start learning there is no difficult, but it make me slow down when
I reach Object Oriented Concept, especially Inherited.
Some of my background knowledge about Inherited is the child class can get
all of characteristic and behaviour of parent class, in other words - data
and methods of parent.
Ok, I am going to show the concept that make me confuse with two programs.
Both of them are getting the same result, so why people are making
different.
---Frist--
class Parent():

parentdata = 0

def __init__(self):

pass

def getParentData(self):

return Parent.parentdata

def setParentData(self, setdata):

Parent.parentdata = setdata



class Child(Parent):

childdata = 0

def __init__(self):

pass
def getChildData(self):

return Child.childdata

def setChildData(self, setdata):

Child.childdata = setdata


child = Child()

print Default Child's Data is : + str(child.getChildData())#getting 0

child.setChildData(3)

print After Adding Child's Data is :+ str(child.getChildData()) # getting
3

print Default Parent's Data is:+ str(child.getParentData())# getting 0

child.setParentData(1)

print After Adding Parent's Data is :+str(child.getParentData())# getting
1



-Second-
class Parent():

parentdata = 0

def __init__(self):

pass

def getParentData(self):

return Parent.parentdata

def setParentData(self, setdata):

Parent.parentdata = setdata

class Child(Parent):

childdata = 0

def __init__(self):

#super(Child, self).__init__()

#super(Child, self).__init__(self, self)

Parent.__init__(self)

def getChildData(self):

return Child.childdata

def setChildData(self, setdata):

Child.childdata = setdata


child = Child()

print Default Child's Data is : + str(child.getChildData())#getting 0

child.setChildData(3)

print After Adding Child's Data is :+ str(child.getChildData()) # getting
3

print Default Parent's Data is:+ str(child.getParentData())# getting 0

child.setParentData(1)

print After Adding Parent's Data is :+str(child.getParentData())# getting
1


---
And also guide me, how to use Super() method for instance of
Parent.__init__(self)
Somebody used, Super method ih there and some are doing as my way.
I am not clearly these two different.
In these two program - I am not using __init__ as constructor.
If I am going to use __init__ as to add data into the class's
data(childdata, parentdata), how do I insert parameter in
Parent.__init__(self) and both of their
def __init__(self): method.
Thanks
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] greater precision?

2012-10-29 Thread John Collins

Hi,
OS: XP
Py: 2.7.2

I am running some old scripts, not written by me, that produce
substantial calculated values data as decimals, 12 significant
figures. AFAIK, the keys calls are;

from math import pi, asin, atan2, cos, sin, sqrt

from math import pi, asin, atan2, cos, sin, sqrt
from crosspoint import crosspoint

which are from the 1st and 2nd scripts, that are run to generate,
then manipulate, the numbers (actually, polygon descriptions!).
However, the 2nd script 'calls' a script called crosspoint.py,
trimmed of most comments this is;

# Python code to find the crossing point of two lines.
# This function is optimised for big-integer or FP arithmetic: it
# multiplies up to find two big numbers, and then divides them.

def crosspoint(xa1,ya1,xa2,ya2,xb1,yb1,xb2,yb2):
Give the intersection point of the (possibly extrapolated) lines\n\
segments (xa1,ya1)-(xa2,ya2) and (xb1,yb1)-(xb2,yb2).
dxa = xa2-xa1
dya = ya2-ya1
dxb = xb2-xb1
dyb = yb2-yb1
if dya * dxb == dxa * dyb:
return None
if dxa == 0:
return (xa1, (xa1 - xb1) * dyb / dxb + yb1)
if dxb == 0:
return (xb1, (xb1 - xa1) * dya / dxa + ya1)
if dya == 0:
return ((ya1 - yb1) * dxb / dyb + xb1, ya1)
if dyb == 0:
return ((yb1 - ya1) * dxa / dya + xa1, yb1)

det = dya * dxb - dyb * dxa
xtop = dxb * dxa * (yb1-ya1) + dya * dxb * xa1 - dyb * dxa * xb1
ytop = dya * dyb * (xa1-xb1) + dxb * dya * yb1 - dxa * dyb * ya1

return (xtop / det, ytop / det)


I am not sure what == means, nor if any 'special' maths functions are
called from crosspoint.py (to me, it appears not?), so, as I understand 
it, the


from math import

line *is* the 'math engine' if you will, and is the source of the 12
sig fig limit, yes?

One other odd thing that occurs, is when the scripts are run, a weird,
small, non ASCII file called crosspoint.pyc is created? Is this the
interpreter 'compiling' crosspoint.py ( either before, during, or
after?) the 2nd script calls it?

Sorry to bother, but if I can squeeze out *at least* 15 sig figs, (30
or more would be better!) I'd be a happy camper!
XNumbers addon for Excel allows over 200 sig figs by switching to base
256 IIRC. It is this with which I'd like to examine the output of these
pyto scripts at finer resolution, if that can be done in python???

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


[Tutor] greater precision?

2012-10-29 Thread John Collins

Hi,
OS: XP
Py: 2.7.2

I am running some old scripts, not written by me, that produce
substantial calculated values data as decimals, 12 significant
figures. AFAIK, the keys calls are;

from math import pi, asin, atan2, cos, sin, sqrt

from math import pi, asin, atan2, cos, sin, sqrt
from crosspoint import crosspoint

which are from the 1st and 2nd scripts, that are run to generate,
then manipulate, the numbers (actually, polygon descriptions!).
However, the 2nd script 'calls' a script called crosspoint.py,
trimmed of most comments this is;

# Python code to find the crossing point of two lines.
# This function is optimised for big-integer or FP arithmetic: it
# multiplies up to find two big numbers, and then divides them.

def crosspoint(xa1,ya1,xa2,ya2,xb1,yb1,xb2,yb2):
Give the intersection point of the (possibly extrapolated) lines\n\
segments (xa1,ya1)-(xa2,ya2) and (xb1,yb1)-(xb2,yb2).
dxa = xa2-xa1
dya = ya2-ya1
dxb = xb2-xb1
dyb = yb2-yb1
if dya * dxb == dxa * dyb:
return None
if dxa == 0:
return (xa1, (xa1 - xb1) * dyb / dxb + yb1)
if dxb == 0:
return (xb1, (xb1 - xa1) * dya / dxa + ya1)
if dya == 0:
return ((ya1 - yb1) * dxb / dyb + xb1, ya1)
if dyb == 0:
return ((yb1 - ya1) * dxa / dya + xa1, yb1)

det = dya * dxb - dyb * dxa
xtop = dxb * dxa * (yb1-ya1) + dya * dxb * xa1 - dyb * dxa * xb1
ytop = dya * dyb * (xa1-xb1) + dxb * dya * yb1 - dxa * dyb * ya1

return (xtop / det, ytop / det)


I am not sure what == means, nor if any 'special' maths functions are
called from crosspoint.py (to me, it appears not?), so, as I understand 
it, the


from math import

line *is* the 'math engine' if you will, and is the source of the 12
sig fig limit, yes?

One other odd thing that occurs, is when the scripts are run, a weird,
small, non ASCII file called crosspoint.pyc is created? Is this the
interpreter 'compiling' crosspoint.py ( either before, during, or
after?) the 2nd script calls it?

Sorry to bother, but if I can squeeze out *at least* 15 sig figs, (30
or more would be better!) I'd be a happy camper!
XNumbers addon for Excel allows over 200 sig figs by switching to base
256 IIRC. It is this with which I'd like to examine the output of these
pyto scripts at finer resolution, if that can be done in python???

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


Re: [Tutor] greater precision?

2012-10-29 Thread John Collins

Hi Dave

Did you really leave two very-similar messages 3 minutes apart?  Or are
you using a broken gateway, like Google-groups, and it hiccoughed?

Sorry, I didn't intend to - flunky LH mouse microswitch!


Without knowing the type of the arguments being passed to the
crosspoint() function, we cannot say.  I can GUESS that they are int,
long, or float.  But you can find that out by examining the source
that's calling it.  Judging from the comments, I might guess they're int
or long, and if so, only the division being done in the function
produces floats.  If that's the case, then you're limited to float's
precision.  if they are some other type (eg. Decimal), then indeed there
might be special functions being called.


Well, the two scripts are only about an email page long each, shall
I post them?


That import gets you access to the particular symbols it imports.
Normal arithmetic on floats is already built in, and doesn't need an import.

Right! Thanks.

I'm assuming you're using CPython, and you say it's on XP.  So
presumably you're running an Intel (or Intel-compatible) processor with
binary floating point built-in.  That processor is the limit of float
values in normal use.  It's good to about 18 digits.

Sure, 32 bit uproc, intrinsic binary limit.

Exactly.  It's a side-effect of the first import of the module.  On
subsequent imports, the pyc file is used, unless the py file has been
modified meanwhile.

Ah! Thanks!

18 digits is what you should get if the code is as I describe.  But if
there are lots of fp operations you're not showing, then an error can
gradually get larger.  And with any finite precision, you have the risk
from things such as subtracting two nearly-equal values, which will
reduce the final precision.

AFAIK, it's all FP. inputs are integers, outputs range from
-2. to 2.

If you need more than 18, then go to the Decimal module, which lets you
set the precision to arbitrary levels.  You will see a substantial
slowdown, of course, if you set the precision very high.  if that
becomes a problem, consider CPython 3.3, which has optimized that
module.  But try not to change too many things at once, as there are
lots of changes between 2.7 and 3.3.

I think I'll need to from what you have said / pointed out - ie, for
in excess of 'machine' precision, one needs to change base 10 floats
to a higher base, do foo, then come back. Sounds daunting!

John.

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


Re: [Tutor] greater precision?

2012-10-29 Thread John Collins
(phi))/2.
#
# Given an arbitrary cumulative probability function, we can
# select a number from the represented probability distribution
# by taking a uniform number in [0,1] and applying the inverse
# of the function. In this case, this means we take a number X
# in [0,1], scale and translate it to obtain 2X-1, and take the
# inverse sine. Conveniently, asin() does the Right Thing in
# that it maps [-1,+1] into [-pi/2,pi/2].

theta = random.random() * 2*pi
phi = asin(random.random() * 2 - 1)
points.append((cos(theta)*cos(phi), sin(theta)*cos(phi), sin(phi)))


# For the moment, my repulsion function will be simple
# inverse-square, followed by a normalisation step in which we pull
# each point back to the surface of the sphere.

while 1:
# Determine the total force acting on each point.
forces = []
for i in range(len(points)):
p = points[i]
f = (0,0,0)
ftotal = 0
for j in range(len(points)):
if j == i: continue
q = points[j]

# Find the distance vector, and its length.
dv = (p[0]-q[0], p[1]-q[1], p[2]-q[2])
dl = sqrt(dv[0]**2 + dv[1]**2 + dv[2]**2)

# The force vector is dv divided by dl^3. (We divide by
# dl once to make dv a unit vector, then by dl^2 to
# make its length correspond to the force.)
dl3 = dl ** 3
fv = (dv[0]/dl3, dv[1]/dl3, dv[2]/dl3)

# Add to the total force on the point p.
f = (f[0]+fv[0], f[1]+fv[1], f[2]+fv[2])

# Stick this in the forces array.
forces.append(f)

# Add to the running sum of the total forces/distances.
ftotal = ftotal + sqrt(f[0]**2 + f[1]**2 + f[2]**2)

# Scale the forces to ensure the points do not move too far in
# one go. Otherwise there will be chaotic jumping around and
# never any convergence.
if ftotal  0.25:
fscale = 0.25 / ftotal
else:
fscale = 1

# Move each point, and normalise. While we do this, also track
# the distance each point ends up moving.
dist = 0
for i in range(len(points)):
p = points[i]
f = forces[i]
p2 = (p[0] + f[0]*fscale, p[1] + f[1]*fscale, p[2] + f[2]*fscale)
pl = sqrt(p2[0]**2 + p2[1]**2 + p2[2]**2)
p2 = (p2[0] / pl, p2[1] / pl, p2[2] / pl)
dv = (p[0]-p2[0], p[1]-p2[1], p[2]-p2[2])
dl = sqrt(dv[0]**2 + dv[1]**2 + dv[2]**2)
dist = dist + dl
points[i] = p2

# Done. Check for convergence and finish.
sys.stderr.write(str(dist) + \n)
if dist  2.10005e-16:
break

# Output the points.
for x, y, z in points:
pprint(x, y, z)


The nfaces.py used on the output from this is a tad longer!



Well, yes, but only with some significant changes

Well, it seems I may have to learn decimal python, and insert it
into the above, and nfaces.py.

John.

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


Re: [Tutor] greater precision?

2012-10-29 Thread John Collins

Hi Peter,
Thanks.

[On modern hardware] Python uses IEEE 754 double-precision
http://en.wikipedia.org/wiki/Double_precision internally which gives 15 to
17 digits. But of course errors may accumulate.

As in my previous, this script seems to output precisely 12 significant
not 15 and not 17. ??? 15 and I'd be happier right now, as it matches
Excel's precision there, 'as it is'.

Equality.

Right, in a 1,0 sense.

Because of rounding errors this is a dangerous operation for floating point
numbers:

print 1.0 == .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1

False

I take it that is because binary for .1 is a repeating sequence, yes?

It is a toolbox rather than an engine.

Ah ha! *Now* I'm getting it!

math is basically a wrapper around the C library, and these functions all
use C's double and [most of the time] your hardware's floating point unit.

Right!

Yes, Python compiles the source to bytecode before it executes it, and for
all modules except the main script this bytecode is cached in a .pyc file.

That nails it (as I was wondering, just now, why the primary scripts
remained intact).

As you correctly observed crospoints() uses only +-*/ and ==, so you can
feed it every type that supports these operations (this is called duck
typing). For example:



from fractions import Fraction
from crosspoint import crosspoint
crosspoint(Fraction(0, 1), Fraction(1, 3), Fraction(1, 1), Fraction(1,

3), Fraction(5, 7), Fraction(0, 1), Fraction(5, 7), Fraction(1, 1))
(Fraction(5, 7), Fraction(1, 3))

p = crosspoint(Fraction(0, 1), Fraction(1, 3), Fraction(1, 1),

Fraction(1, 3), Fraction(5, 7), Fraction(0, 1), Fraction(5, 7), Fraction(1,
1))

print %s, %s % p

5/7, 1/3

Yay, infinite precision ;)

You just lost me.

Of more practical relevance may be something like gmpy
http://code.google.com/p/gmpy/

I've just had a peek. Looks like what I need. Haven't a clue if I'll
understand how to 'patch it in' to the scripts. Doco read time!
John.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] greater precision?

2012-10-29 Thread John Collins

Hi Dave,
Thanks, more insights!

I was only concerned that there was some correction in one of the
messages.  And since there was only 3 minutes between them, i didn't
know which might be the corrected one.  They showed up here out of
order.  I responded to the one with the later timestamp.

No, mia culpa.

Just post one of them.  Otherwise, things can get very confusing.

Done.

Actually, it's 64 bits.  32 bit fp wouldn't get you anywhere near 18 digits.

Darn, of course, you're right! Senior moment for me!

Since the inputs to that function are ints, then the output will be IEEE
floats.  that also means that the == comparisons in the crosspoint()
function are precise.

THAT is a very valuable insight Dave, thanks!

Actually, the base change is already happening.  Using Decimal would
probably reduce the number of base changes.  And if you create the
numbers as Decimal objects, then they'll propagate through the
crosspoint() function correctly.However, even though the decimal
module supports log and sqrt, I don't know how to do trig with it.

Well, as trig is *core essential* to polyhedra maths, I *have* to
use *lots* of it!

Incidentally, I didn't suggest the fractions module, since you're
presumably going to be doing trig on the results, so I don't see the
benefit.

Yes. Core maths is +,-,*,/,sin,cos,tan (and their inverses), sqrt,
^2,^3, (ie, exponentials), etc off hand.

BTW, I misspoke earlier.  The module name is decimal.  The class name
within that module is Decimal.

A minor thing to me, a non programmer, but I do understand that being
very precise is very important to programmers, so thank you!
John.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] greater precision?

2012-10-29 Thread John Collins

Hi Dave,

Not true.  That's just what it was truncated to upon output.  If you
want to show 15 digits, then use formatted output instead of str()
inside the realprint() function.

BIG light bulb moment! I had no idea the str() statement was truncating!
I *did* search the script for 12 or trunc (being a newbie!) and saw
nothing. Hence my silly questions tonight!

SNIP

def realprint(a):
 for i in range(len(a)):
 outfile.write(str(a[i]))
 if i  len(a)-1:
 outfile.write( )
 else:
 outfile.write(\n)



output.write({0:.15f}.format(x))

You may want to play with the format a bit to get it the way you
actually want it.  Note that the format will happily output nonsense
digits beyond the end of the available precision, so you have to do your
own figuring before deciding what to display.

Hmm, well, I did modify the original script by setting the convergence
test value to 2.005e-16 up from 1e-6, s, I 'guess' 15 sig.figs.
will be OK. I'll have a go! That's 3 orders of magnitude better for
a few key strokes! Great! (maybe...)
John.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] greater precision?

2012-10-29 Thread John Collins

Hi Dave,

You just lost me.


If you don't use any transcendental functions, then a fraction has no
quantization error.  It's totally precise.


Ah ha! Another light bulb moment - two in one night! Thank you Dave,
and all!

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


Re: [Tutor] greater precision?

2012-10-29 Thread John Collins

Hi Dave,

Not silly at all.  I didn't realize str(float) would truncate to 12
digits either.  I found out by experimenting (with 2.7) in the interpreter.

Very gracious of you to say, and generous of you to trouble yourself
to experiment - thank you very much!

Note that it may differ from version to version.  And that's another
reason to use format.

Excellent point!

But please don't just take the format string I supplied as right.  It
is if you always want 15 decimal digits to the right of the decimal
point.  But if you have a number like 50 thousand, then many of those
digits to the right are invalid.
Indeed! As you saw, some outputs are, and really must be output as 
integers. A  1 with a decimal point followed by 15 0's would make a real 
mess of the face/vertex designation table. So I have to be careful where 
I invoke

output.write({0:.15f}.format(x))
or similar, ie, that it operates only on the values I'd like output
that way.
Which raises a question. Is the command 'persistent'? In other words,
if I use it early on, but then wish to output integers, has it 'died
after use', do I need to 'kill it after use', or will python just
default back to what it sees next? I know this sounds silly, but to me
the command 'looks' like it's setting a 'hidden pyton variable' to
15f which may need to be explicitly revoked, or not,...???
John.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] greater precision?

2012-10-29 Thread John Collins

Hi Dave,

Valid question.  However, there are no hidden variables used in format.
Each time you invoke the format method (it's a method of str), it starts
from scratch using only its current arguments.  i can't think of any
sense in which 'default' fits here, either.

Thanks, that's somewhat of a relief. In nfaces.py which outputs like
this
SNIP
point vertex_11_22_27 0.482610585141 0.963539328269 -0.1161816686
point vertex_11_18_28 0.894075981233 0.461195737945 0.403417680839
face face_0 vertex_0_2_29
face face_0 vertex_0_25_29
face face_0 vertex_0_15_25
face face_0 vertex_0_7_15
face face_0 vertex_0_7_12
face face_0 vertex_0_2_12
normal face_0 -0.396087591388 -0.781284022758 0.482400140683
face face_1 vertex_1_15_30
SNIP
there are nested outfile.write commands with logical tests! Best now
I try your suggestions - experiment, I can't break it(!), and if after a 
sleepless night, it's all pea soup, I'll log back in with this 
marvellous group of very knowledgeable and helpful folks!

You do really need to study the format spec, to see what other
parameters may be more useful.  What I supplied is great if all the
digits are to the right of the decimal.

Agreed.

Note, you can also use format on integers, in order to make a fixed
number of columns, for example.  Or to get leading zeroes.  Or whatever.

Interesting...

And realize that the format does not have to be inside the write.  So
you can format to a string, then post-process in some way, before
sending to the write method.

Very interesting!

Incidentally, One of numpy or gmpy is probably a very good idea for
you.  But as I have no experience with either, it just didn't occur to
me.  So I'm glad Peter mentioned one of them.  The only catch I know of
is it's an external dependency, meaning you have to download and install
it into the Python search path.

Yes! A while back, Ramit mentioned;
P.S. If you want large amount of accuracy with number crunching, you
 may want to look into using fixed-precision or binary math libraries.
 Try looking at scipy/numpy or using Decimal instead of floating-point
 numbers. (This is just a suggestion and may be incorrect because I
 have not yet needed such accuracy. )

Which I just searched for and dug up!

Right, I'm off to bash this script like a beginner, and see what
emerges! :) Thanks for so many insights in one night - terrific!
Wish I'd picked this language up *years* ago - it's so foreign to
me now, yet so beautifully useful!

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


Re: [Tutor] greater precision?

2012-10-29 Thread John Collins

Hello,
Just checked my py, and 15 was the report! Wish I had known
that factoid - thank you, for a very complete coverage of
the broader intrinsic 'machine' + system precision - it actually
makes sense  to me now - it's a calculation!

On 30/10/2012 2:02 AM, eryksun wrote:
SNIP

A double has 53 bits of precisions, which is 53*log10(2) =~ 15.955
decimal digits. However, one often sees the numbers 15 and 17 quoted
for the precision. It depends. A double is guaranteed to accurately
store a string with 15 decimal digits (round trip). But each 15-digit
decimal string maps to many doubles:

  from struct import unpack

  format(unpack('d', '\x76\x99\x99\x99\x99\x99\xb9?')[0], '.15f')
 '0.100'
  format(unpack('d', '\xbd\x99\x99\x99\x99\x99\xb9?')[0], '.15f')
 '0.100'

  0xbd - 0x76 + 1   # doubles that round to 0.100
 72

(Note: my Intel processor is little endian, so the least significant
byte is index 0 in the packed double, such as '\x76'.)

However, to exactly represent each double requires 17 decimal digits:

  format(unpack('d', '\x76\x99\x99\x99\x99\x99\xb9?')[0], '.17f')
 '0.09951'
  format(unpack('d', '\x77\x99\x99\x99\x99\x99\xb9?')[0], '.17f')
 '0.09952'

Python says the precision is 15 decimal digits:

  import sys
  sys.float_info.mant_dig   # bits of precision
 53
  sys.float_info.dig# decimal digits
 15


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


Re: [Tutor] greater precision?

2012-10-29 Thread John Collins

Thanks Mark. I 'stuck' with 2.7.2 for these old scripts,
unless I want to totally rewrite them. They are so elegant,
this would realy amount to starting from scratch. I get 15
reported, and that's going to be sufficient for these 'as
they are'. For more, it's a go back to year zero exercise
I feel.
John.
On 30/10/2012 2:15 AM, Mark Lawrence wrote:
SNIP

It's 16 digits with 3.3.0.


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


Re: [Tutor] greater precision?

2012-10-29 Thread John Collins

Hi Mark,
Thanks. I wouldn't know C if I fell over it. Until recently,
the *only* language I'd ever used was (HP, GW)BASIC aside
from Fortran 101, 3 decades ago!
John.

On 30/10/2012 2:45 AM, Mark Lawrence wrote:
SNIP

If you're more comfortable with C you can use printf style formatting
see http://docs.python.org/2/library/stdtypes.html#string-formatting


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


[Tutor] python 2.7.1

2012-09-06 Thread john
print hello world #this is just something to say





 /Users/jonathan/Documents/hello.py 
  File stdin, line 1
/Users/jonathan/Documents/hello.py 
^
SyntaxError: invalid syntax

what am i doing wrong?

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


[Tutor] understanding pydoc try

2012-08-30 Thread John Maclean
What does the first line from `pydoc try` actually mean? This does not 
look like the syntax that one is supposed to use.


try_stmt  ::= try1_stmt | try2_stmt

I can write simple statements as shown below, but I want to actually 
understand what I am doing.




try:
import io
print(importing io)
except ImportError:
print(nothing to import)
foo = None
try:
import somefunctionthatdoesnotexist
print(importing ...)
except ImportError:
print(nothing to import)
foo = None

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


Re: [Tutor] understanding pydoc try

2012-08-30 Thread John Maclean

On 08/30/2012 03:05 PM, Dave Angel wrote:

On 08/30/2012 09:30 AM, John Maclean wrote:

What does the first line from `pydoc try` actually mean? This does not
look like the syntax that one is supposed to use.

try_stmt  ::= try1_stmt | try2_stmt


You're looking at the first of three BNF statements.  BNF (Backus Naur
Form, or something like that) is a way of describing a grammar.  i'll
quote the whole thing here, and try to explain it.

The following is from Python 3.2's pydoc:

try_stmt  ::= try1_stmt | try2_stmt
try1_stmt ::= try : suite
  (except [expression [as target]] : suite)+
  [else : suite]
  [finally : suite]
try2_stmt ::= try : suite
  finally : suite

The first statement says that a try_stmt is one or the other of two
formats.  This simply says there are two syntaxes you can use, depending
on what try features you want.

The second lists the (most common, i expect) syntax.  It has a literal
try token, followed by a literal colon token, followed by a suite of
statements (that's defined elsewhere, but would include simple
statements, if statements, and so on.  It wouldn't include def or class,
presumably).

Then there are one or more except clauses.  Note the trailing + which
means this element may be repeated, but must be present at least once.

Then there is an optional else clause.

Then an optional finally clause.

These must be present in the specific order stated above.  And you can't
(for example) have an else without an except, because except is one or
more times.

The second syntax does not include the except nor else clauses.

Is that clearer?



Thanks. This is a heck of a lot more clearer to me! BNF, huh? Another 
set TLA that I don't need to know ;-)


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


Re: [Tutor] understanding pydoc try

2012-08-30 Thread John Maclean

On 08/30/2012 05:15 PM, Alan Gauld wrote:

On 30/08/12 15:43, John Maclean wrote:


Thanks. This is a heck of a lot more clearer to me! BNF, huh? Another
set TLA that I don't need to know ;-)


Actually, BNF is one of those useful skills for any programmer because 
almost every language is 'formally' described using it - at least 
since the days of Algol, for which it was invented.


A simplified version of it is also used to define most command line 
tools and their arguments so its definitely worth learning, at least 
the basics. It can save a lot of typing when you want to precisely 
specify the allowed grammar in a problem.


There are tools which can translate BNF like text into something close 
to code, which is useful if you ever have to define your own 
programming language. Admittedly not something most programmers ever 
need to do, but it does happen occasionally that its the easiest way 
to solve a problem. (The so-called mini-language design pattern)





My main issue is that I am a sysadmin and not a programmer. I am aware 
of pydoc but not of BNF. So I was a bit taken aback when I saw the BNF 
syntax. It was obvious to me that syntax of the try statements were not 
python syntax but had no clue how to parse it. BTW - where in pydoc is 
it mentioned, (or anywhere else for that matter), to refer to BNF?





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


[Tutor] PYFTDI Library for FT232H

2012-08-02 Thread John Battle
I am relatively new to Pyton and am trying to use a library called 
pyftdi which is used to establish communication with USB chips made by 
FTDI.  I have been able to install the library and write a simple piece 
of code to discover my interfaces (I have two FT232H devices 
connected).  The following code seems to work to accomplish that:


#!/usr/bin/python
from pyftdi.pyftdi.ftdi import *
vps=[(0x0403,0x6014)]
devs=Ftdi.find_all(vps)
print devs

However I cannot figure out what to do next.  The devices in question 
are programmed n the FT245 Syncronous mode and I need to send a short 
string to one of them to start a data download and then receive straming 
data on the other one.


I have a C program that will do this but I need to do it in Python.

Any help would be gretly appreciated.

Thanks

John Battle



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


[Tutor] user created lists

2012-04-11 Thread john moore
Hello Pyhton World,

I'm new at this and was wondering how I create a number of user specified lists?

Example:

How many list would you like to create?
User inputs 5
creates five lists,
list1 []
list2 []
list3 []
list4 []
list5 []

I can create one with append, but I don't know how to loop it to create five 
different named list.. 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] which gets called

2012-04-06 Thread John Fabiani
Hi,

I want to create a class that inherits two other classes.

class NewClass( A,B)

But both A and B contain a method with the same name (onKeyDown). 

If my NewClass does not contain something to override the methods which one 
would be called if

myinstance = NewClass()

myinstance.onKeyDown()


Second to insure the right one is called is it possible to do the following

NewClass(object):

  def onKeyDown(self, event):
  b.onKeyDown(event)

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


Re: [Tutor] which gets called

2012-04-06 Thread John Fabiani
On Friday, April 06, 2012 06:54:28 AM John Fabiani wrote:
 Hi,
 
 I want to create a class that inherits two other classes.
 
 class NewClass( A,B)
 
 But both A and B contain a method with the same name (onKeyDown).
 
 If my NewClass does not contain something to override the methods which
 one would be called if
 
 myinstance = NewClass()
 
 myinstance.onKeyDown()
 
 
 Second to insure the right one is called is it possible to do the following
 
 NewClass(object):
 
   def onKeyDown(self, event):
   b.onKeyDown(event)
 
 Johnf

Thanks guys!

The class I'm creating is inheriting from classes I did not create.  And of 
course the inherited classes are from different authors.  So I'm attempting to 
create a wrapper and the problem comes from the keyboard events.  Each of the 
classes has a onKeyDown method and I only want one to work and then pass the 
data to the second.

But you have helped (along with the links).  And I have successfully got the 
right method called.  The issue is now getting the second (B) to fire 
correctly.

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


  1   2   3   4   5   6   7   8   9   10   >