Re: [Tutor] General method for creating a partitioned window

2011-08-09 Thread Knacktus

Am 09.08.2011 16:44, schrieb Shwinn Ricci:


I am using wxPython and OpenGL, although I would prefer to run a script
in Maya, but this does not seem efficient for what I want to do, since
maya only allows for 3-D visualization, not simultaneous 2-D/3-D viewing
(i.e., side-by-side)



On Thu, Aug 4, 2011 at 7:37 PM, Alan Gauld alan.ga...@btinternet.com
mailto:alan.ga...@btinternet.com wrote:

On 04/08/11 20:52, Shwinn Ricci wrote:

Say I want one half of a 720 x 480 window be dedicated for
creating a
2-D structure, and the other half for a 3-D structure. There
would be a
line 1 or 2 pixels thick straight down the window that would
divide the
two sectors. How does one go about doing this without creating two
separate GUI window frames?


You would need one frame (or widget) with an opengl context with 2 
independent viewports. I don't think that's supported by any framework. 
You probably have to use two widgets. But that's no problem, as long as 
you can use layouts and styles to get the desired appearance of the two 
widgets (i.e. to make them appear as one).


I do not have my code with me right

now, I
can post as soon as I have access to it.


You need to give yus more detail. This kind of thing is very GUI
frame-work specific. Are you using Tkinter? wxPython?, Cocoa on MacOSX?

They are all different.

And because you want to do graphics you also need to tell us what
graphics toolkit you are using? OpenGL? Something else?

Or are you trying to script Blender or Maya or some other 2D/3D
modelling tool?


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



_
Tutor maillist  - Tutor@python.org mailto:Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/__mailman/listinfo/tutor
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 maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to get the keys of a dict inside a dict. ValueError: too many values to unpack

2011-08-07 Thread Knacktus

Am 07.08.2011 17:37, schrieb Kayode Odeyemi:

Hello all,

Please I need help figuring out this permutation.

I have a dict like this:

x = {'pk': 1L, 'model': 'trans', 'fields': {'updated': 2011, 'tel':
3456}, {'pk': 2L, 'model': 'trans2', 'fields': {'updated': 2011,
'tel': 34510};
This is not a dict, it's a tuple of two strings. (By the way, the ; is 
only needed if you would want to place several statements in one line, 
which you shouldn't do.)


A tuple of dicts would be:

x = {'pk': 1L, 'model': 'trans', 'fields': {'updated': 2011, 'tel': 
3456}}, {'pk': 2L, 'model': 'trans2', 'fields': {'updated': 2011, 'tel': 
34510}}


Note the additional closing } for each entry. You can loop over the 
entries of your tuple and check the type:


for entry in x:
print type(entry)

Now you can extend this loop and loop over the keys and values for each 
entry:


for entry in x:
for key, value in entry.items():
print key
print value

If key is fields then value is another dictionary. So if you wish you 
could also get the entries of those dicts explicitly:


for entry in x:
for key, value in entry.items():
print key
if key == fields:
for field_key, field_value in value.items():
print %s % field_key
print   %s % field_value
else:
print   %s % value

For string formatting used here see:

http://docs.python.org/library/stdtypes.html#string-formatting-operations

HTH,

Jan



#loop through and get the keys of each
for k,v in x:
 keys = dict(x).keys()
print keys

I get ValueError: too many values to unpack

Any help will be much appreciated.

Regards


--
Odeyemi 'Kayode O.
http://www.sinati.com. t: @charyorde



___
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] Object Management

2011-07-27 Thread Knacktus

Am 27.07.2011 15:51, schrieb Alexander:

Hello everyone. I'm having trouble wrapping my mind around a project I'm
working on. My goal is to create a program that manages (allows its
users to manipulate, search by criteria and edit) objects. There is one
type of object, for example I'll say it's a car.

There will be a central data file containing all of the cars and
multiple users will have access to it at once. I'm having trouble here,
I've done some research on MOO and twisted but I'm not sure where to turn.


Sounds familiar ;-) ... on the way a lot of question are likely to 
arise. Like, OK, I've got a database. Do I load all the data at once to 
the client or only on request? What about concurrent usage by different 
clients (users)? How about authentification and authorisition? If I 
build a rich client (a python programm with GUI and network connection 
to the database), how do I manage the objects on the client?


As James already hinted, there're fantastic python web frameworks. They 
have solutions for almost all the questions that will cross your path. 
There're some relgious wars about which is the best. In my opinion 
Django is the best for starters. Do some tutorials, read the Django book 
and you'll get an idea about the overall architcture, models, views, 
templates, etc.




Additionally I'll need a GUI! tkinter? Does anyone have any suggestions
on how to get started with tkinter? I'm overwhelmed with the amount of
documentation I've had to read and think I have to read to accomplish my
goal.


I've written a rich client with PyQt which talks via web services to a 
web server. It's a lot of work! You have a lot of options, performance 
is amazing, but due to the complexity I would recommend to start with a 
web interface.


If you really need or want a rich client, you should look into Dabo:

http://dabodev.com/about

There's also another rich application framework which uses PyQt and 
looks very good, but I forgot the name. I'm not sure about wether this 
is free or commercial.





Thanks for reading, Alex.ander

--
Alexander



___
Tutor maillist  -  Tutor@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] Descriptors and type declaration order

2011-07-14 Thread Knacktus
Hi guys,

I've got the following (not working) code:

class Attribute(object):

def __init__(self, attribute_name, att_type_name):
self._attribute_name = attribute_name
try:
self._attribute_type = globals()[att_type_name]
except KeyError:
self._attribute_type = getattr(globals()[__builtins__],
att_type_name)

def __get__(self, obj, obj_type):
return getattr(obj, self._attribute_name)

def __set__(self, obj, value):
if isinstance(value, self._attribute_type):
setattr(obj, self._attribute_name, value)
else:
raise ItemTypeException(self._attribute_type, type(value))

class BaseItem(object):

ident = Attribute(ident, int)
owner = Attribute(owner, str)
item = Attribute(item, BaseItem)

if __name__ == __main__:
print About to create an item
test = BaseItem()
print OK

The problem is that the descriptors are created when the module is
evaluated. But at this time the class BaseItem is not known yet. Any ideas?

Cheers,

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


Re: [Tutor] Combining two Dictionaries

2011-04-30 Thread Knacktus





def combine(d1, d2):
 for key in d1:
 if key in d2:
 d2[key] += d1[key]


[Remark]
I usually avoid changing function arguments. But later on you're talking 
about using this function as a method a class, so d1 and d2 would be 
instance attributes I guess.




When I initialize the class which holds these dictionaries, though, I need
to make sure that all the keys contained in d2 match the keys of d1. Thus I
tried:
d1 = {'a': 0, 'b': 0, 'c': 0}


Now d1 holds the address of a dict in memory. The dict contains your data.


d2 = d1


Now d2 holds the same address of the same dict in memory. d1 and d2 
refer to the same dictionary.



My understanding was that d2 looked at d1 once, grabbed its keys and values,
and went off to do its own thing.


You would need to use copy() explicitly.

import copy

d2 = copy.copy(d1) # swallow copy

# or a deep copy
# - copies also referenced objects recursively
# usefull if you have e.g. lists as values in your dict
# and want them copied too.

d2 = copy.deepcopy(d1)


 Just as if you typed:

x = 3
y = x
x = 6
y still holds the value 3.


Python has mutable and immutable types. Str and int, for example, are 
immutable. Dicts and list for example are mutable.
The statement x=6 binds x to a new object, because the object with value 
3 cannot be changed.


There are a lot of  explanations about mutable and immutable types. Much 
better then I could. You could search the list, for example here: 
http://dir.gmane.org/gmane.comp.python.tutor

or the web or see this overview in the docs:
http://docs.python.org/reference/datamodel.html#objects-values-and-types

Generally, I wouldn't copy an existing dict to make sure the other dict 
has the same values. The data must come from somewhere. I would check 
the data, then you wouldn't need to check the container.


Finally, you could use dict.get with a default set to 0, then you 
wouldn't need to care, e.g. (using dict comprehension and creating a new 
dict):


def combine_2(d1, d2):
return {key: d1[key]+d2.get(key, 0) for key in d1}

But that's a bit dirty semantic wise, better to check the input data ... 
just to show you the syntax.



HTH,

Jan

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


Re: [Tutor] Gtk - relational data display and edit

2011-04-26 Thread Knacktus

Am 26.04.2011 17:34, schrieb bod...@googlemail.com:

Hi,

I am reading in data from a csv file which will be in a format like this

User1, attrib1, attrib2
User2, attrib1, attrib2
Etc.

And need to display this in a window. My initial thought was to use gtk.Entry 
widgets because I will need to edit this data, but I don't think this will work 
as I will also need to read the data back, in relation to the user column, e.g 
I will have something like

[Psuedocode]
For I in entries:
 A = usercolumn
 B = attrib1column
 C = attrib2column

 Somefunction(A,B,C)
[/psuedocode]

I don't think I could use this method with entry boxes as I have no idea how 
many entries there will be (column length will be fixed) so I can't create the 
entry widgets beforehand



You could use a table widget. I'm sure GTK has something like that (I'm 
using Qt).


Otherwise, creating a dynamic widget for one set of your data is not 
as hard as it might sound. You need to keeping references to the 
composing widgets, for example in a dict. Here's some PyQt Pseudocode:



# You can retrieve the dictionary and the fieldnames with help of the
# csv module
att_name_to_value = {User: User1, Att1: attrib1, Att1: attrib1}
fieldnames = [User, Att1, Att2]

att_name_to_line_edit = {}

# This is Qt specific
layout = QtGui.QGridLayout()

for row, fieldname in enumerate(fieldnames):
label = QtGui.QLabel(fieldname)
line_edit = QtGui.QLineEdit(att_name_to_value[fieldname]
att_name_to_line_edit[fieldname] = line_edit
# add the label to the first col
layout.addWidget(label, row, 0)
# add the line_edit to the second col
layout.addWidget(line_edit, row, 1)

my_main_widget = QtGui.QWidget()
my_main_widget.setLayout(layout)


Now, if you need to read the changed data from the widget (triggered by 
a button_clicked event or what ever) you can call a function to read the 
data like this:



def read_data_from_widget(att_name_to_line_edit):
for att_name, line_edit in att_name_to_line_edit.items():
# do the conversion, e.g. PyQt
new_text = str(line_edit.text())
# do whatever you wish with the new data ...


HTH,

Jan





Anyone have any suggestions?

Thanks,
Bodsda
Sent from my BlackBerry® wireless device
___
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] counting a list of elements

2011-04-01 Thread Knacktus

Am 01.04.2011 19:16, schrieb Karim:



Hello,

I would like to get advice on the best practice to count elements in a
list (built from scractch).


It's not clear to me what your starting point is.

If you don't have a list and don't need a list, but have a large number 
of objects you create in your code sequentially or a large number of 
other events and you want to know how many of those objects exist / 
events have occured, then simply use a counter while creating.


If you have a list (for whatever reason), then use len().

HTH,

Jan


The number of elements is in the range 1e3 and 1e6.

1) I could create a generator and set a counter (i +=1) in the loop.

2) or simply len(mylist).

I don't need the content of the list, indeed, in term of memory I don't
want to wast it. But I suppose len() is optimized too (C impementation).

If you have some thought to share don't hesitate.

Karim
___
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] Meta language and code generation

2011-04-01 Thread Knacktus

Am 01.04.2011 19:09, schrieb Karim:


Hello All,

I would to ask you if somebody has experience or can give direction in a
new project I have.
I have a meta language description (in xml) from which I should generate
code on different
languages. In my case, lisp and tcl.


You need to provide more information of your description to get some 
specific hints. The other day a had a xml file containing a business 
object model with hierarchy and relations. Then I wrote a code generator 
to build a module with Python classes for each business item. The code 
generator created properties for lazily resolving relations modelled via 
ids in the database and stuff like that. This was very straightforeward 
using a simple print statements like the following:


print class %s(object):\n % class_name
print def __init__(self, %s) % constr_arg
...

Cheers,

Jan



Any idea in term of design, examples, links will be appreciated!

Kind Regards
Karim
___
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] counting a list of elements

2011-04-01 Thread Knacktus

Am 01.04.2011 19:16, schrieb Karim:



Hello,

I would like to get advice on the best practice to count elements in a
list (built from scractch).
The number of elements is in the range 1e3 and 1e6.

1) I could create a generator and set a counter (i +=1) in the loop.

2) or simply len(mylist).

I don't need the content of the list, indeed, in term of memory I don't
want to wast it. But I suppose len() is optimized too (C impementation).

If you have some thought to share don't hesitate.


Just a general suggestion: Provide code examples. I know most of the 
times you don't have code examples yet as you're thinking of how to 
solve your problems. But if you post one of the possible solutions the 
experienced guys here will very likely direct you in the proper 
direction. But without code it's hard to understand what you're after.


Cheers,

Jan




Karim
___
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] Meta language and code generation

2011-04-01 Thread Knacktus

Am 01.04.2011 20:56, schrieb Karim:

On 04/01/2011 08:29 PM, Knacktus wrote:

Am 01.04.2011 19:09, schrieb Karim:


Hello All,

I would to ask you if somebody has experience or can give direction in a
new project I have.
I have a meta language description (in xml) from which I should generate
code on different
languages. In my case, lisp and tcl.


You need to provide more information of your description to get some
specific hints. The other day a had a xml file containing a business
object model with hierarchy and relations. Then I wrote a code
generator to build a module with Python classes for each business
item. The code generator created properties for lazily resolving
relations modelled via ids in the database and stuff like that. This
was very straightforeward using a simple print statements like the
following:

print class %s(object):\n % class_name
print  def __init__(self, %s) % constr_arg
...

Cheers,

Jan



In fact in xml I have something like that:

A metafunction in fact kind of

metfunc name=call_back_do_stuff_function
parameterx/parameter
parametery/parameter
/metafunc


I have to generate the call_back_do_stuff_function(x,y) in lisp and tcl
according to a catalog of specs
of what this function must do generically.

I can do prints for each metafunctio I read but my concern is is there
std libs to help to have good design
and methodology. Is it interesting to use command module of something
like that, is interesting to use
a parser like pylex or pyparsing? I have 50 metafunctions in catalog for
now.

In fact, my point is to have a great extensive design methodology.
Strategy pattern would suit?
Other patterns? std modules?



No ideas about patterns or standarad lib modules from my side, but a 
short description of how I would do it:


Create an abstraction for the catalogue. That's as far as I can see the 
hardest part. Here you have to decide if and how to split the things 
your functions have to do into reusable chunks. Then create code 
generators for these chunks (using print statements). You can name these 
functions and store the references in dicts like 
catalog_comp_name_to_tcl_gen. If you get new functions that need new 
building blocks you can write new generator functions and extend your 
dictionaries.


The generation of your tcl and lisp functions-frames should be straigt 
forward. You need to link the parameters to the building block generator 
functions you've created before.


When you're done with that, you can improve the design step by step. Too 
me, this approach works better than thinking to much about design in 
advance, as often you don't see what you really need unless you've 
started to code.


HTH,

Jan





Lots of question here!

Regards
Karim






Any idea in term of design, examples, links will be appreciated!

Kind Regards
Karim
___
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 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] counting a list of elements

2011-04-01 Thread Knacktus

Am 01.04.2011 21:31, schrieb Karim:

On 04/01/2011 08:41 PM, Knacktus wrote:

Am 01.04.2011 19:16, schrieb Karim:



Hello,

I would like to get advice on the best practice to count elements in a
list (built from scractch).
The number of elements is in the range 1e3 and 1e6.

1) I could create a generator and set a counter (i +=1) in the loop.

2) or simply len(mylist).

I don't need the content of the list, indeed, in term of memory I don't
want to wast it. But I suppose len() is optimized too (C impementation).

If you have some thought to share don't hesitate.


Just a general suggestion: Provide code examples. I know most of the
times you don't have code examples yet as you're thinking of how to
solve your problems. But if you post one of the possible solutions the
experienced guys here will very likely direct you in the proper
direction. But without code it's hard to understand what you're after.

Cheers,

Jan



Thank you all for you answers to clarified I built a collection of
dictionnaries which represent database query on a bug tracking system:

backlog_tables , csv_backlog_table = _backlog_database(table=table,
periods=intervals_list)

backlog_tables is a dictionnary of bug info dictionnaries. The keys of
backlog_tables is a time intervall (YEAR-MONTH) as shown below:

backlog_tables= {'2011-01-01': [{'Assigned Date': datetime.date(2010,
10, 25),
'Category': 'Customer_claim',
'Date': datetime.date(2010, 10, 22),
'Duplicate Date': None,
'Fixed Reference': None,
'Headline': 'Impovement for all test',
'Identifier': '23269',
'Last Modified': datetime.date(2010, 10, 25),
'Priority': 'Low',
'Project': 'MY_PROJECT',
'Reference': 'MY_PROJECT@1.7beta2@20101006.0',
'Resolved Date': None,
'Severity': 'improvement',
'State': 'A',
'Submitter': 'Somebody'},
.
}

_backlog_database() compute the tuple backlog_tables , csv_backlog_table:
In fact csv_backlog_table is the same as backlog_tables but instead of
having
the query dictionnaries it holds only the number of query which I use to
create
a CSV file and a graph over time range.

_backlog_database() is as follow:

def _backlog_database(table=None, periods=None):
Internal function. Re-arrange database table
according to a time period. Only monthly management
is computed in this version.

@param table the database of the list of defects. Each defect is a
dictionnary with fixed keys.
@param periods the intervals list of months and the first element is the
starting date and the
the last element is the ending date in string format.
@return (periods_tables, csv_table), a tuple of periodic dictionnary
table and
the same keys dictionnary with defect numbers associated values.

if periods is None:
raise ValueError('Time interval could not be empty!')

periods_tables = {}
csv_table = {}

interval_table = []

for interval in periods:
split_date = interval.split('-')
for row in table:
if not len(split_date) == 3:
limit_date = _first_next_month_day(year=int(split_date[0]),
month=int(split_date[1]), day=1)
if row['Date']  limit_date:
if not row['Resolved Date']:
if row['State'] == 'K':
if row['Last Modified'] = limit_date:
interval_table.append(row)
elif row['State'] == 'D':
if row['Duplicate Date'] = limit_date:
interval_table.append(row)
# New, Assigned, Opened, Postponed, Forwarded, cases.
else:
interval_table.append(row)
else:
if row['Resolved Date'] = limit_date:
interval_table.append(row)

periods_tables[interval] = interval_table
csv_table[interval] = str(len(interval_table))

interval_table = []

return periods_tables, csv_table


This is not the whole function I reduce it on normal case but it shows
what I am doing.
In fact I choose to have both dictionnaries to debug my function and
analyse what's going
on. When everything will be fine I will need only the csv table (with
number per period) to create the graphs.
That's why I was asking for length computing. Honnestly, the actual
queries number is 500 (bug id) but It could be more
in other project. I was ambitious when I sais 1000 to 10
dictionnaries elements but for the whole
list of products we have internally It could be 5.


I see some similarity with my coding style (doing things by the way), 
which might not be so good ;-).


With this background information I would keep the responsibilities 
seperated. Your _backlog_database() function is supposed to do one 
thing: Return a dictionary which holds the interval and a list of result 
dicts. You could call this dict interval_to_result_tables (to indicate 
that the values are lists). That's all your function should do.


Then you want to print a report. This piece of functionality needs to 
know how long the lists for each dictionary entry are. Then this 
print_report function should be responsible to get the information it 
needs by creating it itself or calling another function, which has the 
purpose to create the information. Latter would be a bit too much, as 
the length would be simply be:


number_of_tables = len(interval_to_result_tables

Re: [Tutor] New person greets you all!

2011-03-11 Thread Knacktus

Am 11.03.2011 17:12, schrieb Yaşar Arabacı:

Hi,

First of all, I want to greet you all since this is the first time I
will be using this mail groups.

I consider myself being familiar with programming logic, structures in
general. I do/did lots of PHP programming. I know python and PHP is
pretty much different things, I am saying this just to show yourself my
level of understanding on programming. I am not computer major or
anything, but I am highly interested in.

Today, I decided to make a chat application using python. I have chosen
python because I know its powerfull and easy to use. The first step for
me to go should be, clearly, begin learning how to use it :)

My question is, where would you recommend for me to read tutorials, see
example etc. What is the best approach would be?


The official Python tutorial is a good start. You get familiar with the 
Python documentation as well.

http://docs.python.org/py3k/
(Find the link to the tutorial on this page.)

A classic and famous tutorial is here:
http://www.alan-g.me.uk/
If you have any questions about this, you're lucky to be on this list, 
because the author of this ressource is very active here. (One of or the 
founder of the list?)


Another classic is Dive into Python. You can find it easily with 
google. There're two versions, Python 2.x and 3.x. By the way, I would 
recommend starting with Python 3.2. Some 3rd party libs and web 
frameworks are not ported yet, but for your chat app you should be very 
happy with Python 3.2.


Recently, a tutorial with a bit of a different style has been finished. 
I haven't done it and the style is not my cup of tea, but some people 
like it a lot. It's called Learning Python the hard way. Google for 
the url...


Now, welcome to the beach of programming!

Jan



___
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] very odd math problem

2011-03-10 Thread Knacktus

Am 11.03.2011 04:23, schrieb Alex Hall:

Hi all,
I am trying to get a list of ordered pairs from the below function. In
my code, evaluate is more exciting, but the evaluate here will at
least let this run. The below runs fine, with one exception: somehow,
it is saying that -2+2.0 is 4.x, where x is a huge decimal involving
E-16 (in other words, a really tiny number). Does anyone have any idea
what is going on here?


You can find some great posts at a thread about decimal floating point 
numbers some weeks ago for background reading. Or (and) look at this:


http://docs.python.org/tutorial/floatingpoint.html#floating-point-arithmetic-issues-and-limitations

Now my guess is:

i is calculated as a sum of floats of step 0.1. That means you have in 
the base 2 representation an approximation of 0.1, not exactly 0.1, 
but something like 0.10123123. When i reaches approximately 
2.0, it is actually 2.0342374 (or what ever). On the 
other hand, e1 can be represented precisely if it's 2.0 in the base 2 
representation. But the sum of e1 and i is actually your tiny number. 
That's why 2.0 - 2.0 is exactly 0.0, but (20*0.1 - 2.0 is not).


To elaborate, you could add some lines to your code:

def getCoords(f, e1, e2, step=.1):
  time=0
  i=0
  coords=[]
  while time=e2:
print time=+str(e1)+++str(i)+=
print type(e1)
print type(i)
time=e1+i
time_2 = e1 + e2
print %s, %.24f % (time, time) # app 0.0
print %s, %.24f % (time_2, time_2) # exact 0.0
coords.append((time, evaluate(f, time)))
i=i+1*step
  return coords

The reason why Python prints i as 2.0 in the first print statement is 
probably due to some internal auto-rounding when using str(). See the 
last paragraph of the link above. No idea, what's exactly going on under 
the hood.


HTH,

Jan




def getCoords(f, e1, e2, step=.1):
  #returns a list of (x,y) tuples from e1 to e2 at the given accuracy (step)
  time=0
  i=0
  coords=[]
  while time=e2:
   print time=+str(e1)+++str(i)+=
   time=e1+i
   print time #watch this line when above is -2+2.0
   coords.append((time, evaluate(f, time)))
   i=i+1*step
  return coords

def evaluate(x,y): return x*y


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


Re: [Tutor] very odd math problem

2011-03-10 Thread Knacktus

Am 11.03.2011 06:05, schrieb Steven D'Aprano:

Alex Hall wrote:

Hi all,
I am trying to get a list of ordered pairs from the below function. In
my code, evaluate is more exciting, but the evaluate here will at
least let this run. The below runs fine, with one exception: somehow,
it is saying that -2+2.0 is 4.x, where x is a huge decimal involving
E-16 (in other words, a really tiny number). Does anyone have any idea
what is going on here?



Let's reword the description of the problem...

2.0 - 2 is a really tiny number close to 4e-16

Welcome to the wonders of floating point maths! Repeat after me:

Floats are not real numbers... floats are not real numbers...
floats are not real numbers... everything you learned about
arithmetic in school only *approximately* applies to floats.

Half :) and half :(

First off, anything involving e-16 isn't a huge decimal, it's a tiny
decimal, very close to zero, no matter what the x is:

0.0004x

Also, although you say -2 + 2.0 in a comment, that's not actually what
you calculate. I know this even though I don't know what you calculate,
because I can test -2 + 2.0 and see that it is exactly zero:

  -2 + 2.0 == 0
True

Somewhere in your calculation you're probably calculating something
which *looks* like 2.0 but isn't. Here's an example:

  x = 2 + 1e-14
  print(x)
2.0
  x == 2.0
False

but you can see the difference by printing the float with more decimal
places than shown by the default view:

  repr(x)
'2.01'


Another problem: you calculate your values by repeated addition. This is
the wrong way to do it, because each addition has a tiny little error,
and repeating them just compounds error upon error. Here's an example:


  x = 0.0
  for i in range(10):
... x += 0.1
...
  x == 1.0
False
  print(x)
1.0
  repr(x)
'0.99989'


The right way is to do it like this:


  x = 0.0
  for i in range(1, 11):
... x = i*0.1
...
  x == 1.0
True

This ensures that errors don't compound.


Some further resources:

http://floating-point-gui.de/
http://introcs.cs.princeton.edu/91float/

David Goldberg used to have a fantastic (although quite technical)
discussion of floating point issues, What Every Computer Scientist
Should Know About Floating-Point Arithmetic:

http://docs.sun.com/source/806-3568/ncg_goldberg.html

Unfortunately, since Oracle bought Sun, they've removed the article.
Bastards.

If you can find a copy of Apple's old Apple Numeric Manual (2nd
Edition), it has a fantastic introduction by William Kahan. Even though
the book is about Apple's SANE, a lot will apply to other floating point
systems as well.

Google on William Kahan and read his stuff :)




Damn, you're fast!! ;-))
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] BLAS Implementation on Python

2011-03-08 Thread Knacktus

Am 08.03.2011 20:00, schrieb Alan Gauld:


Stefan Behnel stefan...@behnel.de wrote

He doesn't have to write it, as it is very obvious, that no Python code
on earth (even written by Guido himself ;-)) stands a chance
compared to
Fortran or C. Look at this:


There is one big proviso. The C or Fortran needs to be well written


It's seriously hard to write computational Python code that is faster
than C code, though.


Agreed, it was the assertion that no Python code on earth...stands
a chance... that I was objecting to.

There are many areas where the C code would have to be pathologically
bad to be beaten by Python, but there are plenty of places where only
slightly inefficient C code can be competitive relatie to Python.


Maybe there're those areas, but the top posters question is about 
reimplementing BLAS, which is a highly optimized package for linear 
algebra. And in this area no pure Python code on earth on any currently 
available Python implementation stands a chance performance wise to one 
of the C or Fortran implementations.




Alan G.

___
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] BLAS Implementation on Python

2011-03-07 Thread Knacktus

Am 07.03.2011 01:50, schrieb Mahesh Narayanamurthi:

Hello,

I am thinking of implementing a BLAS package in pure python. I am
wondering if this is a good idea.


I don't think so. Usually people write extensions to the CPython 
implementation (when talking about performance, we need to talk about 
Python implementations like CPython, Jython or PyPy) in C to do high 
performance stuff. Pure CPython is (depeneding on the problem) 
magnitudes slower than C.


Also, there's NumPy SciPy. Check those out.

More comments below ...

My design goals are:



[1] Efficient manipulation of Matrices and
 Vectors using pure python objects and
 python code.

No, not efficient in terms of performance.

[2] Targetted to run on Python3

Good idea. NumPy and SciPy will be (are already?) ported.

[3] Extensive use of defensive programming
 style
[4] To serve as a reference design for
 future High Performance Code in Python

The future of High Performance Python is probably PyPy.

[5] To serve as a reference material in
 classroom courses on numerical computing
 or for hobbyist programmers

Good idea, as Python is clear and nice to read.


Thanks,
Mahesh Narayanamurthi



___
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] BLAS Implementation on Python

2011-03-07 Thread Knacktus

Am 07.03.2011 22:44, schrieb Steven D'Aprano:

On Tue, 8 Mar 2011 12:28:56 am Knacktus wrote:

Am 07.03.2011 01:50, schrieb Mahesh Narayanamurthi:

Hello,

I am thinking of implementing a BLAS package in pure python. I am
wondering if this is a good idea.


Sure, why not? Even if nobody uses it, it looks good on a resume and you
will hopefully learn a lot.



I don't think so. Usually people write extensions to the CPython
implementation (when talking about performance, we need to talk about
Python implementations like CPython, Jython or PyPy) in C to do high
performance stuff. Pure CPython is (depeneding on the problem)
magnitudes slower than C.


Typical pure Python code is between 10 and 100 times slower than C, but
talking about implementations, it is the aim of the PyPy project to use
Just In Time compilation and clever optimizations to meet *and exceed*
the speed of static C compilers. In just a few years, with a handful of
people working on it, and a tiny grant from the EU, they have already
doubled the speed of CPython. If PyPy could get *half* the love and
attention that CPython gets, who knows what they could accomplish?

(If only Google had thrown some work into PyPy, instead of wasting time
with Unladen Swallow that never went anywhere useful...)

But the beauty of Python is that if a piece of code is too slow, you can
rip it out into an extension written in C or Fortran while keeping the
rest of the library in Python. See, for example, the re module, which
has a front end written in Python and the regex engine in C.

The itertools module is another good example. Using a few primitives
written in C, itertools allows Python code to run efficiently and
quickly.



Also, there's NumPy SciPy. Check those out.

More comments below ...

My design goals are:

[1] Efficient manipulation of Matrices and
  Vectors using pure python objects and
  python code.


No, not efficient in terms of performance.


How do you know how efficient his code will be before he's even written
it?


He doesn't have to write it, as it is very obvious, that no Python code 
on earth (even written by Guido himself ;-)) stands a chance compared to 
Fortran or C. Look at this:


http://shootout.alioth.debian.org/u32/performance.php?test=spectralnorm

CPython implementation runs 12 mins compared to 8 secs of a Fortran 
implementation. PyPy is about 100 secs, which is remarkable but still 
far off.




[...]

The future of High Performance Python is probably PyPy.


Exactly why a pure-Python library *may* be useful. Today it will be
slow, running under CPython, but in five (unlikely) or ten years
(possibly), it may be fast, running under PyPy.

Or not. Who can tell what the future will bring?




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


Re: [Tutor] Help!

2011-03-03 Thread Knacktus

Am 03.03.2011 22:28, schrieb Andrew Bouchot:

okay so this is my comp sci lab
*

Problem:

*ProductionTime.py It takes exactly 2 minutes and 7 second to produce an
item. Unfortunately, after 143 items are produced, the fabricator must
cool off for 5 minutes and 13 seconds before it can continue. Write a
program that will calculate the amount of time required to manufacture a
given number of items. *

Output:

*Output the amount of time D days HH:MM:SS *

Sample Input :

*

numItems =1340 Represents the numbers items to be manufactured

*

Sample Output :

*

2 days 00:03:17

this is the coding i have written for it!

numitems= int(raw_input(Enter the number of items needed to be
manufactured:))
seconds=numitems*127
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
print %d:%02d:%02d % (h, m, s)

but how would i add the 5 min and 13 seconds after 143 items have been
produced???
For any given number of item, how many cool-down periods do you have in 
total?

What's the prodcution time without cooling?

---||---||--||--
producing  |cooling |producing  |cooling |producing |cooling |producing

HTH,

Jan





___
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] A class that instantiates conditionally ?

2011-03-02 Thread Knacktus

Am 01.03.2011 07:49, schrieb David:

I have an idea that might clean up my code slightly, if I can make one
of my classes
clever enough to refuse to instantiate itself if a necessary condition
is not met.


I think that's too clever ;-). Instead, you could create a function 
which has the only and explicit purpose to decide wether or not to 
create the class, e.g.


def class_for_condition(condition):
if condition:
return MyClass()
return None

and use this throughout your code, e.g.

my_object = class_for_condition(condition)

But to me, it sounds a bit like trouble in general. As Alan said, you 
have to deal with two options for my_object in the remaining code. I 
can't really judge without seeing what you want to do later on, but 
maybe you have the chance to branch on a higher abstraction level?


if condition:
do_all_this_stuff() # do the things with my_object
else:
do_the_other_stuff() # do the things you don't need my_object

Cheers,

Jan



Below I propose some example code that seems to achieve this, and I am
asking here
for feedback on it, because I have not written much python. So I might be doing
something unwise due to fiddling with things I don't totally understand.

My aim is that instead of writing this:

class MyClass:
pass

condition = 0

if condition:
my_object = MyClass()
else:
my_object = None

I could instead write this:

class MyClass_2:
# put the if-test here inside the class

my_object_2 = MyClass_2(condition)

to achieve the goal that (my_object_2 == None) when (condition == False).

I read the (ver 2.6) Python Language Reference
  Section 3.4.1. Basic customization
  Section 3.4.3. Customizing class creation

Most of the content there is way beyond my current understanding, but I came up
with the following code, which seems to work:

class MyClass_2(object):
def __new__(self, condition):
if condition:
return object.__new__(self)
else:
return None

condition = 0
my_object_2 = MyClass_2(condition)
print my_object_2
condition = 1
my_object_2 = MyClass_2(condition)
print my_object_2

Can anyone see any technical or style issues with that? Or
alternatively reassure me that it is completely ok?
Thanks.
___
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] couchdb.mapping 'Document' class

2011-03-01 Thread Knacktus

Am 01.03.2011 16:19, schrieb Emanuel Lauria:

Hi everyone,

I'm trying to map a couchdb document to a python object using
couchdb.mapping. I'm stuck in the very first part were it says I should
declare a Python class that inherits from the 'Document'.. Where does
this 'Document' superclass comes from? I can't resolve it. Or do I have
to create it? How? Could someone point me in to the right direction?

  import couchdb

  class Person(Document):
... name = TextField()
...
Traceback (most recent call last):
File stdin, line 1, in module
NameError: name 'Document' is not defined



It looks like the class Document is located in the module couchdb.client 
(it's chapter 3.3).

This should work:

import couchdb.client

class Person(couchdb.client.Document):

...

HTH

Jan



Thanks for your help, and please forgive me if im too n00b in this. I
havent found any documentation except
http://packages.python.org/CouchDB/mapping.html which is not enough.

Thanks



___
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] Object, methods, class

2011-02-26 Thread Knacktus

Am 26.02.2011 18:49, schrieb Christopher Brookes:

Hi,
Is there in Python private/protected attributes in class like in other
langage ?

Yes, there is. But it's protected by convention not compiler ;-).
Check out this:
http://docs.python.org/tutorial/classes.html#private-variables


--
Brookes Christopher.



___
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] Object, methods, class

2011-02-26 Thread Knacktus

Once again a very insightfull answer. Much appreciated! Same to you, Alan.
I paricularly like the even longer answer. It remindes us of how lucky 
we are using Python and brings me light in dark times when I wish I had 
better code completion in my IDE for my own spaghetti-code ;-))

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


Re: [Tutor] Unintentionally manipulating a list

2011-02-25 Thread Knacktus

Am 25.02.2011 15:49, schrieb ranjan das:


I am facing the following problem


I have a list of the form

INPUT= [ [ ['A1-N','A2-Y','A3-N' ],['B1-Y','B2-N','B3-N' ] ], [.] ]


and I want an output of the form (selecting only those elements which
have a Y associated with them)

OUTPUT=[ ['A2-Y', 'B1-Y'],[] ]


I wrote the following code. Although it gives me the desired output, it
CHANGES the list INPUT

now after i run the code I get INPUT as the same as OUTPUT (which i dont
want to happen). I have used the copy function but it still is not
working. Any help or pointers is appreciated

_CODE_

from copy import copy

temp=copy( INPUT )
OUTPUT=temp



for i in range(len(temp)):

 for j in range(len(temp[i])):

 for k in range(len(temp[i][j])):

 if temp[i][j][k][-1]=='Y':

 OUTPUT[i][j]=temp[i][j][k]


There's no need for an index. You can iterate over the elements directly 
and create the result on the fly:


results = []
for sub_list in INPUT:
sub_results = []
for sub_sub_list in sub_list:
sub_sub_results = []
for entry in sub_sub_list:
if entry.endswith(Y):
sub_sub_results.append(entry)
if sub_sub_results:
sub_results.append(sub_sub_results)
if sub_results:
results.append(sub_results)

Uuppsy daisy, not really readable code ;-). Your solution looks cleaner. 
I bet, some of the gurus can come up with a real pythonic solution.


Cheers,

Jan








___
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] dict['_find']

2011-02-20 Thread Knacktus

Am 20.02.2011 05:14, schrieb Max Niederhofer:


Hello all,

Hello Max,


first post, please be gentle. I'm having serious trouble finding an
alternative for the deprecated find module for dictionaries.

The code (from Zed Shaw's Hard Way, exercise 40) goes something like
this. Hope indentation survives.

cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'}
I use a naming convention for dicts that has made me very happy on 
several occasion ;-):

key_to_value, in your case
state_to_city = {...}


def find_city(themap, state):
 if state in themap:
 return themap[state]
 else:
 return Not found.

cities['_find'] = find_city

Did you put this entry into the same dictionary as the data on purpose?
Or is the purpose a kind of dispatch? Something that could be a dict on 
its own, like

private_function_name_to_function = {'_find': find_city}
You should try to keep things seperate and explicit.


while True:
 print State? (ENTER to quit),
 state = raw_input(  )

 if not state: break

city_found = cities['_find'](cities, state)
print city_found

My question is - how do I rewrite this using an alternate module given
find is deprecated? Grateful for all suggestions or pointers. For
reference, I'm using 2.6.1 on darwin.

Thanks so much for your help.

Best,
Max

--
Dr. Maximilian Niederhofer
Founder, Qwerly
http://qwerly.com/ | http://qwerly.com/max
+44 78 3783 8227
___
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] scraping and saving in file

2010-12-29 Thread Knacktus

Am 29.12.2010 10:54, schrieb Tommy Kaas:

Hi,

I’m trying to learn basic web scraping and starting from scratch. I’m
using Activepython 2.6.6

I have uploaded a simple table on my web page and try to scrape it and
will save the result in a text file. I will separate the columns in the
file with #.

It works fine but besides # I also get spaces between the columns in the
text file. How do I avoid that?

This is the script:

import urllib2

from BeautifulSoup import BeautifulSoup

f = open('tabeltest.txt', 'w')

soup =
BeautifulSoup(urllib2.urlopen('http://www.kaasogmulvad.dk/unv/python/tabeltest.htm').read())

rows = soup.findAll('tr')

for tr in rows:

 cols = tr.findAll('td')

 print  f,
cols[0].string,'#',cols[1].string,'#',cols[2].string,'#',cols[3].string


You can strip the whitespaces from the strings. I assume the 
string-attribute returns a string (I don't now the API of Beautiful 
Soup) E.g.:

cols[0].string.strip()

Also, you can use join() to create the complete string:

resulting_string = #.join([col.string.strip() for col in cols])

The long version without list comprehension (just for illustration, 
better use list comprehension):


resulting_string = #.join([cols[0].string.strip(), 
cols[1].string.strip(), cols[2].string.strip(), cols[3].string.strip(), 
cols[4].string.strip()])


HTH,

Jan






f.close()

And the text file looks like this:

Kommunenr # Kommune # Region # Regionsnr

101 # København # Hovedstaden # 1084

147 # Frederiksberg # Hovedstaden # 1084

151 # Ballerup # Hovedstaden # 1084

153 # Brøndby # Hovedstaden # 1084

155 # Dragør # Hovedstaden # 1084

Thanks in advance

Tommy Kaas

Kaas  Mulvad

Lykkesholms Alle 2A, 3.

1902 Frederiksberg C

Mobil: 27268818

Mail: tommy.k...@kaasogmulvad.dk mailto:tommy.k...@kaasogmulvad.dk

Web: www.kaasogmulvad.dk http://www.kaasogmulvad.dk



___
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] Choice of Python

2010-12-28 Thread Knacktus

Am 28.12.2010 14:41, schrieb Stefan Behnel:

Abdulhakim Haliru, 28.12.2010 13:38:

I come from a Cakephp, zend framework angle cutting through ASP.net,VB
and
C# at an intermediate level.
[...]
Is python really worth the pain or should I just skip it ?


Given that you already invested your time into learning all of the above
(which basically cover about 1 1/2 of several main corners of
programming), I think you should really take some time off to unlearn
some of the bad habits that these particular languages tend to teach
you. Python is a truly good way to do that.

My advice: don't spend too much time reading books. Pick a task that
sounds like fun to implement and give it a try with Python. Some would
propose exercises from project Euler for this or maybe pygame, but
you'll likely have your own idea about what's fun and what isn't.
+1 for jumping into coding. You seem to have enough experience in 
programming generally. With Python the fun comes with the experienced 
productivity. At least, that was the case with me.
Learning the syntax is not the deal, but how to design your app. You can 
use the best of OO, functional and procedural programming.
Also, Python is to me the best general purpose language. You can create 
little helper scripts, web apps and rich client apps with PyQt or WxPython.




Stefan

___
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] vim as a python editor

2010-12-15 Thread Knacktus

Am 15.12.2010 23:26, schrieb Paul Griffiths:

Hi - I'm a beginner at programming and Python.

I have been looking for an editor to replace Idle and tried out a few.
I liked Geany but decided on vim because I am also learning Linux
and the vim skills might be useful.  I run Python 2.6.5 on Ubuntu 10.04.

How have those of you who use vim configured it?  I have looked
on the web but got a bit confused by the advice and options.

I am currently following some of the advice in the on-line tutorial at
http://openbookproject.net/thinkcs/python/english2e/app_c.html and

- installed the full version of vim (sudo apt-get install vim-gnome)
- created a .vimrc file in my home directory and entered
 syntax enable
 filetype indent on
 set et
 set sw=4
 set smarttab
 map f2 :w\|!python %

- added the following to .bashrc:
 EDITOR=vim
 export EDITOR

I open up a terminal in the folder where I keep my python files and
create two additional tabs in this terminal.  I use the first tab to
run python, the second one to run vim and the third one for running
linux commands such as ls to list the folder contents.

Is this is a reasonable approach?  Thank you for any feed back.
Sure. I'm more an IDE-guy for Python now, but in my before-days with 
Fortran I used pretty much this approach.
Even though I'm using an IDE (on Windows) myself, I would recommend 
learning vi/vim.


Regs,

Jan




PaulG



___
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] vim as a python editor

2010-12-15 Thread Knacktus

Am 15.12.2010 23:26, schrieb Paul Griffiths:

Hi - I'm a beginner at programming and Python.

I have been looking for an editor to replace Idle and tried out a few.
I liked Geany but decided on vim because I am also learning Linux
and the vim skills might be useful.  I run Python 2.6.5 on Ubuntu 10.04.

How have those of you who use vim configured it?  I have looked
on the web but got a bit confused by the advice and options.

I am currently following some of the advice in the on-line tutorial at
http://openbookproject.net/thinkcs/python/english2e/app_c.html and

- installed the full version of vim (sudo apt-get install vim-gnome)
- created a .vimrc file in my home directory and entered
 syntax enable
 filetype indent on
 set et
 set sw=4
 set smarttab
 map f2 :w\|!python %

- added the following to .bashrc:
 EDITOR=vim
 export EDITOR


I forgot:
Here some more information about vim and Python:

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

Some guy tuned vim to the maximum with code completion and everything. 
But start simple to learn the basics. You can extend anytime later.


Jan



I open up a terminal in the folder where I keep my python files and
create two additional tabs in this terminal.  I use the first tab to
run python, the second one to run vim and the third one for running
linux commands such as ls to list the folder contents.

Is this is a reasonable approach?  Thank you for any feed back.


PaulG



___
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] making onthefly attributes persistent

2010-12-14 Thread Knacktus

Am 13.12.2010 23:50, schrieb Jojo Mwebaze:



On Mon, Dec 13, 2010 at 8:44 PM, Alan Gauld alan.ga...@btinternet.com
mailto:alan.ga...@btinternet.com wrote:


Jojo Mwebaze jojo.mweb...@gmail.com
mailto:jojo.mweb...@gmail.com wrote

Assuming i have a class bank as below .

class bank(object):
  def __init__(self, bal=0):
  self.bal = bal
  def deposit(self, amount):
  self.bal+=amount
  print self.bal

I define a method debit - which i add to the class onthefly

bank.debit = debit


#I can also add an attribute owner

myaccount.owner = 'jojo'


My problem is how to make the added attributes, 'owner' and 'debit'
persistent automatically


If that's your only problem with this approach congratulations!
How does your orther code know when/if these dynamic
operations/data exist so as to use them? If they just assume
they exist then why not just add them in the definition. Even as nulls?

While Python allows you to dynamically add features to classes/objects
its not something I would recommend unless you have a really good
reason - not least because you bring upon yourself all sorts of
problems!

If you are determined to do so you can make the objects persistent
using the approach I outline on my tutorial but adding a loop to cycle
over the contents of dir(). But you may find that recovering the
objects - especially if they have a mixed set of attribnutes - presents
even more problems...

IMHO This is a feature of python that should be considered unorthodox
and only to be used when no other approach will work!

HTH,




Thanks Allan for the feedback, the idea is to write a method like
store() on the object, that probably looks up all these changes and
commits them into the database.


Assuming you're planning to use a database with a scheme (e.g. a 
relational DB) you need to define your tables in advance anyway. Even if 
you're using a schemeless DB, where do you track which data is in it? 
How do you build your queries dynamically? This can become very messy.
Overall, I think Alan's recommendation to avoid dynamic attribute 
creation is the one to follow.




Please let me know where to find approach you propose in your tutorial.
I read your tutorial when i was just initiated to python, a reference
would be helpful to help me find the soln without hustle.

Cheers



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


___
Tutor maillist  - Tutor@python.org mailto: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 maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Ressources for licensing

2010-12-12 Thread Knacktus

Am 12.12.2010 03:42, schrieb David Hutto:

On Sat, Dec 11, 2010 at 9:52 AM, Knacktusknack...@googlemail.com  wrote:

Hi everyone,

can anybody recommend a lib or some other ressources about license
mechanisms of desktop applications written in python. I'm thinking of a
license-key that can be used to limit the time the application can be used.
I also need to exploit the usage of a license server.



You probably need:

def license_this(self):
 print touch mine

license_this(self)



I don't get it. Could you please explain a bit?





Cheers,

Jan
___
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] Any recommend of UML tool and UI design tool for python?

2010-12-12 Thread Knacktus

Am 12.12.2010 19:16, schrieb Alan Gauld:


cajsdy caj...@gmail.com wrote

Either paid or free open source is fine.
I'm creating automation frame work. Idealy it includes:

test plan management,
test manager across windows, unix, linux, solaris and other os.
UML documentation for python scripts
IDE tool for python on windoes and linux
UI design tool for python(best is integrated with IDE)


Eclipse would be the logical choice and there are a few free
UML editor plug-ins. I've tried one (can't recall the name) and
although a bit clunky compared to commercoal versions it
worked fine for small class and sequence diagrams.

If you don't need full CASE modelling facilities someting
like a drawing tool such as Dia, Visio or Smartdraw might
suffice.

If you want full CASE features (model validation, simulation,
code generation, reverse engineering fof diagrams from code, etc)
then I think you will need to pay - and probably quite a lot! I've
used both Borland Together and IBM RSA. I prefer Borland
although IBM produces prettier diagrams - but I found it a
lot less intuitive. to use. Both come as Eclipse plugins and
work with whatever version control tools Eclipse is using.

There are other standalone UML tools too but it depends how
much of UML you want to use. If it's only a few basic class diagrams,
sequence diagrams and state diagrams then prettty much
anything will do. If you need to get into the more structural
aspects of UML (deployment diagrams, components, nested states,
activity charts, use-cases etc) then you might want to look at
paying out some money.



If you're willing to pay for a CASE tool then check out Enterprise 
Architect from http://sparxsystems.eu/
For the massive features I think it's reasonable priced (professional 
edition for 165 Euro + VAT).
UML-Source Code integration with Python ... I don't know if it really 
works. You would need to limit your code to pure OO-style. Such 
integration might work with Java and C# (Enterprise Architect can do 
this: Change code - update UML and vice versa). Nevertheless. 
Enterprise Architect supports Python for reverse engineering.


For designing UIs: You will need another tool. It depends on your GUI 
toolkit. If you're planning to use PyQt  as GUI toolkit (which I can 
only highly recommend) you're lucky. It has GUI designer, which is quite 
nice.

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


[Tutor] Ressources for licensing

2010-12-11 Thread Knacktus

Hi everyone,

can anybody recommend a lib or some other ressources about license 
mechanisms of desktop applications written in python. I'm thinking of a 
license-key that can be used to limit the time the application can be 
used. I also need to exploit the usage of a license server.


Cheers,

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


Re: [Tutor] Which non SQL Database ?

2010-12-05 Thread Knacktus

Am 04.12.2010 23:42, schrieb Jorge Biquez:

Hello all.

Newbie question. Sorry.

As part of my process to learn python I am working on two personal
applications. Both will do it fine with a simple structure of data
stored in files. I now there are lot of databases around I can use but I
would like to know yoor advice on what other options you would consider
for the job (it is training so no pressure on performance). One
application will run as a desktop one,under Windows, Linux, Macintosh,
being able to update data, not much, not complex, not many records. The
second application, running behind web pages, will do the same, I mean,
process simple data, updating showing data. not much info, not complex.
As an excersice it is more than enough I guess and will let me learn
what I need for now.
Talking with a friend about what he will do (he use C only) he suggest
to take a look on dBase format file since it is a stable format, fast
and the index structure will be fine or maybe go with BD (Berkley)
database file format (I hope I understood this one correctly) . Plain
files it is not an option since I would like to have option to do rapid
searches.

What would do you suggest to take a look? If possible available under
the 3 plattforms.
As a non SQL Database I can recommend MongoDB. It's a document store, 
which uses binary json as format. You can create secondary indexes and 
also perform more sophisticated queris.
The main advantage from my point of view is the ease of use. 
Installation was a breeze and it has an easy to use python driver. Note 
that you need a 64-bit OS to use it with bigger data volumes (I remember 
 3 GB, but it's all on their website).





Thanks in advance for your comments.

Jorge Biquez

___
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] Which non SQL Database ?

2010-12-05 Thread Knacktus

Am 05.12.2010 10:41, schrieb Alan Gauld:


Jorge Biquez jbiq...@icsmx.com wrote


Talking with a friend about what he will do (he use C only) he suggest
to take a look on dBase format file since it is a stable


True enough and Dabo is worth a look since it provides not only a dbase
format db engine but a good GUI builder tool too.

However


(Berkley) database file format (I hope I understood this one
correctly) . Plain files it is not an option since I would like to
have option to do rapid searches.


Why not use SQL?
SQLlite comes with Python, is small, easy to use and if necessary can be
used in-memory and as such fast.
Once you have decided to go down the database route then not using SQL
nowadays is a very odd decision. Its rather liike going out looking for
a car that has solid types instead of pneumatics. Why would you want to?
The NoSQL databases seem to be en vogue. Some big internet companies 
have started to use them, like Google with its Big Table. That's how I 
stumbled across them. There're a lot of discussions going on on the 
internet which is better for which use case. There're some cases where 
one kind of the database type is the clear winner, but most use cases 
can be modelled with both.


My conclusion and what draw me finally to MongoDB over PostgreSQL and 
SQLAlqemy was:


1) Really the ease of use (from setting up the database and later when 
it comes to administration and scaling, which is particularly easy). 
MongoDB is very useful for prototyping.


2) I don't need complex transactions and the ability to perform complex, 
not in advanced known queries.


I'd say SQL-DBs are more sophisticated but more complex to use. For the 
sake of learning, go with SQL. It doesn't hurt having a driver license. 
If you need to go to the bakery around the corner the driver license 
doesn't prevent you to jump on your bicycle.


Cheers,

Jan



HTH,



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


Re: [Tutor] data structures

2010-12-01 Thread Knacktus

Am 02.12.2010 02:51, schrieb Dana:

Hello,

I'm using Python to extract words from plain text files. I have a list
of words. Now I would like to convert that list to a dictionary of
features where the key is the word and the value the number of
occurrences in a group of files based on the filename (different files
correspond to different categories). What is the best way to represent
this data? When I finish I expect to have about 70 unique dictionaries
with values I plan to use in frequency distributions, etc. Should I use
globally defined dictionaries?
Depends on what else you want to do with the group of files. If you're 
expecting some operations on the group's data you should create a class 
to be able to add some more methods to the data. I would probably go 
with a class.


class FileGroup(object):

def __init__(self, filenames):
self.filenames = filenames
self.word_to_occurrences = {}
self._populate_word_to_occurrences()

def _populate_word_to_occurrences():
for filename in filenames:
with open(filename) as fi:
# do the processing

Now you could add other meaningful data and methods to a group of files.

But also I think dictionaries can be fine. If you really only need the 
dicts. You could create a function to create those.


def create_word_to_occurrences(filenames):
word_to_occurrences = {}
for filename in filenames:
with open(filename) as fi
# do the processing
return word_to_occurrences

But as I said, if in doubt I would go for the class.



Dana
___
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] JOB AD PROJECT

2010-11-21 Thread Knacktus

Am 21.11.2010 04:34, schrieb delegb...@dudupay.com:

Hi People,
I am afraid only Alan has said something to me. Is it that solution would never 
come or u guys are waiting to gimme the best?

I agree with what Alan wrote. Your project sounds like real challenge 
even for experienced developers. Even for a team of experienced developers.


You need both deep knowlegde of certain areas and broad knowledge of 
programming, databases and networking/communication. Of course you don't 
get the knowlegde if you don't start to develope a system. But if you 
start with too much and too complex things the risk is that you get 
stuck. There's a saying: You've got so much in your mouth that you 
can't chew anymore. (And you realise it only when it has happened ;-))


To avoid that risk of suddenly being buried in complexitiy and not 
knowing what to do and where to move next, I'd recommend to follow a 
step by step learning path:


With your project in mind, plan 3-5 smaller projects. Each project has 
one of the key technologies for your final project as focus. For example:


1) Create a Django site where users can register and unregister. 2 or 3 
simple web forms. Nothing more. You'll learn all the database stuff and 
Django basics.

2) Build a system that handles SMS communication.
3) Build some a nice html+JS websites.
...
...

Then you can tackle the last and most challenging task, which is to 
design your overall system: Infrastructure, layers and your 
business-logic modules/classes.


Go in small steps! That will also keep your motivation up as you get 
feedback after each step.


HTH,

Jan


Please help.
Sent from my BlackBerry wireless device from MTN

-Original Message-
From: Alan Gauldalan.ga...@btinternet.com
Sender: tutor-bounces+delegbede=dudupay@python.org
Date: Sat, 20 Nov 2010 09:00:52
To:tutor@python.org
Subject: Re: [Tutor] JOB AD PROJECT


delegb...@dudupay.com  wrote


I have done some extensive reading on python.
i want to design a classifieds site for jobs.


Have you done any extensive programming yet?
Reading alone will be of limited benefit and jumping into
a faurly complex web project before you have the basics
mastered will be a painful experience.

I'm assuming you have at least some experience of
web programming in other languages for you to take
such a bold step?



I am taking this as my first project and would appreciate any help.
I am looking in the direction of python, maybe django.


The choice of tools is fine, but its a big task for a first
ever Python project!

HTH,




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


Re: [Tutor] Paper Book

2010-11-18 Thread Knacktus

Am 18.11.2010 15:31, schrieb Srinidhi Rao:

Hi,

Thanks for the reply guys, I would prefer a Paper Book as I don't have a
kindle(amazon) and also the PDF is not so suitable out here.. (the power
cuts hamper continuity :( )

@Alan,
Nice website for a beginner. I glanced through your webpage and thanks
for the link.
I too have an Electronics background, I am only new to Python and of
course OOPs... can you suggest any good books(paper) on Python.

Thanks and Regards,
|| SRX ||



My first book was Learning Python from Mark Lutz. Today, I think it's 
a bit too long. (OK, now I have learned most of the stuff in the book). 
It's certainly not the wrong choice for a beginner book. And now I'm a 
convinced Python fan. So it must have somehow worked.


Programming in Python 3 from Mark Summerfield is also nice. I've 
bought it recently and like it. But can't comment on how it feels 
reading it as a complete novice.


The best book in my opinion, however *not* a beginner book, is from 
David Beazley: Python Essential Reference. As the name tells it's a 
reference, but with a lot of good recommendations and right to the 
point. That might be a good choice as a second book. Or you could read 
it in parallel to your beginner book - look up the topics you covered in 
the reference book.


There's another good one (also for beginners): Dive into Python. There's 
a free edition on the web:


http://diveintopython.org/

If you like it you can also by a dead tree version. (I've learned a 
new expression today, too ;-))


HTH,

Jan




___
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] Advantages or disadvantages on Platform?

2010-11-04 Thread Knacktus

Am 04.11.2010 20:43, schrieb Jorge Biquez:

Hello all.

I am newbie and studying and working hard learning python. Per your
advise I am on 2.7 . I have one question for you.

I can work on Windows (XP) or under Ubuntu .

The advantage of using Ubuntu is that you learn how to work in a 
Linux/Unix environment. Most servers are using Linux/Unix based 
operation systems. Therefore if your goal is to develop web-apps, I 
would go for Ubuntu.
Also, once you've set up your development environment and know how to 
work with your shell, working on Linux is incredible fast and fun. I 
used to work professionally for engineering stuff on Linux/Unix before 
moving to Windows. Productivity on Linux for OS operations like 
organising your files and quickly modifing scripts is by far higher than 
on Windows.
Another advantage is, that there're good editors well integrated. If you 
have the time to learn vim, go for it.


After telling you all this, I have to admit that I'm currently on a 
Windows 7 machine and also perfectly happy. Using an IDE makes the OS 
less important.



Do you see any advantages or disadvantanges to be working in one or
another ?
My main goal , for now, is use Python for web applictions.

Thanks in advance for your comments and advice.

Jorge Biquez

___
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] mutable types

2010-11-02 Thread Knacktus

Am 02.11.2010 13:51, schrieb John:

Hello, I thought the following should end with G[1] and G[0] returning
20. Why doesn't it?

In [69]: a = 10
a is a reference to an immutable object of type int with value 10. 
Somewhere in memory is an object of type int with value 10 stored. This 
object cannot be changed. a is just a name that references to the 
memory adress.

In [70]: G = {}
In [71]: G[0] = [a]
now, G[0] holds a reference to a mutable object of type list with an 
immutable object of type int with value 10 as its content. So, your list 
holds as item the memory adress of an object int with value 10. Your 
list knows nothing about other names (like a), that refer to the same 
adress in memory. You have handed over the object to the list (or memory 
adress of the object), not the name a.

In [72]: G[1] = G[0]
In [73]: a = 20

Now, you've created a *new* immutable object of type int with value 20.
a now refers to the adress of the new integer object. a has 
forgotten everything about its former reference to the object of type 
int with value 10.
You have *not* changed the old object of type int with value 10. Your 
list in G[0] still holds the memory adress of the first int with value 10.

In [74]: G[1]
Out[74]: [10]
In [75]: G[0]
Out[75]: [10]

??
Now, if you would keep a reference to the list you've handed over to the 
dict, you could change the content of the list, as the list is mutable.


 a = [10]
 G = {}
 G[0] = a
 G[0]
[10]
 a[0] = 20
 G[0]
[20]

Take care of some operations that return a copy of the list:

 a = a[:]
Now, a refernces to a new list, which has also one item of type in 
with value 20. But it's not the same list as originally!

 a[0] = 30
Changing this new list ...
 G[0]
[20]
does not affect the list, we stored in the dict.

HTH,

Jan

___
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] pickle problem

2010-10-12 Thread Knacktus

Am 12.10.2010 19:35, schrieb Roelof Wobben:



Hello,

I have this code :

import urllib
import pickle

image = urllib.URLopener()
image.retrieve(http://www.pythonchallenge.com/pc/def/peak.html,banner.p; )
plaatje = open(banner.p, rb)
plaatje2 = pickle.load(plaatje)

But it gives this output :

Traceback (most recent call last):
   File C:\Users\wobben\workspace\oefeningen\src\test2.py, line 7, inmodule
 plaatje2 = pickle.load(plaatje)
   File C:\Python27\lib\pickle.py, line 1378, in load
 return Unpickler(file).load()
   File C:\Python27\lib\pickle.py, line 858, in load
 dispatch[key](self)
KeyError: ''

The last error indicates that a python module (pickle.py) tried to 
access a dictionary (dispatch) with the key . The expected value 
seems to be a callable as indicated by the (self). But there's no key 
 in it. So, probably, this module was called with improper data.
If you follow up your stack trace to where the error in your code 
occurs, you'll see that something is wrong with unpickling the data in 
your plaatje file.
Obviously, the data could be passed to the pickle module. So no read 
error on the file. What's left? There's probably an issue with the data 
in the file.
Now, you have to know that pickling reads and writes Python objects in a 
certain format. That means you can only load data with pickling, which 
was created by pickling.

Question: Is your data in banner.p properly formatted pickling data?

Note: There're different formats for pickling. Check the docs or a very 
nice source for examples of the Python Standard lib: PyMOTW (Google 
first hit); there's an article about pickling among others. But first 
should be the standard documentation.


What does this mean ?

Roelof

___
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] Hiding Superclass Methods

2010-10-11 Thread Knacktus

Am 11.10.2010 06:24, schrieb Denis Gomes:

Hi Everyone,

I have a basic python question.  I am writing an n dimensional vector
class by inheriting from the builtin python list object.  I want to be
able to hide the parent object's methods in the derived class instances.

Why inheriting then?
Another approach to reusing exisiting methods is to wrap them into your 
newly defined methods. Here you would not inherit from a list, but 
create a list in your class (composition). E.g.


class MyVector(object):

def __init__(self):
self.data = []

def append_data(self, new_data):
self.data.append(new_data)

Actually I use this all the time. And I used this before I knew about 
inheritance.


Inheritance makes sence, when you want to reuse (almost) all methods of 
the superclass, like in GUI toolkits, where you typically have a base 
widget as superclass of a all other widgets.


HTH,

Jan



I know I can overload the method in the derived class and raise some
sort of an implementation error but that is not what I had in mind. I am
also not looking to use numpy. This is strictly for learning purposes.
Is there a way to hide superclass methods in python?

Thanks to all,
Denis


___
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] IDE for Python

2010-10-07 Thread Knacktus

Am 07.10.2010 17:23, schrieb Juan Jose Del Toro:

Dear List;

In your experience what is the best IDE for Python?

I'm using Wing IDE. Very good overall package. I like especially the 
debug probe, which is like an interactive shell in the current stack. To 
me it's a good balance between features and learning curve. The only 
thing I really miss is refactoring support.
That's why I'm currently checking out PyCharm, which is about to be 
released (currently release candidate). It's from the company that 
created IntelliJ. PyCharm is in my opinion by far the most feature-rich 
Python IDE, looks very impressive so far. The only drawback is that it's 
written in Java and has a Swing GUI ;-) (ouuch, it hurts your eyes for a 
while but you get over it, once you discover all those wicked features 
;-)). But Wing isn't excactly eye-candy either.
Both are commercial, but if you code a lot it's worth it. Check out the 
offerings. (I think both are free for Open Source Projects.)


I also tried the free PyDev (an Eclipse plugin), which is very complete 
as well, but I don't get along with the Eclipse world.


So, check out Wing and PyCharm.

Cheers,

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


Re: [Tutor] how to extract data only after a certain condition is met

2010-10-06 Thread Knacktus

Am 06.10.2010 18:25, schrieb Eduardo Vieira:

The other day I was writing a script to extract data from a file from
the line where a text is found to the end of the file. The same
functionality is this sed script:
'1,/regexp/'d
I couldn't put my head to work around this and came up with a solution
using list slicing. But how can I do that? I was experimenting with a
simple list and I came up with this. I wonder if I shouldn't you a
while statement, but how?

a = ['m', 'a', 'r', 'i', 'g', 'o', 'l', 'd']
b = True

for letter in a:
if letter != 'i' and b:
continue
elif letter == 'i':
b = False
else:
print letter

Ok. This works, but I wonder if I shouldn't you a while statement, but how?
Why would you want to use a while-loop? You would need to somehow stop 
the iteration (by catching some EOF Exception or the like). I think it's 
fine to use a for-loop as you have a predefined fixed number of 
iterations. I think your approach is OK. Easy to understand. But what if 
there's a second i after the first? In your solution all i are 
skipped. Also, I would choose clearer names:


letters = ['m', 'a', 'r', 'i', 'g', 'o', 'l', 'd', 'i', 'n', 'i', 'o']
skip_letter = True

for letter in letters:
if letter == 'i' and skip_letter:
skip_letter = False
continue  # if you don't want the first occurrence of i
if not skip_letter:
print letter

Cheers,

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


Re: [Tutor] filling 2d array with zeros

2010-09-27 Thread Knacktus

Am 27.09.2010 20:29, schrieb Steven D'Aprano:

On Tue, 28 Sep 2010 03:54:55 am Alex Hall wrote:

Hi again everyone,
I have a 2d array (I guess it is technically a list) which I want to
fill with zeros. Later I will change some values, but any I do not
change have to be zeros. I have two complex for loops, but I tried to
scale things down to a couple list comprehensions and I broke things.
What is wrong with the following line?
self.am=[[(a,b) for a in range(len(self.lines)) a=0] for b in
range(len(self.lines)) b=0]



Start with a single row, of n columns:

[0 for i in range(n)]  # the loop variable i is not used

Now all you need is to set n appropriately:

n = len(self.lines)
[0 for i in range(n)]


Is there an easier way? Yes, you don't even need a list comp:

[0]*n

Now make m rows of the same:

[ [0]*n for i in range(m) ]

And you are done.


You might be tempted to take a short-cut:

[ [0]*n ]*m

but this doesn't work as you expect. This is one of the rare Python
gotchas -- it looks like it should work, but it doesn't behave like you
might expect. Try it and see:


a = [[0]*3]*4
a

[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

a[0][1] = 2
a

[[0, 2, 0], [0, 2, 0], [0, 2, 0], [0, 2, 0]]

What's going on here? It's a little complicated, so let's start with a
simpler situation:


b = [0, 0, 0]
c = b  # c is an alias to the same list as b
d = b  # so is d
e = c  # and e
b[0] = 3
e

[3, 0, 0]

Because both b and e refer to the same list (not copies!) any change to
b *must* also change e. It's like if Barack Obama gets a haircut, so
does the current President of the USA, because they're the same person.

Now stick them in a list:


a = [b, c, d, e]
a

[[3, 0, 0], [3, 0, 0], [3, 0, 0], [3, 0, 0]]

a[0][1] = 4
a

[[3, 4, 0], [3, 4, 0], [3, 4, 0], [3, 4, 0]]

Modify one, modify them all, because in fact they are actually all the
same list.

[ [0]*3 ]*4 behaves the same way. There's no problem in the inner list,
but the outer list doesn't make four copies of [0,0,0], it has *one*
list repeated four times. Modify one, modify them all.


Another extremly helpful explanation for every learner watching the 
mailing list. Steven, you really deserve the golden tutor medal of honor!


Cheers,

Jan

P.S.: You other guys are awesome as well. Amazing mailing list...
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python And reading the Web - Javascript

2010-09-25 Thread Knacktus


Any ideas in general in how to do this appreciated. i don't mind
reading so if you have some good links they are appreciated.



I have no experience myself with this task, but I would look at those 
resource:


1) For reading html pages in addition to the standard-lib modules:

http://www.crummy.com/software/BeautifulSoup/

2) For more advanced stuff it might be worth looking at a webkit 
implementation of Qt via PyQt Bindings:


http://doc.trolltech.com/4.7/qtwebkit.html

here the Python bindings

http://www.riverbankcomputing.co.uk/news

HTH,

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


[Tutor] Best practice for API design handeling collections and single objects

2010-09-22 Thread Knacktus

Hi all,

I've got a question for you about how to best design an API that has to 
handle requests for single objects and collections of those objects.


My naming conventions are: Plural nouns for collections, singular nouns 
for single objects. Key_to_value-style for dictionaries. So I normaly 
know in my code wether I'm handling collections, dicts or single types.


So, here's an simplified example:
#---
class Meals(object):

def __init__(self, id_on_menu_to_meal):
self.id_on_menu_to_meal = id_on_menu_to_meal

#---

Now I need to return one meal by one id_on_menu and also several meals 
by several ids_on_menu.


I can think of three options:

1) create two methods:
#---
def get_meal_by_ident(self, ident):
return self.id_on_menu_to_meal[ident]

def get_meals_by_idents(self, idents):
return [self.get_meal_by_ident(ident) for ident in idents]

#---


2) create one method, which is smart enough to discriminate between the 
input (having fun with the naming conventions ;-)):

#---
def get_meal_or_meals_by_ident_or_idents(self, ident_or_idents):
try:
return self.id_on_menu_to_meal[ident_or_idents]
except KeyError:
return [self.id_on_menu_to_meal[ident] for
ident in ident_or_idents]

#---


3) handle by convention application-wide only collections:
#---
def get_meals_by_idents(self, idents):
return [self.id_on_menu_to_meal[ident] for ident in idents]

#---

Without having too much experience on things like that, my gut feeling 
tells me to use option 1). What would you guys consider as a best 
practice here?


Thanks in advance and cheers,

Jan

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


Re: [Tutor] Can this be done easly

2010-09-19 Thread Knacktus

Am 19.09.2010 10:49, schrieb Roelof Wobben:



Hello,

I have this programm :

class Point:
  def __init__(self, x=0, y=0):
  self.x = x
  self.y = y

class Rectangle(Point):
 def _init_(self, width=0, length=0):
 self.width = width
 self.length = length

You're inheriting the Point Class, but you don't initialise it.
For some detailled description of inheritance in Python I rather suggest 
to check out some tutorials instead of trying to explain it. Also, 
others on this list can do this probably better. Here's one reference:

http://diveintopython.org/object_oriented_framework/index.html

But now some remarks regarding your problem:

First, I would not consider a Rectangle as a special Point. It's not a 
relation like a Sportscar is a Car (is-a-relationship). It's more a 
relation a Rectangle has 4 Points (has-a-relationship), or 1 Point and a 
width and length. So, it's probably better to express your Rectangle 
class like this:


class Rectangle(object):
def __init__(self, base_point, width=0, length=0):
self.base_point = base_point
self.width = width
self.length = length

then you go (with German names ;-)):

punkt = Point(3,4)
rechteck = Rectangle(punkt,20,30)

In your Rectangle class, the __init__ method takes only two arguments 
(not counting the instance: self), but you're passing three arguments.


At the beginning, the error messages are a bit confusing, because they 
count the instance as one of the arguments. So it tells you, that you 
have given 4 arguments, but you might wonder Hey, I gave you 3.


HTH,

Jan



punt = Point(3,4)
rechthoek = Rectangle (punt,20,30)

Now I wonder how I can change this to rechthoek = rectangle (punt,20,20)
This one gives as error message  :

Traceback (most recent call last):
   File C:\Users\wobben\workspace\oefeningen\src\test.py, line 12, inmodule
 rechthoek = Rectangle (punt,20,30)
TypeError: __init__() takes at most 3 arguments (4 given)

Roelof

___
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] What are singletons good for?

2010-09-18 Thread Knacktus

Hey all,

the usual explanation for the usage of a Singleton goes like this:

Use a singleton if you want to make sure, that only one instance of a 
class exists.


But now I ask myself: Why should I call the constructor of a class more 
than once if I only want one instance?
After all, I decide in my code when to create an instance or when to 
pass an existing instance around.


Example in pseudocode:

class Session(object):
Hold a dictionary of ident_to_data_objects

def __init__(self, ident_to_data):
self.ident_to_data = ident_to_data

Now, that would be a typical singleton use case. I want one instance 
of this class application-wide. For example in a View class:


class View(object):
Create fancy views

def __init__(self, session):
self.session = session

In my code I use these classes like this:

class MainApp(object):
Do some stuff with the data_objects

def __init__(self):
self.session = Session()
self.view = View(self.session)

Would a singleton usage in the View class look like that?

class View(object):
Create fancy views

def __init__(self):
self.session = Session()

What's the point? Is it the spared typing when instanciating a lot of 
View classes (I wouldn't need to pass the session to the constructor). 
Or are there some more advantages (instead of passing the same instance 
aorund)? Also, what would you guys consider as disadvantages?



Another question related to this topic is, if I would use a module as a 
singleton (as suggested by Steve and other), how would I import it the 
instances of a class? Maybe like this?


class View(object):
Create fancy views

import session

def do_something(self, ident):
self.certain_data_object = session.ident_to_data[ident]

A lot of questions, so thanks in advance for any comments!

Cheers,

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


Re: [Tutor] selecting elements from dictionary

2010-09-14 Thread Knacktus

xdic
{11135457: [1], 11135492: [1], 11135913: [1], 11135436: [1, 2],
11135699: [1, 2], 11135702: [1, 3], 11135901: [1]}


I want to print only those items that have [1,2] and [1,3] in any order,
such as [1,2] or [2,1], [3,1] or [1,3]


  for item in xdic.keys():
... if [1,2] in xdic[item]:
... print item


You can loop over the values directly:

xdic = {11135457: [1], 11135492: [1], 11135913: [1], 11135436: [1, 2], 
11135699: [1, 2], 11135702: [1, 3], 11135901: [1]}


for values in xdic.values():
if len(values) == 2:
print values

or if you only want values which contain 1 and 2 or 3:

for values in xdic.values():
if 1 in values and 2 in values or 3 in values:
print values

or a combination of the above, where you check the length and the 
content of the list.


HTH,

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


Re: [Tutor] design question

2010-09-11 Thread Knacktus

Am 10.09.2010 16:11, schrieb Albert-Jan Roskam:

Hi Jan,

Here's a screendump of my program: http://nl.tinypic.com/r/2qtlojc/7 .
This might make my description a little bit clearer. The beautiful
sunset will in reality be a dull, handwritten form. ;-)

Regarding the iterator pattern, I was referring to this:
http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html#iterators-and-generators
Inside my program I have to keep a list of all the image files that are
scheduled for data entry. The main purpose is to be able to read in the
image files one by one. Another one of the purposes of this list is to
show some information on the title bar. Currently, my program only has a
'next' button and the fact that implementing a 'previous' button is
causing problems suggests to me that I have to look for a more
fundamentally better solution.
Sounds to me that the easiest solution would be to simply use a list to 
hold the images, a reference to the current image and your desired 
methods in a class.


class ImageStack(object):

def __init__(self, images=None)
self.images = images or []
self.current_image = None

def next_image(self):
if self.current_image:
current_index = self.images.index(self.current_image)
try:
next_image = self.images[current_index + 1]
except IndexError:
print All images done # or return the first one
else:
next_image = self.images[0]
self.current_image = next_image
return next_image

def prev_image(self):
if self.current_image:
current_index = self.images.index(self.current_image)
try:
prev_image = self.images[current_index - 1]
self.current_image = next_image
return next_image
except IndexError:
print There's no prev image
print There's no current image


You could also track the current_index instead of the current_image. 
That would make the class easier, but how to track the current image 
depends on what other methods you need.


HTH,

Jan


Cheers!!
Albert-Jan

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


Re: [Tutor] What Design Pattern for Document class (NOT URGENT)

2010-09-11 Thread Knacktus

Hi Karim,

it's difficult to comment as to me the problem is not quite clear.
But I try ;-)

You have a complex xml and need to read different data types. For each 
type you have certain rules, how to extract them from the xml (docrules).


You could create a DocRule class, that do nothing but hold instructions 
of how to read and write the xml for each data, e.g. xpathes. For each 
data type you create an instance of that class.


Then, in your main xml Reader class you define a method, that accepts a 
doc rule instance as argument.


doc_rule_1 = DocRule(some_pattern)
doc_rule_2 = DocRule(another_pattern)

class Reader(object):

def __init__(self, filename):
... # create the etree

def get_data_by_doc_rule(self, doc_rule):
... # search the tree based on the doc_rule
... # you can use any type here if it has the correct mehtods

In your get_data_by_doc_rule method you can use any type for the 
doc_rule, that has corresponding attributes and methods (duck typing). 
So you have a lot of flexibility of how to create your doc_rules.


Is that what you're looking for?

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


Re: [Tutor] changing list index start

2010-09-11 Thread Knacktus

Am 11.09.2010 15:46, schrieb Joel Goldstick:



On Sat, Sep 11, 2010 at 9:25 AM, Rance Hall ran...@gmail.com
mailto:ran...@gmail.com wrote:

On Fri, Sep 10, 2010 at 6:14 PM, Lie Ryan lie.1...@gmail.com
mailto:lie.1...@gmail.com wrote:
  On 09/11/10 07:36, Rance Hall wrote:

snip

  In most cases in Python, you would almost never need to reference the
  list's index directly since python makes it easy to use iterators;
  however in your particular case, which is a valid exception,
enumerate()
  takes an optional second argument `start` which defines the
number that
  enumerate start to count with, i.e. you can do:
 
  for i, option in enumerate(mainmenuoptions, 1):
 print('%s. %s' % (i, option))
 
  php provided a way to change this, but I can find no documentation
  that says python can do this as well.
 


Thanks everyone for responding,  Because this menu structure is
repeated many times in my code, the ideal solution would have been to
set index start = 1 in the beginning of the script.

something like sysctl variables in Linux perhaps but in this case only
valid for this program.

Its clear from the responses that this solution is not available in
python, I wish it were, it would make my life much easier for this
project.

I like the approach that Lie suggested, as it seems more natural
python to me as opposed to a workaround.

However this is also only half a solution since it applies to the
printed menus only and not to the response afterward.


It might be more trouble than its worth, but you could use a dictionary:
Instead of this:
 mainmenuoptions = ['Clients','Jobs','Billing','Quotes','To Do
Items','Employee','Exit']

do this:
 mainmenuoptions = {'Clients': 1,'Jobs': 2,'Billing': 3,'Quotes':
4,'To Do
Items': 5,'Employee': 6,'Exit': 7}

Use the phrases as key, and the value as your numeric index.  Or you could
reverse {1: 'Clients', ...

if that suites your already written code.

If you use this pattern in many places, could you not refactor so that
you call
the process with the menu data structures as parameters, and fix the code
in a single place?




+1 for the dictionary. A variation of Joels suggestion might be:

shortcuts_to_name_and_functions = {1: ['Clients', clientsmenu], 2: 
['Jobs', jobsmenu]}


for shortcut, name_and_func in shortcuts_to_name_and_functions.items():
print %s. %s % (shortcut, name_and_func[0])

# later make your call
shortcuts_to_name_and_functions[mainchoice][1]()







It seems that Luke is right looks like we have to do math with the
indexes.

Lie also referred to my particular case as a valid exception, are
there enough other such valid exceptions that requesting a feature
enhancement would gain some traction?

If this is but one of a few special cases, I doubt it would be worth
the time or trouble to formally make the request.

Maybe I should ask if there is a better way to do what I want to do
here. Is there?
___
Tutor maillist  - Tutor@python.org mailto:Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor




--
Joel Goldstick



___
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] design question

2010-09-10 Thread Knacktus

Am 10.09.2010 11:23, schrieb Albert-Jan Roskam:

Hi,

I've made a small data entry program where a picture of a hand-written,
scanned form is shown next to several text entries. The design has been
largely 'bottom up', although of course I started with a rough sketch. I
started with the following classes: Menu (responsible for the widget
creation), Autocomplete (a subclass of the tkinter text entry widget
which I've found on the internet, I wanted to keep this intact), Convert
(responsible for the conversion/cropping of the images, which is
somewhat tedious) and Events (here's the pain spot: this has become a
mixed bag). Originally, the Events class was supposed to contain all the
commands behind the widgets, but it has slowly gotten more
responsibilities. Notably, all methods that deal with reading/writing
the data also live here. The program is about 500 lines of code now,
including blanks.
It's difficult to judge from the outside. It sounds to me like a good 
idea to create separate classes or modules for reading and writing.


I'd like to rewrite to entire program so that (1) all classes have just
one responsibility (2) classes connect to as little other classes (so it
becomes easy to e.g. change to another widget set). I'd love to hear
some thoughts or advice on the new design from you (I hope my
description wasn't too short). Is there a specific design pattern that
could be used?

One specific, additional question: the program has a title bar that
shows something like processing file X (1 of 3; 33%). My colleague
suggested to use the Iterator pattern (gang of four) for this. Is this
(a) overkill (b) a simple opportunity to apply this pattern?

For what exactly do you want to use the pattern?
The iterator pattern is easy to implement in Python. And the usage of 
iterators is even more easy (you can use them in loops without calling 
the next() method explicitly). Lists among others are iterator types. 
You can create your own with generator functions or of course implement 
the iterator-protocol. See here:


http://docs.python.org/library/stdtypes.html#iterator-types

Generally iterator types and generators are great features of Python. 
For a more concrete advice you'd need to explain a bit further what you 
need to do.


HTH

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


Re: [Tutor] Conditional attribute access / key access

2010-08-31 Thread Knacktus



The sizes given are in bytes. So 200,000 instances of this class, plus
the list to hold them, would take approximately 34 megabytes. An entry
level PC these days has 1000 megabytes of memory. Huge? Not even
close.


The items hold a lot of metadata, which I didn't provide in my example. 
Depending on the source up to 30 addional attributes per item, mainly 
strings. And I will have several sources.



So far
there're no restrictions about how to model the items. They can be
dicts, objects of a custom class (preferable with __slots__) or
namedTuple.

Those items have references to each other using ids.


That approach sounds slow and ponderous to me. Why don't you just give
items direct references to each other, instead of indirect using ids?



Unfortunately I have to able to use a relational database later on. 
Currently I'm using a document database for developement. That's where 
the ids are coming from and you're right: They are a pain ... ;-)




If you *need* indirection, say because you are keeping the data in a
database and you want to only lazily load it when needed, rather than
all at once, then the right approach is probably a proxy object:

class PartProxy(object):
 def __init__(self, database_id):
 self._info = None
 self.database_id = database_id
 @property
 def info(self):
 if self._info is None:
 self._info = get_from_database(self.database_id)
 return self._info



That's it! Excactly what I was looking for! That eases the id-pain. Thanks!!

Jan

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


[Tutor] Conditional attribute access / key access

2010-08-30 Thread Knacktus

Hey everyone,

I have a huge number of data items coming from a database. So far 
there're no restrictions about how to model the items. They can be 
dicts, objects of a custom class (preferable with __slots__) or namedTuple.


Those items have references to each other using ids. Fresh from the 
database the items look like this (using dicts as examples):


item_1 = {id: 1, name: root, children_ids: [2, 3]}
item_2 = {id: 2, name: child_1, children_ids: [4]}
item_3 = {id: 3, name: child_2, children_ids: [6, 7, 8]}

Now I'd like to resolve the references on demand. For that purpose I 
think about adding another entry in my dicts (children_obj_refs):


item_1 = {id = 1, name = root, children_ids = [2, 3], 
children_obj_refs = [item_2, item_3]}


To achieve that substitution dynamically on demand I could use a function:

def get_children(item):
try:
return item[children_obj_refs]
except AttributeError:
# pseudocode for retrieving items from db based on ids
fresh_items_from_db = get_items_from_db(item[children_ids])
# Now create new dict entry for future usage
item[children_obj_refs] = fresh_items_from_db

However, I dislike to have to call a function all the time. I'd rather 
get this done under the hood when accessing the dict with 
item[children_obj_refs]. So I've looked into subclassing a dict and 
overwriting the __getitem__() method like this:


class TestSubDict(dict):

def __getitem__(self, key):
try:
return self[key]
except KeyError:
# load item from db and so on ...

But I run into recursion limit problems.

Any recommendations about that? (I'm not restricted to dicts, custom 
classes are OK to, but with __slots__ to limit memory consumption.)


Many thanks in advance and cheers,

Jan

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


Re: [Tutor] Conditional attribute access / key access

2010-08-30 Thread Knacktus

Am 30.08.2010 17:53, schrieb Francesco Loffredo:


Two questions and one doubt for you:
1- How many generations do you want to keep in a single item (call it
dictionary or list, or record, whatever)? I mean, what if some children
have children too, and some of those have more children, etc ?
There's always one level (generation) of children in an item. An item 
can have zero or more direct children. And a lot of grandchildren and 
grandgrandchildren etc. The item-structure represent an assembly 
hierarchy of the parts of a car. So overall the structure can be up to 
about 20 levels deep and consist of up to 20 items overall, where 
the application needs to handle several structures.


2- Are you SURE that there are no circular references in your database?
In your example, what if item_3 was
item_3 = {id: 3, name: child_2, children_ids: [6, 1, 8]}? Is't
it possible that those recursion limit problems you had could come from
some circular reference in your data?
That's a good hint. But the recursion limit doesn't come from that (the 
test data actually had no children. I used a single instance of my dict.)


d- If the number of data items is really huge, are you sure that you
want to keep the whole family in memory at the same time? It depends on
the answer you gave to my question #1, of course, but if retrieving an
item from your database is quick as it should be, you could use a query
to resolve the references on demand, and you wouldn't need a special
structure to hold the rest of the family. If the retrieval is slow or
difficult, then the creation of your structure could take a significant
amount of time.
One thing is, that I have to do some additional calculations when 
resolving the structure. The items will get some kind of 
labels/conditions and versions, further, when resolving the structure a 
set of rules for those conditions is given. At my first shot I'll have 
to do those calculations in the Python code (even if it would be very 
wicked to do stuff like that with SQL). So, I will always have a large 
number of items in memory, as I don't want to call the database for each 
structure-level I want to expand. Also, I'm using a pyqt-treeview 
(AbstractItemModel) for a client-site gui. For this purpose I need to 
create an additional structure, as in the original data items can have 
more than one parent, which is not permitted in the model for the treeview.
The whole idea of replacing the id-references to object-references is to 
enhance performance and make the application code easier.


Thanks for the feedback so far.


Hope this helps,
Francesco




Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com
Versione: 9.0.851 / Database dei virus: 271.1.1/3100 -  Data di rilascio: 
08/29/10 08:34:00




___
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] Help with Object Oriented Programming

2010-08-30 Thread Knacktus

Am 30.08.2010 20:13, schrieb Tino Dai:

Hi Everybody,

I'm beefing up my Object-Oriented Analysis and Design - getting
the gaps in my
knowledge filled in through the Head First OOAD book
(http://headfirstlabs.com/books/hfooad/).
  That book focuses on Java - is there a comparable book for Python? I
have already read the
Alan Gauld's intro on classes, but I'm looking for more. My goal is to
be able to design
and code in Python in an OO fashion exploiting the OO paradigm as it related to
Python at the level of  Kent Johnston (hey, if I'm going to dream,
might as well dream big! :)  ).
Currently, some of the things such as inheritance and encapsulation
apply across OO languages
but interfaces (I know that Zope has this) and mixin's are language
specific constructs.
If anybody could point me in the right direction, that would be great!

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

Hi Tino,

I've started in a very simliar fashion. My first OO-app was a procedural 
Fortran-style Java application ;-)
Then I stumbled over Python but was aware that I had no clue about 
OO-Programming. I read the book Head First OOAD, too. And also stuff 
about design patterns.
At the beginning, it's a bit confusing. There's a lot of overhead 
involved due to Java's static typing. You have to use inheritance, 
interfaces, abstract classes etc. to achieve certain things, e.g. make 
code general (develop for interface not implementation ...) With 
Python the same things can be achieved a loot easier and in the end 
clearer (at least to me). One example are the iterator and visitor 
patterns. Those can be done so smoothly in Python thanks to everything 
is a first class object. It would be fatal to try to translate Java 
Code from the DP book to python.
Overall, Java OO and DP are helpful to know and understanding the ideas 
behind them will help you with Python. But things are done differently 
with Pyhton (don't try to mimick Java!) and you will be very very happy 
about that.

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


Re: [Tutor] Help with Object Oriented Programming

2010-08-30 Thread Knacktus

You could google for

1) Alex Martelli, Design Patterns
He's a Pyton guru and there're some online talks (at Google and some 
conferences) about DP; a bit difficult to understand, well, he's guru ;-)


2) http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html
I like that one.

Also, there're some presentations about the lack of design patterns in 
Python on the web. Google should help or look at the PyCon archives. 
Very useful stuff there.


And finally, 1 gramm of practice weighs more than 1 ton of theory. I see 
it right now after some month absence from coding.


Cheers,

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


Re: [Tutor] type() problem

2010-08-22 Thread Knacktus



fruit=ramadana
print fruit heeft als type, type(fruit)
y=len(fruit)
print y

z=fruit[:3]
print z



These lines put in a module and executed print (using Python 2.7):

fruit heeft als type type 'str'
8
ram

Strange that it doesn't work for you.

I can only advice you to check the file again or run the code from the 
Python shell.


HTH,

Jan


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


[Tutor] Elementtree and pretty printing in Python 2.7

2010-08-20 Thread Knacktus

Hi guys,

I'm using Python 2.7 and the ElementTree standard-lib to write some xml.

My output xml has no line breaks! So, it looks like that:

ItemsProject creation_date=heute//Items

instead of something like this:

Items
Project creation_date=heute/
/Items

I'm aware of lxml which seems to have a pretty print option, but I would 
prefer to use the standard-lib ElementTree which seems not to have a 
feature like this.


Do I miss something using the ElementTree-lib or is it bug?

Cheers,

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


[Tutor] Done -- Elementtree and pretty printing in Python 2.7

2010-08-20 Thread Knacktus

Hi guys,

just found hidden in the Schema change in Etree-Thread the answer to 
my formatting question:


Quotation:

ElementTree doesn't have a way of formatting (pretty printing) XML 
files, so there can't be that many newline characters in the structure 
(they may be in the occur, though!). There's a pretty printing recipe on 
the effbot site that you can easily adapt to inject the newline 
characters you need.



The recipe works fine.

Cheers,

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


Re: [Tutor] Error Using exec to Run Module Files

2010-08-17 Thread Knacktus

Am 18.08.2010 06:54, schrieb mes...@juno.com:

I'm a rank beginner in Python.  Took advantage of the O'Reilly one-day sale of 
'Learning Python' announced on the tutor, and starting to work my way through 
it.  When I tried out an example from pg57, on Using exec to Run Module Files, 
I get the following result:

exec(open('script1.py').read())

Traceback (most recent call last):
   File stdin, line 1, inmodule
   File string, line 1
 %!PS-Adobe-3.0
 ^
SyntaxError: invalid syntax

It looks like the first line of your file script1.py contains 
%!PS-Adobe-3.0. (Which is no valid syntax, of course)
Have you doublechecked the content of script1.py and does it work by 
invoking it form the command line with python script1.py? My guess is 
the file somehow got screwed up.


HTH

Jan


What is going on/
Gene R.

___
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] Multiple inheritance for mixin attributes

2010-08-16 Thread Knacktus

Hello everyone,

I've got a question about class design. I want to model classes like 
these (examples):


#
class BaseItem(object):

def __init__(self, ident, name, description):
self.ident = ident
self.name = name
self.description = description

class DataSourceItem(object):

def __init__(self, ident, name, description, data_source):
self.ident = ident
self.name = name
self.description = description
self.data_source = data_source

class BaseItemCollection(list):

def __init__(self, ident, name, description):
self.ident = ident
self.name = name
self.description = description

def default_version(self):
return self[-1]

class BaseDataSourceItemCollection(list):

def __init__(self, ident, name, description, data_source):
self.ident = ident
self.name = name
self.description = description
self.data_source = data_source

def default_version(self):
return self[-1]
###

Now, to remove all the duplicated code I could use inheritance. But that 
would lead to multiple inheritance and the question how to initialise 
both superclasses?


I would appreciate some advice about how to model classes like this. 
Personaly, I don't have to use inheritance, but I have no better idea. 
Would you accept at least some duplication to avoid multiple inheritance?


Thanks in advance,

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


[Tutor] Performance list vs. deque for [-1]

2010-08-11 Thread Knacktus

Hi everyone,

I'm wondering what's the fastet datatype in python to lookup the last 
element in an ordered collection. I know about lists, of course, and 
read about deques. As I understand deques have better performance for 
popping and adding elements, but I didn't understand what's the behavior 
for look-up's without any changes to the collection.


I will not pop() out of my ordered collection, and only recently append. 
Also, the collections will be small (about 10-20 elements), but I will 
have huge amount (5-10) of those collections which need to be 
processed for certain tasks in my application.


Thanks in advance and cheers,

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


Re: [Tutor] how to get str() to use my function?

2010-08-04 Thread Knacktus

Am 04.08.2010 17:37, schrieb Alex Hall:

It worked, thanks. Is there a list of these functions somewhere? That
is, the functions that map implicitly to operators or implied uses?
For example, printing will call __str__, as will a cal to str(). What
about math or comparison operators? I have heard of __eq__, __gt__,
and so on, but I tried to implement one and I got an error saying that
it required three arguments. It did, but only because the first was
self. I put the function inside my card class:
  def __eq__(self, card1, card2):
   return(card1.rank==card2.rank)
  #end def __eq__
For some reason it is still looking for three arguments...


The official list of all special methods can be found at the datamodel 
description, chapter 3.4:


http://docs.python.org/reference/datamodel.html#special-method-names

Most Python books also have some explanations about this. Maybe the nice 
online book Dive into Python has a chapter? (I didn't check...)


Regarding your problem: I've flew very fast over the docs. __eq__ seems 
to expect two arguments (self, other). So probably your method of the 
card class should look like:


def __eq__(self, card2):
return(self.rank==card2.rank)

Cheers,

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


Re: [Tutor] Python and Abaqus

2010-07-30 Thread Knacktus

Am 30.07.2010 13:44, schrieb leo.ruggier...@libero.it:

Dear All,

I am trying to have access to the Abaqus kernel by a Python script. My
intention is to avoid to use the Abaqus GUI (or command line) to run a
simulation.
The idea is to lunch the Python script by DOS or Python module.

The problem is that my Python script runs from the Abaqus command line or from
the GUI (menu--file--run script) but it doesn't run from outside.


Without knowing very much about the Abaqus command line my guess is that 
a special environment (env. variables, path, etc.) is set up for the 
Abaqus command line. In that case you need to create that environment in 
your DOS command window where the python script is to run or create that 
environment within your python script (see the os module in the standard 
library).
But prior to that you need to know more about the environment. You could 
query the Abaqus command line (if it's a DOS window by invoking the 
python shell then using os.environ, if it's a Python you can use 
os.environ directly after importing os, of course).
Alternatively you could examine the command file, *.bat file or whatever 
opens the Abaqus command shell. Probably that file has a lot of set up 
stuff in it.


HTH and cheers,

Jan

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


Re: [Tutor] Question

2010-06-19 Thread Knacktus



~So is it better to learn 1 programming language first, then learn
another. Or better to pretty much learn them at the same time? And why?


First, I think python is a bit underrated for creating real 
applications. I'm amazed again and again by it's power on all 
programming scales (e.g. quick and dirty csv-file hacks, medium scripts 
to bigger app with gui (e.g. pyqt is unbelievable powerful) and 
database-connections). So, I hardly see something of an urge for 
learning c++. Python will bring you a looong way.


Then, I think when learning to programm, there're two big levels. Level 
one is to learn the language syntax, basic algorithms, data types, etc..
The second level is how to design larger programs. How to make them as 
easy and clear to understand (and to maintain) as possible. You'll find 
yourself thinking about what to place where in the code, read stuff 
about OO-Programming and Design Patterns etc.. I'm currently at this 
level. So, if you start learning another language, it will broaden your 
level 1 skills, but I think it'll be more valuable to become better at 
level 2. So, once you're familiar with python, I would start creating 
some bigger apps.
One thing to keep in mind is that python has a lot of patterns build in 
due to its dynamic typing and first class callables. A lot of things can 
be expressed much easier with python than with Java or C++. That will 
leave you more brain power for innovation. But for the pure sake of 
learning design patterns, Java might be a candidate.


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


[Tutor] How to model objects aimed to persistence?

2010-06-16 Thread Knacktus

Hi everyone,

within a python application I can easily model object association with 
simple references, e.g.:


#
class FavoritMovies(object):
def __init__(self, movies):
self.movies = movies

class Movie(object):
def __init__(self, name, actor):
self.name = name
self.actor = actor

gladiator = Movie(Gladiator, Russel Crowe)
my_favorit_movies = FavoritMovies([gladiator])

kung_fu_panda = Movie(Kung Fu Panda, Jack Black)
your_favorit_movies = FavoritMovies([gladiator, kung_fu_panda])
##

So far, so good. But what is best practise to prepare this data for 
general persistence? It should be usable for serialisation to xml or 
storing to an RDBMS or ObjectDatabase ...


I guess I have to incorporate some kind of id for every object and use 
this as reference with some kind of look-up dictionary, but I wouldn't 
like it and hope that there're some other sweet pythonic solutions?


Cheers,

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


Re: [Tutor] How to model objects aimed to persistence?

2010-06-16 Thread Knacktus

Am 17.06.2010 02:17, schrieb Alan Gauld:

Steven D'Aprano st...@pearwood.info wrote

Deliberate misspellings in class and variable names will cost you
*far* more in debugging time when you forget to misspell the words
than they will save you in typing. Trust me on this.


Thanks for that hint. I can imagine the nightmares ... It was just a 
spelling mistake. English is not my native language and I sometime tend 
to skip trailing es ;-).


But I think I need to clarify my question a bit. The point I'm unsure 
with is how to best model references in python for persistence when not 
using pickle or any dedicated python. Python doesn't even need names as 
reference to the objects location in memory. I could do something like this:


###
my_favourite_movies = FavouriteMovies([Movie(Gladiator, Russel Crowe)])
###

When I want to rebuild the data from a xml file or database, my objects 
somehow need to know which references to other objects they hold.
I don't now wether I have to use explicit indices in my python code to 
make it xml-ready and if that's the case, how to do it smoothly. Or 
whether there's some other trick.


Cheers,

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


[Tutor] What's the catch with ZopeDB?

2010-06-11 Thread Knacktus

Hey everyone,

I'm planning to create small application which manages product data e.g. 
parts of cars. There are quite some relations, e.g.

- a car consists of certain assemblies,
- an assembly consists of certatin parts,
- a part has serveral documents which describe the part, e.g. a CAD 
document or material data.


So, one could think of storing the data in a relational database. But 
now I start to think ... ;-):


- I would just need some predefined queries which would be performed by 
Python code, of course. Maybe using an ORM.

- Therefore, I don't think I need all the power and flexibility of SQL.
- I will work with Python objects. Why should I translate to an 
relational schema just for persistence?
- Performancewise, caching is probably much more sensitive than pure 
database performance. (That my guess...)


To me, ZopeDB (a object database for Python) looks like an awesomely 
easy solution. I could save some brain power for the innovative part or 
drink more beer watching the soccer world cup. At the same moment, I 
wonder why anyone in the python world would go through the hassle of 
using relational databases unless forced.


So, has anyone experience with ZopeDB? Are there some drawbacks I should 
be aware of before getting a book and dive in? (It sounds too good ;-))


Cheers,

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


Re: [Tutor] Unit testing command-line options from argparse or optparse

2010-05-18 Thread Knacktus

Am 18.05.2010 22:49, schrieb Serdar Tumgoren:

Hello all,

Does anyone have advice for writing unit tests against variables set 
by command-line options?


I have a program I'd like to run in either debug or live mode, 
with various settings associated with each. Below is some pseudo-code 
that shows what I'd like to do:


snipped argparse import and options setup 
mode = p.parse_args() #always set to either --debug or --live

if mode.live:
recipients = ['jsm...@email.com mailto:jsm...@email.com', 
'jane...@email.com mailto:jane...@email.com']

# set logging to a file
elif mode.debug:
recipients = ['ad...@admin.com mailto:ad...@admin.com']
# log to stdout

The live and debug attributes are set by command-line flags passed 
to the argparse module. What I'd like to do is write tests that check 
whether various settings (recipients, logging, etc.) are configured 
properly based on the command-line options.


But if mode is not set until runtime, I clearly can't import it into 
my suite of unit tests, right? Is there some standard testing approach 
to this problem (perhaps mocking?) that you all can recommend?


I'd greatly appreciate it.
Serdar


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
   
I just had a look at the optparse documentation ... huuu, quite heavier 
than I have expected But to your question:


You could reorganise your main module. Put all your code which is on 
module level into a function called main with mode as argurment and 
add the neat if __name__ == __main__ condition at the end of your 
module to parse the command line options and call your main function. 
When you import your module to your test, you have to call the main 
function manually and can pass a mock for the mode as required. Let's 
say your main module is called serdars_main_module


serdars_main_module.py:
--

def main(mode):
# all the program logic
 if mode.live:
recipients = ['jsm...@email.com mailto:jsm...@email.com', 
'jane...@email.com mailto:jane...@email.com']

# set logging to a file
 elif mode.debug:
recipients = ['ad...@admin.com mailto:ad...@admin.com']
# log to stdout
# ...

if __name__ == __main__:
mode = p.parse_args() #always set to either --debug or --liv
main(mode)
#

Then your test module could look like:

serdars_test_module.py:
-
#
import serdars_main_module
import unittest

class ArgParseMock(object):
def __init__(self, live, debug):
self.live = live
self.debug = debug

class TestDebugMode(unittest.TestCase):
def test_live_mode(self):
mode = ArgParseMock(True, False) # create the mock for the 
arguments

serdars_main_module.main(mode) # call the main logic with the mock
# 
def test_debug_mode(self):
mode = ArgParseMock(False, True) # create the mock for the 
arguments

serdars_main_module.main(mode) # call the main logic with the mock
# 
##

Hope that helps,

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


Re: [Tutor] pickle.load() all dict

2010-05-16 Thread Knacktus

Am 16.05.2010 09:10, schrieb Yutao Deng:

Hi all:
I'm trying to learn to use Python  wrote a applet to record every day 
doing.

and i use the pickle
pickle.dump something to file no problem i think.
but pickle.load whith a problem. can not load all dict do my way that 
what i pickle.dump().


My code:

import cPickle as pickle
pickle_file = open(data2,rb)
i = pickle.load(pickle_file)
print i
i = pickle.load(pickle_file)
print i
i = pickle.load(pickle_file)
print i
i = pickle.load(pickle_file)
print i
i = pickle.load(pickle_file)
print i

console show :
{'2010-5-23': ['1242', 'first']}
{'2010-5-24': ['1232', 'third']}
{'2010-5-25': ['211', 'second']}
{'2010-3-22': ['3211', 'fou']}
{'2050-3-2': ['3990', '322']}

This is i want but that's silly. if the dict too much, then i have not 
ideas.


the other way from 
http://mail.python.org/pipermail/tutor/2005-July/039859.html



import cPickle as pickle
pickle_file = open(data2,rb)

number_of_pickles = pickle.load(pickle_file)
for n in range(number_of_pickles):
p = pickle.load(pickle_file)
print p

this way didnt work for me.

console show:
Traceback (most recent call last):
number_of_pickles = pickle.load(pickle_file)
cPickle.UnpicklingError: invalid load key, '
'.
how do i define a range for pickle.load a file . i mean that how can i 
know how many dict in the data2.



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
   
If you want to unpickle a file which contains an unknown number of 
pickled objects, this should work. You'll get a list containing all the 
objects.

#
import cPickle
import pprint

test_data_1 = {2010-12-13: [1324, first]}
test_data_2 = {2010-12-14: [234, first_and_a_half]}
test_data_3 = {2010-12-15: [132224, second]}

for data in (test_data_1, test_data_2, test_data_3):
with open(data2.pickle, ab) as file_stream:
cPickle.dump(data, file_stream, 2)

with open(data2.pickle, rb) as file_stream:
pickled_objects = []
while True:
try:
pickled_objects.append(cPickle.load(file_stream))
except EOFError:
break

print Number of pickled objects is %s. % len(pickled_objects)
pprint.pprint(pickled_objects)
Cheers,

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


Re: [Tutor] pickle.load() all dict

2010-05-16 Thread Knacktus

Am 16.05.2010 14:45, schrieb Yutao Deng:

LOL, try...except is a good idea.
i fix it  lick this:


with open(data2.pickle,rb) as file_stream:
c = 0
while True:
try:
i = cPickle.load(file_stream)
print i
c += 1
except:
print Numer of pickled objects is %s. %c
break
#


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
   
Just a remark on your except statement: You should not use except: 
without specifying a concrete exception class, because all kind of 
exceptions are then handled by the except block (and therefore hidden). 
If for example an IOError occurs while reading the file (for what ever 
reason...), it would be handled by your except block and you would never 
know that there was a problem reading the file. If you use except 
EOFError: the exception block is evaluated only when the EOFError 
occurs. All other exceptions are raised as usual.


Best regards,

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