Docstrings and class Attributes

2011-08-08 Thread Nick
Is it possible to put a doc string on a class attribute? Something
like this

class Test (object):
'''classx'''

fred = 10
'''attribute'''

print Test.__doc__
print Test.fred.__doc__

This code produces this output

classx
int(x[, base]) -> integer

Convert a string or number to an integer, if possible.  A floating
point
argument will be truncated towards zero (this does not include a
string
representation of a floating point number!)  When converting a string,
use
the optional base.  It is an error to supply a base when converting a
non-string.  If base is zero, the proper base is guessed based on the
string content.  If the argument is outside the integer range a
long object will be returned instead.

===

So the class doc string is return, but no doc string for the
attribute.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Meta Data

2016-03-29 Thread Nick
I did find a couple of patterns in Effective Python: 59 Specific Ways to Write 
Better Python (Effective Software Development).

Registering classes and a field example.

Thanks

N.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Bitching about the documentation...

2005-12-05 Thread nick
"BartlebyScrivener" <[EMAIL PROTECTED]> writes:

> Go to Python.org
>
> Click on DEVELOPERS
>
> The lead sentence says:
>
> Contributors and potential contributors should read Documenting Python,
> which describes in details the conventions and markup used in creating
> and maintaining the Python documentation. The CVS trunk version is the
> recommended version for contributors, regardless of which Python branch
> is being modified.
>
> The link takes you straight to a primer on LaTex.
>
> Did I miss something?
>
The "Documenting Python" link takes you to a page that starts like this
- NB. the last sentence of the abstract:

"""
Documenting Python

Fred L. Drake, Jr.

PythonLabs
Email: [EMAIL PROTECTED]

Release 2.5a0
August 9, 2005

Abstract:

The Python language has a substantial body of documentation, much of
it contributed by various authors. The markup used for the Python
documentation is based on LaTeX and requires a significant set of
macros written specifically for documenting Python. This document
describes the macros introduced to support Python documentation and
how they should be used to support a wide range of output formats.

This document describes the document classes and special markup used
in the Python documentation. Authors may use this guide, in
conjunction with the template files provided with the distribution, to
create or maintain whole documents or sections.

If you're interested in contributing to Python's documentation,
there's no need to learn LaTeX if you're not so inclined; plain text
contributions are more than welcome as well.
"""


-- 
nick  (nicholas dot dokos at hp dot com)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding user's home dir

2005-02-02 Thread Nick
Python 2.4 (#1, Jan  1 2005, 21:33:55)
[GCC 3.3.4] on linux2
Slackware 10 Current
Works! Nice.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lots of pdf files

2005-07-21 Thread nick
Paul Rubin  wrote:
> Greg Lindstrom <[EMAIL PROTECTED]> writes:
> > There does not appear to be a simple way to merge many pdf's into one.

> There's probably some way to do it with pstops or some related program
> or set of programs.

Google for "multivalent tools" - a collection of Java applications
for PDF manipulation...


N.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python, VB and COM

2004-12-21 Thread Nick
Thanks Steve.

I eventually found the library. Running makepy over the library
produced the requisite file.

Its working.

Help appreciated.

Nick

-- 
http://mail.python.org/mailman/listinfo/python-list


Meta Data

2016-03-28 Thread Nick
Django has the idea of specifying models using typed Fields. 
The same exists within SQLAlchemy

Are there any tutorials on setting up a similar system.

ie. Declare classes and fields, query the meta data. Fields restricted to 
certain types. 

N.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Meta Data

2016-03-28 Thread Nick
Thanks Joel, 

A quick look on Amazon shows it is probably relevant. 

N.
-- 
https://mail.python.org/mailman/listinfo/python-list


Python on handhelds

2006-09-10 Thread Nick

Hi all,

I have never programmed in Python a day in my life. My group is working
on developing an application on the Dell Axim hand held that has a
tight deadline. I have heard that Python is particularly advantageous
in rapid prototyping and deployment. I would like to lean this way if I
can. Does anyone know if I can run Python on the Dell Axim handheld. It
runs Windows CE. If so, what all is needed to make this possible.
Thanks


Nick../

-- 
http://mail.python.org/mailman/listinfo/python-list


Python Worship

2006-11-30 Thread Nick
http://www.sciencedaily.com/releases/2006/11/061130081347.htm

World's Oldest Ritual Discovered -- Worshipped The Python 70,000 Years
Ago

Nick

-- 
http://mail.python.org/mailman/listinfo/python-list


Click this link, scroll to the bottom, and get your own free mall!!

2006-02-17 Thread nick
http://www.telebay.com/esolutions/mall.html

-- 
http://mail.python.org/mailman/listinfo/python-list


Click this link, scroll to the bottom, and get your own free mall!!

2006-02-17 Thread nick
http://www.telebay.com/esolutions/mall.html

-- 
http://mail.python.org/mailman/listinfo/python-list


Click this link, scroll to the bottom, and get your own free mall!!

2006-02-17 Thread nick
http://www.telebay.com/esolutions/mall.html

-- 
http://mail.python.org/mailman/listinfo/python-list


strip() 2.4.4

2007-06-21 Thread Nick
strip() isn't working as i expect, am i doing something wrong -

Sample data in file in.txt:

'AF':'AFG':'004':'AFGHANISTAN':'Afghanistan'
'AL':'ALB':'008':'ALBANIA':'Albania'
'DZ':'DZA':'012':'ALGERIA':'Algeria'
'AS':'ASM':'016':'AMERICAN SAMOA':'American Samoa'


Code:

f1 = open('in.txt', 'r')

for line in f1:
print line.rsplit(':')[4].strip("'"),

Output:

Afghanistan'
Albania'
Algeria'
American Samoa'

Why is there a apostrophe still at the end?

Thanks in advance.
Nick

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strip() 2.4.4

2007-06-21 Thread Nick
On 21 Jun, 14:53, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> On 2007-06-21, Nick <[EMAIL PROTECTED]> wrote:
>
>
>
> > strip() isn't working as i expect, am i doing something wrong -
>
> > Sample data in file in.txt:
>
> > 'AF':'AFG':'004':'AFGHANISTAN':'Afghanistan'
> > 'AL':'ALB':'008':'ALBANIA':'Albania'
> > 'DZ':'DZA':'012':'ALGERIA':'Algeria'
> > 'AS':'ASM':'016':'AMERICAN SAMOA':'American Samoa'
>
> > Code:
>
> > f1 = open('in.txt', 'r')
>
> > for line in f1:
> > print line.rsplit(':')[4].strip("'"),
>
> > Output:
>
> > Afghanistan'
> > Albania'
> > Algeria'
> > American Samoa'
>
> > Why is there a apostrophe still at the end?
>
> Most likely it's the newline at the end of each record that's
> getting in your way.
>
> You can double-strip it.
>
> for line in f1:
> print line.strip().rsplit(':')[4].strip("'")
>
> --
> Neil Cerutti
> The world is more like it is now than it ever has been before. --Dwight
> Eisenhower

Thank you all very much for your input, the above solved the problem
as most of you had already pointed out.

-- 
http://mail.python.org/mailman/listinfo/python-list


Curses and resizing windows

2007-02-28 Thread Nick !
> Chris Share  wrote:
> > I've been writing an application using curses, and have been trying to
> > handle resizing the terminal, if running in xterm or similar. Increasing
> > the window size is working perfectly, however shrinking it is not
> > working at all. No matter how much I shrink the window, the size
> > returned by getmaxyx() does not change. However as soon as I increase it
> > again, it works fine.
>
> > I've tracked the problem down to the fact I have created a window
> > derived from stdscr. A small script showing the effect is at the end of
> > this post.
>
> odd (thanks for the example - I don't know if this is a problem in
> ncurses or in the python interface to it, but will check/see).
>
> > Can anyone suggest how to solve this problem, that doesn't involve not
> > making a derwin of stdscr?
>
> > I've been googling for hours, but found nothing to help.
>
> > Python version is 2.3.4 on debian testing.
>
> probably should report it as a bug (so it's not overlooked).
>
> --
> Thomas E. Dickey
> http://invisible-island.net
> ftp://invisible-island.net

http://web.cs.mun.ca/~rod/ncurses/ncurses.html#xterm says "The ncurses
library does not catch [the SIGWINCH aka resizing] signal, because it
cannot in general know how you want the screen re-painted". First, is
this really true? When I make my xterms smaller they clip what is
displayed--is that a function of curses or the xterm?
Second, if true, it explains /what/ is going on--stdscr, only--, but
isn't really satisfactory; it doesn't solve the original poster's bug.

#!/usr/bin/env python
"""
curses_resize.py -> run the program without hooking SIGWINCH
curses_resize.py 1 -> run the program with hooking SIGWINCH
"""


import sys, curses, signal, time

def sigwinch_handler(n, frame):
curses.endwin()
curses.initscr()

def main(stdscr):
"""just repeatedly redraw a long string to reveal the window 
boundaries"""
while 1:
stdscr.insstr(0,0,"abcd"*40)
time.sleep(1)

if __name__=='__main__':
if len(sys.argv)==2 and sys.argv[1]=="1":
signal.signal(signal.SIGWINCH, sigwinch_handler)
curses.wrapper(main)

If you run this without sigwinch then the line never gets resized, but
if you do then it works fine. What we can glean from this is that
stdscr only reads off it's size upon initialization. This behaviour
may seem a bit strange, but 1) it's legacy and 2) avoids breaking the
semantics of windows (which don't change size on their own).

The "curses.initscr()" part is kind of unhappy though. It modifies the
stdscr variable without us explicitly assigning anything (but I can't
think of any other way to do it, beyond making stdscr a global, and
that feels worse) and will break if initscr() ever returns a new
Window structure instead of just updating and returning the old one.
Does anyone have any tips for how to structure this so that the screen
can actually be assigned to?

In conclusion, it's not a bug, it's a feature. Joy! The workaround is
to write a sigwinch_handler that at least does `endwin(); initscr()`.

Sorry for reviving an old thread, but it doesn't seem the issue was
ever resolved (the thread doesn't go anywhere and there's no warning
about this in the docs that I noticed).

(please CC: me if anyone cares, I'm not on the list)

-Nick Guenther
-- 
http://mail.python.org/mailman/listinfo/python-list


Escaping the semicolon?

2007-12-04 Thread Nick
Hi all,

Is this expected behavior?

>>> s = '123;abc'
>>> s.replace(';', '\;')
'123\\;abc'

I just wanted a single backslash. I can see why this probably happens
but i wondered if it is definitely intentional.

Thanks
Nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Escaping the semicolon?

2007-12-04 Thread Nick
Thanks guys, you answered that interactive prompt question really
clearly however, whats going on here. This works now -

>>> working_string = '123;abc'
>>> search_string = ';'
>>> print working_string.replace(search_string, '\\' + search_string)
123\;abc

But this doesn't -

---
import sys
import string

input = string.join(sys.argv[1:], '')
escape_char_list = [ '(', '[]', ';', '^', '\\', '/', '|', '*', '$',
'&', '[', ']', ')', '?' ]

for ch in escape_char_list:
input = input.replace(ch, '\\' + ch)

print input
---

Try "123 *?/ abc d;o /$'" as the argument... and you get -

123 \*\?\/ abc d\\;o \/\$

Still two back slashes, did i miss something very obvious? Sorry,
sometimes these things are exasperating and just need more eyes or a
head screwed on (if thats the case!).

Nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Escaping the semicolon?

2007-12-04 Thread Nick

>
> If you move '\\' to the front of your list of replacement characters,
> things will probably work as you expect.
>
> --
> Jerry

I knew it would be something like that! Thanks for your help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with reload(sys) (doing reload on the sys module)

2006-05-04 Thread nick
Looks like a bug (probably in IDLE): when I start IDLE from the command
line, it pops up its interaction window and here is what it says about
stdout:

IDLE 1.1.2  
>>> import sys
>>> sys.stdout


Then I try the reload and I get no output in the interaction
window:

>>> reload(sys)
>>> sys.stdout
>>> 

After the reload, stdout has been changed to the terminal from which
IDLE got started, so I see the messages there:


', mode 'w' at 0xb7b67068>

As you can see, stdout has been redefined (back to the way it would be if
you started Python from the command line, with no IDLE involved).
-- 
nick  (nicholas dot dokos at hp dot com)
-- 
http://mail.python.org/mailman/listinfo/python-list


free download - breve 2.7.2 : a 3D Simulation Environment for Multi-Agent Simulations and Artificial Life

2009-01-22 Thread Nick
www.filecub.com

What is breve?
breve is a free, open-source software package which makes it easy to
build 3D simulations of multi-agent systems and artificial life. Using
Python, or using a simple scripting language called steve, you can
define the behaviors of agents in a 3D world and observe how they
interact. breve includes physical simulation and collision detection
so you can simulate realistic creatures, and an OpenGL display engine
so you can visualize your simulated worlds.

www.filecub.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Portable way to refer to the null device?

2009-02-07 Thread nick
On Fri, Feb 06, 2009 at 07:32:20PM -0800, Roy Smith wrote:
> I need to run a command using subprocess.Popen() and have stdin
> connected to the null device.  On unix, I would do:
> 
> self.process = subprocess.Popen(argv,
> env=new_env,
> stdout=open(outfile, 'w'),
> stderr=open(errfile, 'w'),
> stdin=open('/dev/null')
> )
> 
> but that's not portable to windows.  Does Python have a portable way
> to get a file object connected to the null device, regardless of what
> operating system you're running on?

I normally just implement my own object:

class DevNull:
def write(self, str):
pass
--
http://mail.python.org/mailman/listinfo/python-list


Re: simple web app, where to start

2009-02-07 Thread nick
On Fri, Feb 06, 2009 at 09:16:02PM -0700, Vincent Davis wrote:
> I have a simple script that takes a few input values and returns a csv file
> and a few stats. If I wanted to host this on the web how would I. I have no
> idea where to begin. If someone could point me in the right direction like
> maybe a tutorial, tools I will need, functions. I would appreciate it.I
> know a little html but am not sure how to integrate python or know what
> servers will handle it .
> 
> Thanks
> Vincent Davis

I'd suggest CherryPy[1]. It's fairly welcoming to newbies, because the
web server and the framework and bundled together.

1: http://www.cherrypy.org/

HTH,
Nick

--
http://mail.python.org/mailman/listinfo/python-list


Re: Best 3d graphics kit for CAD program???

2009-02-08 Thread nick
Gary

Your email client is set to HTML mode and looks terrible for those of us
who prefer plain view. It also appears your client is not properly
sending your message in  text/plain encoding.


--
http://mail.python.org/mailman/listinfo/python-list


An inheritance question: getting the name of the "one up" class

2009-03-30 Thread Nick
I've got a collection of classes describing animals, part of which looks 
like:


class Animal(object):
   def __init__(self):
   self.pet = False
   self.edible = False
   self.legs = 0
   self.sound = None
   self.name = self.__class__.__name__.lower()

class Mammal(Animal):
   def __init__(self):
   Animal.__init__(self)
   self.legs = 4

class Primate(Mammal):
   def __init__(self):
   Mammal.__init__(self)
   self.legs = 2

class Human(Mammal):
   def __init__(self):
   Primate.__init__(self)
   self.sound = "Hey, I can talk!"

I want to add a "pedigree" function to Animal so that I can have:


h = Human()
h.pedigree()

human < primate < mammal < animal




I've been thinking about something like:
def pedigree(self):
   n = self.name
   while n != 'object' # base class of Animal
   print n,
   n = Well, this is where I'm stuck. super(???,???).???
   print

Oh, and while the gurus are at it, what would be the advantage (if any) of 
changing, say

  Primate.__init__(self)
to
   super(Human, self).__init__()

Thanks, all,

Nick. 


--
http://mail.python.org/mailman/listinfo/python-list


Re: An inheritance question: getting the name of the "one up" class

2009-03-31 Thread Nick
Thanks for the replies. This has given me some incentive to start looking at 
Python 3. Oh, and thanks for the articles on super().


Nick 


--
http://mail.python.org/mailman/listinfo/python-list


SQL and CSV

2009-05-05 Thread Nick
I have a requirement to read a CSV file. Normally, no problem, just
import CSV and slurp the file up.

However, in this case I want to filter out lines that have fields set
to particular values.

It would be neat to be able to do something like this.

select * from test.csv where status <> "Canceled"

Using adodb I can do this, so long as I don't have the where clause. :-
(

Is there a reasonable lightweight way of doing this in Python?

I could write some python code that is used to filter rows, and inport
that from config, but it's not quite as elegant as an SQL route.

Thanks

Nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: SQL and CSV

2009-05-05 Thread Nick
On May 5, 5:19 pm, Tim Golden  wrote:
> Nick wrote:
> > I have a requirement to read a CSV file. Normally, no problem, just
> > import CSV and slurp the file up.
>
> > However, in this case I want to filter out lines that have fields set
> > to particular values.
>
> > It would be neat to be able to do something like this.
>
> > select * from test.csv where status <> "Canceled"
>
> > Using adodb I can do this, so long as I don't have the where clause. :-
> > (
>
> > Is there a reasonable lightweight way of doing this in Python?
>
> > I could write some python code that is used to filter rows, and inport
> > that from config, but it's not quite as elegant as an SQL route.
>
> Not entirely clear what you are and aren't prepared to try here, but...
> the most obvious Python-based way to do this is treating the csv reader
> as an iterator and filtering there. Your last line suggests that's not
> what you want but just in case I've misunderstood:
>
> 
> id,code,status
> 1,"ONE","Active"
> 2,"TWO","Cancelled"
> 3,"THREE","Active"
> 
>
> 
> import csv
>
> for row in csv.DictReader (open ("c:/temp/test.csv", "rb")):
>   if row['status'] != 'Cancelled':
>     print row
>
> 
>
> Doesn't seem too onerous, and could obviously be wrapped in
> some useful class/module.
>
> But if you really want to go the SQL route, I believe there are
> ODBC adapters for CSV which, combined with PyODBC or CeODBC,
> would probably take you where you want to go.
>
> TJG

Part of the problem is that the 'selection' needs to be in a config
file. I can put the if row['status'] != 'Cancelled': return True into
a config, read it and eval it, but its not quite as clean as an sql
route.

Nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: SQL and CSV

2009-05-07 Thread Nick
On May 5, 8:27 pm, Tim Golden  wrote:
> Nick wrote:
> > Part of the problem is that the 'selection' needs to be in a config
> > file. I can put the if row['status'] != 'Cancelled': return True into
> > a config, read it and eval it, but its not quite as clean as ansql
> > route.
>
> Still not clear what the restriction is. If you were writingSQLyou'd have to 
> read *something* from your config file,
> unless you're suggesting that the "config file" is in fact
> aSQLfile. Which is one way of doing it, but then you might
> just as well have your config file as a Python file and
> import it.
>
> Have I missed the point somewhere here? Can you give an
> example -- even a fictional one -- of what you couldn't
> do using, say, the example I gave earlier?
>
> TJG

Solution found. In the end I used SQLite to read from a csv file, and
now I can query the CSV file. The file is read using the csv module

First create a function

def fraction(p, denom):
num, frac = p.split ('-')
return float (num) + float (frac) / denom

for use within queries.

Now build the class.

self.filename  = filename
self.dialect   = dialect
self.query = query
reader = csv.reader (open (filename, 'r'))
self.connection = sqlite.connect(":memory:")
self.connection.create_function("fraction", 2, fraction) #
Adds in function
self.cursor = self.connection.cursor()
first = True
for row in reader:
if first:
headers = []
for r in row:
n = r.strip().replace (' ', '_').replace ('-','_')
headers.append (n)
command = 'create table csv (%s)' % ','.join (headers)
self.cursor.execute (command)
first = False
else:
command = 'insert into csv values ("%s")' % '","'.join
(row)
self.cursor.execute (command)

and then I can use this

self.cursor.execute (self.query)
rows = self.cursor.fetchall()
headers = []
for r in self.cursor.description:
headers.append (r[0])
results = Results.Results (headers, self.name, {})
i = 0
for row in rows:
results.add (row, i)
i = i + 1
return results

to query the results.

Results.Results is one of my classes that's reused in lots of places.

The query then looks somethign like this

select
Client_Reference_Number as TrdNbr,
Asset_Number as ISIN,
Quantity as Qty,
status
from
csv
where status in ("CANCELLED")

union

select
Client_Reference_Number as TrdNbr,
Asset_Number as ISIN,
Quantity as Qty,
status
from
csv
where status not in ("CANCELLED")


All incredibly neat and the first time I've used SQLite.

nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: SQL and CSV

2009-05-08 Thread Nick
On May 8, 1:49 pm, "andrew cooke"  wrote:
> Lawrence D'Oliveiro wrote:
> > In message , Peter Otten wrote:
>
> >> While it may not matter here using placeholders instead of manually
> >> escaping user-provided values is a good habit to get into.
>
> > Until you hit things it can't deal with.
>
> The post you are replying to was talking about using the SQL library's "?"
> syntax that automatically escapes values.  The usual reason this is
> recommended (if I have understood correctly) is that the library code is
> much more likely to foil injection attacks.  I have seen this mentioned
> often and assume it is good advice.
>
> Can you expand on your comment?  I assume you are thinking of how the
> library might handle some strange class.  But aren't the number of types
> limited by SQL?  In which case a "thing that can't be handled" could
> presumably be managed by adding an appropriate __str__ or __float__ or
> whatever?  And you would still use the library to give safety with other
> values.
>
> Maybe you could give an example of the kind of problem you're thinking of?
>
> Thanks,
> Andrew

Injection attacks aren't an issue, its a local app.

It's part of a reconciliation system, where sometimes data is in csv
files. If you want the whole csv file, you can use csv module without
a problem.

In some cases, I need to manipulate the data.

The choices are hard code the manipulation, or load the data from a
config file.

So what I've got is the query in the config and I can process it.

Nick
--
http://mail.python.org/mailman/listinfo/python-list


Implementation suggestions for creating a Hierarchical circuit database

2009-12-10 Thread nick
Hi,

I am writing a personal software that will read circuit design/
netlist. I will be using the MCNC benchmarks that contain different
types of designs in SPICE netlist format.

I need some pointers/papers/suggestions on creating a "hierarchical"
netlist database. The netlist database can, at times, be fully
flattened, partially flattened or fully hierarchical. I should be able
to answer queries like: are there any capacitors connected to node:
x1.x2.n1?

My program is currently only for analyzing designs for connectivity,
types of elements (resistors/capacitors) and figuring out some simple
electrical properties.

I am just starting, so please bear with me if I haven't thought about
corner cases.

Regards
Nick
-- 
http://mail.python.org/mailman/listinfo/python-list


catching my own exception

2010-06-18 Thread nick
I have a problem with catching my own exception. Here is the code:
http://fly.srk.fer.hr/~nick/travapi/blame.php?repname=Travian+API&path=%2Fvillage.py&;

Line 252 calls a method, which on line 207 raises a
SomethingBeingBuiltError exception. On line 253 I catch that
exception, but when I run that code, I get:

Traceback (most recent call last):
  File "village.py", line 252, in 
v.upgrade_cheapest()
  File "/media/data/home/code/travapi/village.py", line 207, in upgrade_cheapest
raise SomethingBeingBuiltError()
village.SomethingBeingBuiltError: 'Unable to upgrade, check if something is 
being built.'

If I change line 253 to only "except:", everything works as
expected. How come? What am I missing? Any help would be appreciated.

P.S.: I'm aware I'm exposing my login/pass in the code. Don't care
really, those are throwaway accounts.

-- 
"Now the storm has passed over me
I'm left to drift on a dead calm sea
And watch her forever through the cracks in the beams
Nailed across the doorways of the bedrooms of my dreams"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: catching my own exception

2010-06-18 Thread nick
Dana Fri, 18 Jun 2010 10:36:21 -0700 (PDT), 
Jon Clements  kaze:
> http://www.travian.com/spielregeln.php -- rule 3???

Yeah, I know. If it's any consolation to you, I'm not doing it for the
fun of wining the game (hence not bothering to hide de code) but for
the fun of coding the API. :-)

Anyway, catching your own exceptions?

-- 
"Now the storm has passed over me
I'm left to drift on a dead calm sea
And watch her forever through the cracks in the beams
Nailed across the doorways of the bedrooms of my dreams"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fascinating interview by Richard Stallman on Russia TV

2010-07-18 Thread Nick
Emmy Noether  writes:

> On Jul 7, 1:57 pm, bolega  wrote:
>> "Democracy is sick in the US, government monitors your 
>> Internet"http://www.youtube.com/watch?v=2BfCJq_zIdk&feature=fvsr
>>
>> Enjoy .
>
> In this video, Stall man makes 4 promises to public but stalls on 2nd
> of them.

I have no idea of the rights or wrongs of this case.  But I've found
through experience that when someone uses a "witty" misspelling of
someone's name, they are almost always the one in the wrong.  5 lines in
and here we are - so if your case has merit, think about whether you
want to do this.

BTW - Did you see what I did there?  I snipped all the rest of the post
as it wasn't relevant.  I know several people have asked you to do it,
but you seem to be having difficulty with the concept, so I thought I'd
give you a practical example.
-- 
Online waterways route planner| http://canalplan.eu
Plan trips, see photos, check facilities  | http://canalplan.org.uk
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fascinating interview by Richard Stallman on Russia TV

2010-07-18 Thread Nick
Emmy Noether  writes:

> On Jul 18, 1:09 am, Nick <3-nos...@temporary-address.org.uk> wrote:
>> Emmy Noether  writes:
>> > On Jul 7, 1:57 pm, bolega  wrote:
>> >> "Democracy is sick in the US, government monitors your 
>> >> Internet"http://www.youtube.com/watch?v=2BfCJq_zIdk&feature=fvsr
>>
>> >> Enjoy .
>>
>> > In this video, Stall man makes 4 promises to public but stalls on 2nd
>> > of them.
>>
>> I have no idea of the rights or wrongs of this case.  But I've found
>> through experience that when someone uses a "witty" misspelling of
>> someone's name, they are almost always the one in the wrong.  
>
> Huh, you forgot that the whole of GNU = Gnu Not Unix
>
> You have double standard and you know very well whats right and whats
> wrong.

Ah.  I see.  You know my thoughts better than I do.  

That means you're another nutter.

What I wrote was entirely true - I haven't read these great long posts
in any detail.  I've just deleted your email unread and plonked you.
-- 
Online waterways route planner| http://canalplan.eu
Plan trips, see photos, check facilities  | http://canalplan.org.uk
-- 
http://mail.python.org/mailman/listinfo/python-list


gett error message: "TypeError: 'int' object is not callable"

2009-07-09 Thread Nick
I've seen a lot of posts on this problem, but none seems to help.
Here is the code:
/code

file = open(prefix1)
text = file.readlines()
len = len(text)
fields = text[1].split()
num_rows = int(fields[1])
num_cols = int(fields[2])

U1_matrix = []

print fields
print repr(fields)
print len(fields)

for line in text[2: num_rows+2]:
fields = line.split()
#print "fields", fields, line
for i in range(len(fields)):
fields[i] = float(fields[i])
U1_matrix.append(fields)

/*code

prefix is a space/line delimited ascii file that represents a 2D
matrix.  i'm trying to read in 2 matrices from different files, strip
away the header stuff and then take the dot product of the 2
matrices.  any help is much appreciated.

thanks,
nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: gett error message: "TypeError: 'int' object is not callable"

2009-07-09 Thread Nick
On Jul 9, 10:02 am, "Richard Brodie"  wrote:
> "Nick"  wrote in message
>
> news:e54c4461-c0b7-42fb-8542-cefd7bf5f...@h18g2000yqj.googlegroups.com...
>
> > file = open(prefix1)
> > text = file.readlines()
> > len = len(text)
>
> You have redefined two built-in functions "file" and "len" in the first three 
> lines.
> This is usually considered poor practice. Stick to meaningless variable names,
> it's safer (only joking).
>
> TypeError: 'int' object is not callable". This means that something you 
> thought
> was a function is in fact an integer. It's helpful to post/look at the line 
> number of
> the error; "how is this line failing", is much easier to answer than
> "how is my program failing".
>
> print len(fields)
>
> Here len is an integer, because you redefined it in line 3. I'm guessing this 
> is the
> problem.

thanks for spotting the obvious errors, its my 2nd day programming
python in about 3 years.
fridrick, code should be workable with the exception of the
errors...thats the whole program

Thanks again for all the help problem fixed
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: gett error message: "TypeError: 'int' object is not callable"

2009-07-09 Thread Nick
no problem, i understand, i haven't coded anything in literally 2
years, but it was a simple and pretty obvious mistake.  thanks for all
your help,

nick


On Jul 9, 11:30 am, Friðrik Már Jónsson  wrote:
> Previously, I wrote:
> >> P.S. While this is a fairly obvious problem it's usually a good
> >> idea to post working code and a traceback when requesting help.
> Nick wrote:
> > thanks for spotting the obvious errors, its my 2nd day programming
> > python in about 3 years.
>
> I'm sorry, my saying it was obvious may have come off a little
> arrogant. My clumsily delivered point was that because it was a small
> snippet of code it didn't take much time to run through for someone
> who codes daily with Python. What you did there was a perfectly
> ordinary thing to do until experience teaches you how Python does
> things. :)
>
> > fridrick, code should be workable with the exception of the
> > errors...thats the whole program
>
> You're right, I failed to say it explicitely but I was referring to
> the input file.  In some cases, albeit not this one, problems can
> exist in parsing gotchas.
>
> Regards,
> Friðrik Már

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: gett error message: "TypeError: 'int' object is not callable"

2009-07-10 Thread Nick
On Jul 9, 8:22 pm, Paul Rubin <http://phr...@nospam.invalid> wrote:
> Nick  writes:
> > text = file.readlines()
> > len = len(text)
> > fields = text[1].split()
>
> Is that intended to split the first line of the file?  Remember
> that arrays in python begin at index 0.

no the '1st line' is garbled meta data, but thanks man
-- 
http://mail.python.org/mailman/listinfo/python-list


This is a mess...

2009-07-16 Thread Nick
I've been coding python for about a week now, and i'm trying to make
an object oriented version of a program i just wrote.  in this post is
the original program.  the next post will include the new programs and
the traceback.  i'm sure there are many underlying problems, but have
been stuck on this for 2 days now...

email me for input files since they are big and i don't see a way to
upload a file here(~5 mB)
this program works, and inputing the same file twice you should get a
"Q" values of ~1 (.99...)

##CODE#

#9July09
#Compute the covariance overlap of two results
#Read in _U.asc files for both ensembles to find e-vectors
#Read in _ .asc files for both ensembles to find sqrt e-values
#strip out matrix info
#compute corvariance


import sys
import math
from math import sqrt


if len(sys.argv) != 3:
print " "
print "The corrent usage is 'python covariance.py file1 file2'"
print "where the _U.asc and _s.asc will be appended when needed"
print " "
exit(1)


Input the first prefix1_U.asc file:
this is the first eigen vector matrix
prefix1 = sys.argv[1] + "_U.asc"
fileholder = open(prefix1)
text = fileholder.readlines()
fields = text[1].split()
num_rows = int(fields[1])
num_cols = int(fields[2])

U1_matrix = []
for line in text[2: num_rows+2]:
fields = line.split()
for i in range(len(fields)):
fields[i] = float(fields[i])
U1_matrix.append(fields)

Input the second prefix2_U.asc file:
this is the 2nd eigen vector matrix
prefix2 = sys.argv[2] + "_U.asc"
fileholder = open(prefix2)
text = fileholder.readlines()
fields = text[1].split()
num_rows = int(fields[1])
num_cols = int(fields[2])
#print "look here nick:", fields

U2_matrix = []
for line in text[2: num_rows+2]:
fields = line.split()
for i in range(len(fields)):
fields[i] = float(fields[i])
U2_matrix.append(fields)

Then Read in the first eigen values
1st 2 lines are header and need to be stripped away
prefix3 = sys.argv[1] + "_s.asc"
fileholder = open(prefix3)
text = fileholder.readlines()
fields = text[1].split()
num_vals1 = int(fields[1]) #add check to see if correct # of values
added
print "square if", len(U1_matrix), "=", len(U2_matrix), "=", len
(U1_matrix[1]), "=", len(U2_matrix[1])
#the list of sqrt e vals
sqrt_s1 = [float(line) for line in text[2: num_vals1+2]]
s1 = [float(line) * float(line) for line in text[2: num_vals1+2]]

Finally, read in the 2nd set of eigen vals
prefix4 = sys.argv[2] + "_s.asc"
fileholder = open(prefix4)
text = fileholder.readlines()
fields = text[1].split()
num_vals2 = int(fields[1]) #add check to see if correct # of values
added
#the list of sqrt e vals
sqrt_s2 = [float(line) for line in text[2: num_vals1+2]]
s2 = [float(line) * float(line) for line in text[2: num_vals1+2]]


#=
double summation (the 2nd term)
doublesum = 0.0
for i in range(len(U1_matrix[1])):
   #print "i = ", i
v1 = U1_matrix[i]
sum = 0
for j in range(len(U2_matrix)):
 v2 = U2_matrix[j]
 dot = 0
 for k in range(len(U1_matrix)):
 dot += v1[k] * v2[k]
 root = sqrt_s1[i] * sqrt_s2[j]
 sum += root * dot * dot
doublesum += sum


print "double sum: ", doublesum

single summation (the 1st term and denominator)
singsum = 0.0
for k in range(len(s1)):
singsum += s1[k] + s2[k]
print "sing sum:", singsum


Put it all together
Q = 1 - sqrt(abs((singsum - (2.0*doublesum)) / singsum))
print "your Q:"
print Q

# end of code covariance.py

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: This is a mess...

2009-07-16 Thread Nick
this is the new oop version, its pretty messy currently, and i do
understand it is a simple routine, but i'm using it as an exercise to
learn oop python...

first the (current) traceback:
 [:~/python]$  python oop_covariance.py b2ar_all_test b2ar_all_test


Traceback (most recent call last):
  File "oop_covariance.py", line 24, in 
cov = set1.covariance(set2, Eigen_vect.dot)
  File "/home/nleioatts/python/Eigen.py", line 66, in covariance
print self.vectors[i][i]
AttributeError: Eigen_vect instance has no attribute '__getitem__'

and a quick explaination:  the file structures aare a 2d list of lists
of numbers corresponding to eginvectors and a list of numbers
corresponding to eigenvalues

#33##Here is the main body
#!/usr/bin/env python
import sys
import Eigen
from Eigen import *

if len(sys.argv) != 3:
print " "
print "The corrent usage is 'python covariance.py file1 file2'"
print "where the _U.asc and _s.asc will be appended when needed"
print " "
exit(1)
file1 =  sys.argv[1]
file2 =  sys.argv[2]
set1 = Eigen_set(file1+"_U.asc", file1+"_s.asc")
set2 = Eigen_set(file2+"_U.asc", file2+"_s.asc")
cov = set1.covariance(set2, Eigen_vect.dot)
print cov


###and here are the classes:

#!/usr/bin/env python
import sys
import math
from math import sqrt

class Eigen_vect:
def __init__(self, e_val, e_vect):
self.e_val  = e_val
self.e_vect = e_vect
def length(self):
return len(self.e_vect)

def dot(self, other):
d = 0.0
if other.length() != self.length():
    raise ValueError, "Eigen Vectors not same Length"
for k in range(self.length()):
   # print "HI NICK", self.e_vect[k], other.e_vect[k]
d += float(self.e_vect[k]) * float(other.e_vect[k])
return d


class Eigen_set:
def __init__(self,  vec_filename, val_filename):
self.vec_filename = vec_filename
self.val_filename = val_filename
# open two files
# loop through them, skipping lines that begin with #
# for each row, extract eigen vector and eigen values
fileholder = open(self.vec_filename)
text = fileholder.readlines()
fields = text[2].split()
#print "len of fields", len(fields)
self.vectors = []
for line in text[2: len(fields)]:
fields = line.split()
#print "len of fields", len(fields)
for i in range(len(fields)):
fields[i] = float(fields[i])
e_vect = fields
fileholder = open(self.val_filename)
text = fileholder.readlines()
e_val = [float(line) for line in text[2: self.length()]]
self.vectors.append(Eigen_vect(e_val, e_vect))
#print "this is self.vectors"
#print self.vectors(e_val)

def length(self):
return len(self.vectors)

def covariance(self, other, dot):
newdot = 0.0
# do a length check to make sure we're consistent
if other.length() != self.length():
raise ValueError, "Eigen Vectors not same Length"
#double loop over all my vectors and all of other's vectors
doublesum = 0.0
for i in range(self.length()):
sum = 0.0
v1 = self.vectors[i]
for j in range(self.length()):
newdot += v1.dot(self.vectors[j])
   # root = self.e_val[i] * other.e_val[j]
print self.vectors[i]
print self.vectors[j]
print self.vectors[i][i]
#<<This is line 66, I'm
trying to figure out how to call "e_val" from the Eigen_set class

root = self.vectors[i][i] * other.vectors[i][j]
sum  += newdot * newdot * root
doublesum += sum
#
singsum = 0.0
for k in range(self.length()):
singsum += self.e_val[k] * self.e_val[k] + other.e_val[k]
* other.e_val[k]
Q = 1 - sqrt(abs((singsum - (2.0*doublesum)) / singsum))
print "your Q:"
print Q



and any additional help is great.  thanks in advance, like the title
says this is really a mess
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-09-28 Thread Nick
t...@sevak.isi.edu (Thomas A. Russ) writes:

> Malcolm McLean  writes:
>
>> I'd like to design a language like this. If you add a quantity in
>> inches to a quantity in centimetres you get a quantity in (say)
>> metres. If you multiply them together you get an area, if you divide
>> them you get a dimeionless scalar. If you divide a quantity in metres
>> by a quantity in seconds you get a velocity, if you try to subtract
>> them you get an error.
>
> Done in 1992.
>
> See 
>  
> 
>  citation at 
>
> and my extension to it as part of the Loom system:
>
> 

I didn't go as far as that, but:

$ cat test.can
database input 'canal.sqlite'

for i=link 'Braunston Turn' to '.*'
print 'It is ';i.distance into 'distance:%M';' miles (which is 
'+i.distance into 'distance:%K'+' km) to ';i.place2 into 'name:place'
end for i
$ canal test.can
It is 0.10 miles (which is 0.16 km) to London Road Bridge No 90
It is 0.08 miles (which is 0.13 km) to Bridge No 95
It is 0.19 miles (which is 0.30 km) to Braunston A45 Road Bridge No 91
-- 
Online waterways route planner| http://canalplan.eu
Plan trips, see photos, check facilities  | http://canalplan.org.uk
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Strong typing vs. strong testing"

2010-09-29 Thread Nick
Ian Collins  writes:

> On 09/30/10 05:57 PM, RG wrote:
>>
>> I'm not saying one should not use compile-time tools, only that one
>> should not rely on them.  "Compiling without errors" is not -- and
>> cannot ever be -- be a synonym for "bug-free."
>
> We is why wee all have run time tools called unit tests, don't we?

But you have to know a lot about the language to know that there's a
problem.  You cannot sensibly test your max function on every
combination of (even int) input which it's designed for (and, of course,
it works for those).
-- 
Online waterways route planner| http://canalplan.eu
Plan trips, see photos, check facilities  | http://canalplan.org.uk
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Creating a Super Simple WWW Link, Copy, & Paste into Spreadsheet Program

2013-06-13 Thread Nick Cash
>> there is a python module that reads and writes to excel files.  look 
>> for that

>More than one, actually, and which to use depends on whether "Excel files" 
>means the .xls or .xlsx 
>format.  On Windows, the most flexible solution is going to be to just use COM 
>to control the Excel >application in reading and writing the files.  Outside 
>of Windows, the best bet is usually to work >with csv files instead, as Dave 
>suggested.

I've had success with the xlrd and xlwt suite of modules 
(http://www.python-excel.org/), using both .xls and .xlsx, on Linux. 

-Nick Cash

-- 
http://mail.python.org/mailman/listinfo/python-list


RE: vBulletin scraper -- feasible?

2012-06-25 Thread Nick Cash
You may want to look into http://www.crummy.com/software/BeautifulSoup/
It's made for parsing (potentially bad) HTML, and is quite easy to use. I'd say 
it's quite feasible.

Thanks,
Nick Cash
NPC International

-Original Message-
From: python-list-bounces+nick.cash=npcinternational@python.org 
[mailto:python-list-bounces+nick.cash=npcinternational@python.org] On 
Behalf Of Andrew D'Angelo
Sent: Monday, June 25, 2012 14:10
To: python-list@python.org
Subject: vBulletin scraper -- feasible?

Taking a look through vBulletin's HTML, I was wondering whether it would be 
overly difficult to parse it into nice, manipulatible data.
I'd suppose my ultimate goal would be to dynamically parse a vBulletin and feed 
it into a locally hosted NNTP server. 


--
http://mail.python.org/mailman/listinfo/python-list


-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Numpy combine channels

2012-09-10 Thread Nick Cash
> I have an array generated by audiolab of left and right stereo
> channels. It looks like [[1,1],[1,2],[2,3]]. I would like to combine
> the left and right channels to get an array [2,3,5]. Is there a numpy
> command to do that?

You may be over-thinking this, and numpy might not be necessary.

A simple solution would be just a quick list comprehension:

stereo_array = [[1, 1], [1, 2], [2, 3]]
mono_array = [l+r for (l, r) in stereo_array]

Thanks,
Nick Cash


-- 
http://mail.python.org/mailman/listinfo/python-list


RE: get google scholar using python

2012-10-01 Thread Nick Cash
> urllib2.urlopen('http://scholar.google.co.uk/scholar?q=albert
>...
> urllib2.HTTPError: HTTP Error 403: Forbidden
> >>>
> 
> Will you kindly explain me the way to get rid of this?

Looks like Google blocks non-browser user agents from retrieving this query. 
You *could* work around it by setting the User-Agent header to something fake 
that looks browser-ish, but you're almost certainly breaking Google's TOS if 
you do so.

Should you really really want to, urllib2 makes it easy:
urllib2.urlopen(urllib2.Request("http://scholar.google.co.uk/scholar?q=albert+einstein%2B1905&btnG=&hl=en&as_sdt=0%2C5&as_sdtp=";,
 headers={"User-Agent":"Mozilla/5.0 Cheater/1.0"}))

-Nick Cash
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: len() on mutables vs. immutables

2012-10-18 Thread Nick Cash
> I'm curious as to the implementation (I'd be happy to dig through the
> source, just don't have the time right now). I've seen various
> implementations across interpreters in the past (some which have been
> rather shocking) and I'd like to get some insight into Python (well,
> CPython at this point anyway).
> 
> When len() is called passing an immutable built-in type (such as a
> string), I'd assume that the overhead in doing so is simply a function
> call and there are no on-call calculations done. Is that correct?
> 
> I'd also assume that mutable built-in types (such as a bytearray) would
> cache their size internally as a side effect of mutation operations. Is
> that correct? If so, is it safe to assume that at least all built-in
> types observe this behavior, or are there some that incur an O(n) cost
> on every len() call?

It appears that list has len() complexity of O(1)
source: http://wiki.python.org/moin/TimeComplexity
It may be worth mentioning that lists in Python are implemented using arrays 
instead of linked lists.

It's reasonable to assume that other built-in collection types would be 
similar, though I don't see anything explicitly saying so for bytearray.

-Nick Cash

-- 
http://mail.python.org/mailman/listinfo/python-list


SQLAlchemy: How to do Table Reflection and MySQL?

2012-10-20 Thread Nick Sabalausky
Hi, I'm fairly new to Python, and I'm trying to figure out how to use
SQLAlchemy to connect to a MySQL DB and use table reflection to set up
SQLAlchemy's tables. But the  SQLAlchemy documentation is gigantic and
frankly kinda making my head spin, so I'm having trouble even finding
any information on how to use its table reflection, mostly just that it
exists and *can* be done, but not so much "how". My web searching has
just been turning up examples of SQLite and manually describing the
tables in Python and having SQLAlchemy create the tables, which isn't
what I'm looking for.

Is there a simple way to do this somehow? To just connect to a MySQL DB
and use table reflection?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SQLAlchemy: How to do Table Reflection and MySQL?

2012-10-23 Thread Nick Sabalausky
On Mon, 22 Oct 2012 14:35:23 -0700 (PDT)
darnold  wrote:
> 
> i'm not brave enough to dig too deeply into SQLAlchemy, but maybe this
> will help? :
> 
> http://kashififtikhar.blogspot.com/2010/07/using-sqlalchemy-reflection-with-pylons.html
> 
> that came up from googling "sqlalchemy table reflection tutorial".

Thanks, your view of Google seems to be far better tailored for Python
than mine is, that doesn't come up for me anywhere on the first five
pages of results for that query.

Unfortunately the info on that page doesn't seem to work for me:

--
from sqlalchemy import *
from sqlalchemy.orm import sessionmaker

engine = create_engine(my connection string)
meta = MetaData()
meta.bind = engine
meta.reflect()

Session = sessionmaker(bind=engine)
session = Session()

res = session.query(user).filter(user.name=="bert").first()
print res.name
--

That just gives me:

NameError: name 'user' is not defined

(And yes, the code given on that page to print out the table info
*does* indicate a table named 'user' was found.)

I also tried this which also fails:

res =
session.query(meta.tables["user"]).filter(meta.tables["user"].name=="bert").first()

sqlalchemy.exc.ArgumentError: filter() argument must be of type
sqlalchemy.sql.ClauseElement or string

The page you linked to appears to get around the matter by manually
setting up tables filled with the reflected info, but that seems to
defeat much of the point for me. I may as well just set up the tables
manually without the reflection, which is what I'll probably do.

Maybe I just misunderstood what was meant in the SQLAlchemy docs here?:

"but note that SA can also “import” whole sets of Table objects
automatically from an existing database (this process is called table
reflection)."  --
http://docs.sqlalchemy.org/en/rel_0_7/core/tutorial.html

It said that but then didn't say how and didn't link to any info on how.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SQLAlchemy: How to do Table Reflection and MySQL?

2012-10-23 Thread Nick Sabalausky
On Tue, 23 Oct 2012 22:42:08 +
"Prasad, Ramit"  wrote:

> Nick Sabalausky wrote:
> > On Mon, 22 Oct 2012 14:35:23 -0700 (PDT)
> > darnold  wrote:
> > >
> > > i'm not brave enough to dig too deeply into SQLAlchemy, but maybe
> > > this will help? :
> > >
> > > http://kashififtikhar.blogspot.com/2010/07/using-sqlalchemy-reflection-with-pylons.html
> > >
> > > that came up from googling "sqlalchemy table reflection tutorial".
> > 
> > Thanks, your view of Google seems to be far better tailored for
> > Python than mine is, that doesn't come up for me anywhere on the
> > first five pages of results for that query.
> > 
> > Unfortunately the info on that page doesn't seem to work for me:
> > 
> > --
> > from sqlalchemy import *
> > from sqlalchemy.orm import sessionmaker
> > 
> > engine = create_engine(my connection string)
> > meta = MetaData()
> > meta.bind = engine
> > meta.reflect()
> > 
> > Session = sessionmaker(bind=engine)
> > session = Session()
> > 
> > res = session.query(user).filter(user.name=="bert").first()
> > print res.name
> > --
> > 
> > That just gives me:
> > 
> > NameError: name 'user' is not defined
> > 
> > (And yes, the code given on that page to print out the table info
> > *does* indicate a table named 'user' was found.)
> 
> This does not seem to be a SQLAlchemy problem. Instead it seems
> there is not a variable called `name`. 

Oops, yea, it's supposed to be:

meta.tables["user"].columns["name"]

Not:

meta.tables["user"].name

Works now, thanks all.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Good use for itertools.dropwhile and itertools.takewhile

2012-12-04 Thread Nick Mellor
Hi Neil,

Nice! But fails if the first word of the description starts with a capital 
letter.

Nick


On Wednesday, 5 December 2012 01:23:34 UTC+11, Neil Cerutti  wrote:
> On 2012-12-04, Nick Mellor  wrote:
> 
> > I have a file full of things like this:
> 
> >
> 
> > "CAPSICUM RED fresh from Queensland"
> 
> >
> 
> > Product names (all caps, at start of string) and descriptions
> 
> > (mixed case, to end of string) all muddled up in the same
> 
> > field. And I need to split them into two fields. Note that if
> 
> > the text had said:
> 
> >
> 
> > "CAPSICUM RED fresh from QLD"
> 
> >
> 
> > I would want QLD in the description, not shunted forwards and
> 
> > put in the product name. So (uncontrived) list comprehensions
> 
> > and regex's are out.
> 
> >
> 
> > I want to split the above into:
> 
> >
> 
> > ("CAPSICUM RED", "fresh from QLD")
> 
> >
> 
> > Enter dropwhile and takewhile. 6 lines later:
> 
> >
> 
> > from itertools import takewhile, dropwhile
> 
> > def split_product_itertools(s):
> 
> > words = s.split()
> 
> > allcaps = lambda word: word == word.upper()
> 
> > product, description = takewhile(allcaps, words), dropwhile(allcaps, 
> > words)
> 
> > return " ".join(product), " ".join(description)
> 
> >
> 
> > When I tried to refactor this code to use while or for loops, I
> 
> > couldn't find any way that felt shorter or more pythonic:
> 
> 
> 
> I'm really tempted to import re, and that means takewhile and
> 
> dropwhile need to stay. ;)
> 
> 
> 
> But seriously, this is a quick implementation of my first thought.
> 
> 
> 
> description = s.lstrip(string.ascii_uppercase + ' ')
> 
> product = s[:-len(description)-1]
> 
> 
> 
> -- 
> 
> Neil Cerutti

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Good use for itertools.dropwhile and itertools.takewhile

2012-12-04 Thread Nick Mellor
Hi Terry,

For my money, and especially in your versions, despite several expert solutions 
using other features, itertools has it. It seems to me to need less nutting out 
than the other approaches. It's short, robust, has a minimum of symbols, uses 
simple expressions and is not overly clever. If we could just get used to using 
takewhile.

takewhile mines for gold at the start of a sequence, dropwhile drops the dross 
at the start of a sequence.

Thanks all for your interest and your help,

Best,

Nick

Terry's implementations:

> from itertools import takewhile
> 
> def allcaps(word): return word == word.upper()
> 
> 
> 
> def split_product_itertools(s):
> 
>  product = ' '.join(takewhile(allcaps, s.split()))
> 
>  return product, s[len(product)+1:]
> 
> 
> 
> print(split_product_itertools("CAPSICUM RED fresh from QLD"))
> 
>  >>>
> 
> ('CAPSICUM RED', 'fresh from QLD')
> 
> 
> 
> [if there could be surplus whitespace], the same idea applies to the split 
> list.
> 
> 
> 
> def split_product_itertools(s):
> 
>  words = s.split()
> 
>  product = list(takewhile(allcaps, words))
> 
>  return ' '.join(product), ' '.join(words[len(product):])
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Good use for itertools.dropwhile and itertools.takewhile

2012-12-05 Thread Nick Mellor
Hi Neil,

Here's some sample data. The live data is about 300 minor variations on the 
sample data, about 20,000 lines.

Nick

Notes:

1. Whitespace is only used for word boundaries. Surplus whitespace is not 
significant and can be stripped

2. Retain punctuation and parentheses

3. Product is zero or more words in all caps at start of line

4. Description is zero or more words beginning with first word that is not all 
caps. Description continues to the end of the line

5. Return tuple of strings (product, description)


Sample data
---

BEANS hand picked
BEETROOT certified organic
BOK CHOY (bunch)
BROCCOLI Mornington Peninsula
BRUSSEL  SPROUTS
CABBAGE green
CABBAGE Red
CAPSICUM RED
CARROTS
CARROTS loose
CARROTS juicing, certified organic
CARROTS Trentham, large seconds, certified organic
CARROTS Trentham, firsts, certified organic
CAULIFLOWER
CELERY Mornington Peninsula IPM grower 
CELERY Mornington Peninsula IPM grower 
CUCUMBER
EGGPLANT
FENNEL
GARLIC (from Argentina)
GINGER fresh uncured
KALE (bunch)
KOHL RABI certified organic
LEEKS
 LETTUCE iceberg
MUSHROOM cup or flat
MUSHROOM Swiss brown
ONION brown
ONION red
ONION spring (bunch)
PARSNIP, certified organic
POTATOES certified organic
POTATOES Sebago
POTATOES Desiree
POTATOES Bullarto chemical free
POTATOES Dutch Cream
POTATOES Nicola
POTATOES Pontiac
POTATOES Otway Red
POTATOES teardrop
PUMPKIN certified organic
SCHALLOTS brown
SNOW PEAS
SPINACH I'll try to get certified organic (bunch)
SWEET POTATO gold certified organic 
SWEET POTATO red small
SWEDE certified organic
TOMATOES  Qld
TURMERIC fresh certified organic
ZUCCHINI
APPLES Harcourt  Pink Lady, Fuji, Granny Smith
APPLES Harcourt 2 kg bags, Pink Lady or Fuji (bag)
AVOCADOS
AVOCADOS certified organic, seconds
BANANAS Qld, organic
GRAPEFRUIT
GRAPES crimson seedless
KIWI FRUIT Qld certified organic
LEMONS
LIMES
MANDARINS
ORANGES Navel
PEARS Beurre Bosc Harcourt new season
PEARS Packham, Harcourt new season
SULTANAS 350g pre-packed bags
EGGS Melita free range, Barker's Creek
BASIL (bunch)
CORIANDER (bunch)
DILL (bunch)
MINT (bunch)
PARSLEY (bunch)


On Thursday, 6 December 2012 00:29:13 UTC+11, Neil Cerutti  wrote:
> On 2012-12-05, Nick Mellor  wrote:
> 
> > Hi Terry,
> 
> >
> 
> > For my money, and especially in your versions, despite several
> 
> > expert solutions using other features, itertools has it. It
> 
> > seems to me to need less nutting out than the other approaches.
> 
> > It's short, robust, has a minimum of symbols, uses simple
> 
> > expressions and is not overly clever. If we could just get used
> 
> > to using takewhile.
> 
> 
> 
> The main reason most of the solutions posted failed is lack of
> 
> complete specification to work with while sumultaneously trying
> 
> to make as tiny and simplistic a solution as possible.
> 
> 
> 
> I'm struggling with the empty description bug right now. ;)
> 
> 
> 
> -- 
> 
> Neil Cerutti

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Good use for itertools.dropwhile and itertools.takewhile

2012-12-05 Thread Nick Mellor
Neil,

Further down the data, found another edge case:

"Spring ONION from QLD"

Following the spec, the whole line should be description (description starts at 
first word that is not all caps.) This case breaks the latest groupby.

N
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: urlopen in python3

2012-12-05 Thread Nick Cash
> In python2, this work if "something" is a regular file on the system as
> well as a remote URL. The 2to3 script convert this to
> urllib.request.urlopen. But it does not work anymore if "something"
> is just a file name.
> 
> My aim is to let the user specify a "file" on the command line and have
> something that works, whatever the "file " actually is: a regular file,
> an http url, etc...

A file path, such as "/etc/passwd", isn't properly a URL, so urllib correctly 
refuses to handle it. You can make it a URL by using the file:// protocol, i.e. 
"file:///etc/passwd"... which appears to work in both python2 and python3.

-- 
http://mail.python.org/mailman/listinfo/python-list


RE: How to get time.strptime()?

2012-12-26 Thread Nick Cash
> Error: AttributeError: 'module' object has no attribute '_strptime'
> 
> This problem is driving me crazy. It only happens in Python 3.3.0,
> while on my server running 3.1.3 it behaves as expected. When I try to
> access time.strptime() it errors with
> 
> AttributeError: 'module' object has no attribute '_strptime'.
> 
> This error only occurs under mod_wsgi, when running as a one-shot
> webapp it behaves normally. All other functionalities of the time
> module are normal.

I've run into this issue in the past with Python 2.6 (or maybe 2.7) and 
mod_python. My problem was that datetime.strptime imported _strptime at 
runtime, and multiple threads trying to import it at the same time broke an 
internal import lock.

I was able to work around this by simply importing _strptime myself at server 
startup time. This may or may not work for you.

See also: http://code.google.com/p/modwsgi/issues/detail?id=177 and 
http://www.mail-archive.com/python-list@python.org/msg248664.html 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a specific sort of string modification. Can someone help?

2013-01-06 Thread Nick Mellor
Hi Sia,

Here's another variation. It's within my tolerance for readability :-) and also 
quick, if that's an issue. It does 100,000 of your longer string in a couple of 
seconds on my venerable laptop.

It handles only single-digit numbers. For multi-digit, I'd be inclined to have 
a look at takewhile and/or dropwhile, both in itertools (Python 2.7 and 3.x 
only.)


from string import maketrans

class redux:

def __init__(self):
   intab = '+-'
   outtab = '  ' # two spaces
   self.trantab = maketrans(intab, outtab)


def reduce_plusminus(self, s):
list_form = [r[int(r[0]) + 1:] if r[0].isdigit() else r
for r
in s.translate(self.trantab).split()]
return ''.join(list_form)

if __name__ == "__main__":
p = redux()
print p.reduce_plusminus(".+3ACG.+5CAACG.+3ACG.+3ACG")
print p.reduce_plusminus("tA.-2AG.-2AG,-2ag")

for n in range(10): p.reduce_plusminus(".+3ACG.+5CAACG.+3ACG.+3ACG")

On Saturday, 5 January 2013 19:35:26 UTC+11, Sia  wrote:
> I have strings such as:
> 
> 
> 
> tA.-2AG.-2AG,-2ag
> 
> or
> 
> .+3ACG.+5CAACG.+3ACG.+3ACG
> 
> 
> 
> The plus and minus signs are always followed by a number (say, i). I want 
> python to find each single plus or minus, remove the sign, the number after 
> it and remove i characters after that. So the two strings above become:
> 
> 
> 
> tA..,
> 
> and
> 
> ...
> 
> 
> 
> How can I do that?
> 
> Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a specific sort of string modification. Can someone help?

2013-01-06 Thread Nick Mellor
Hi Sia,

Find a multi-digit method in this version:

from string import maketrans
from itertools import takewhile

def is_digit(s): return s.isdigit()

class redux:

def __init__(self):
   intab = '+-'
   outtab = '  '
   self.trantab = maketrans(intab, outtab)


def reduce_plusminus(self, s):
list_form = [r[int(r[0]) + 1:] if r[0].isdigit() else r
for r
in s.translate(self.trantab).split()]
return ''.join(list_form)

def reduce_plusminus_multi_digit(self, s):
spl = s.translate(self.trantab).split()
digits = [list(takewhile(is_digit, r))
   for r
   in spl]
numbers = [int(''.join(r)) if r else 0
   for r
in digits]
skips = [len(dig) + num for dig, num in zip(digits, numbers)]
return ''.join([s[r:] for r, s in zip(skips, spl)])

if __name__ == "__main__":
p = redux()
print p.reduce_plusminus(".+3ACG.+5CAACG.+3ACG.+3ACG")
print p.reduce_plusminus("tA.-2AG.-2AG,-2ag")
print 'multi-digit...'
print p.reduce_plusminus_multi_digit(".+3ACG.+5CAACG.+3ACG.+3ACG")
print p.reduce_plusminus_multi_digit(".+12ACGACGACGACG.+5CAACG.+3ACG.+3ACG")


HTH,

Nick

On Saturday, 5 January 2013 19:35:26 UTC+11, Sia  wrote:
> I have strings such as:
> 
> 
> 
> tA.-2AG.-2AG,-2ag
> 
> or
> 
> .+3ACG.+5CAACG.+3ACG.+3ACG
> 
> 
> 
> The plus and minus signs are always followed by a number (say, i). I want 
> python to find each single plus or minus, remove the sign, the number after 
> it and remove i characters after that. So the two strings above become:
> 
> 
> 
> tA..,
> 
> and
> 
> ...
> 
> 
> 
> How can I do that?
> 
> Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a specific sort of string modification. Can someone help?

2013-01-06 Thread Nick Mellor
Note that the multi-line version above tolerates missing digits: if the number 
is missing after the '+/-' it doesn't skip any letters.

Brief explanation of the multi-digit version:

+/- are converted to spaces and used to split the string into sections. The 
split process effectively swallows the +/- characters.

The complication of multi-digits is that you need to skip the (possibly 
multiple) digits, which adds another stage to the calculation. In:

+3ACG. -> .

you skip 1 + 3 characters, 1 for the digit, 3 for the following letters as 
specified by the digit 3. In:

-11ACGACGACGACG. -> G.

You skip 2 + 11 characters, 2 digits in "12" and 11 letters following. And 
incidentally in:

+ACG. -> ACG.

there's no digit, so you skip 0 digits + 0 letters.

Having split on +/- using .translate() and .split() I use takewhile to separate 
the zero or more digits from the following letters. If takewhile doesn't find 
any digits at the start of the sequence, it returns the empty list []. 
''.join(list) swallows empty lists so dropwhile and ''.join() cover the 
no-digit case between them. If a lack of digits is a data error then it would 
be easy to test for-- just look for an empty list in 'digits'.

I was pleasantly surprised to find that using list comprehensions, zip, join 
(all highly optimised in Python) and several intermediate lists still works at 
a fairly decent speed, despite using more stages to handle multi-digits. But it 
is about 4x slower than the less flexible 1-digit version on my hardware (about 
25,000 per second.)

Nick

On Monday, 7 January 2013 14:40:02 UTC+11, Nick Mellor  wrote:
> Hi Sia,
> 
> 
> 
> Find a multi-digit method in this version:
> 
> 
> 
> from string import maketrans
> 
> from itertools import takewhile
> 
> 
> 
> def is_digit(s): return s.isdigit()
> 
> 
> 
> class redux:
> 
> 
> 
> def __init__(self):
> 
>intab = '+-'
> 
>outtab = '  '
> 
>self.trantab = maketrans(intab, outtab)
> 
> 
> 
> 
> 
> def reduce_plusminus(self, s):
> 
> list_form = [r[int(r[0]) + 1:] if r[0].isdigit() else r
> 
> for r
> 
> in s.translate(self.trantab).split()]
> 
> return ''.join(list_form)
> 
> 
> 
> def reduce_plusminus_multi_digit(self, s):
> 
> spl = s.translate(self.trantab).split()
> 
> digits = [list(takewhile(is_digit, r))
> 
>for r
> 
>in spl]
> 
> numbers = [int(''.join(r)) if r else 0
> 
>for r
> 
> in digits]
> 
> skips = [len(dig) + num for dig, num in zip(digits, numbers)]
> 
> return ''.join([s[r:] for r, s in zip(skips, spl)])
> 
> 
> 
> if __name__ == "__main__":
> 
> p = redux()
> 
> print p.reduce_plusminus(".+3ACG.+5CAACG.+3ACG.+3ACG")
> 
> print p.reduce_plusminus("tA.-2AG.-2AG,-2ag")
> 
> print 'multi-digit...'
> 
> print p.reduce_plusminus_multi_digit(".+3ACG.+5CAACG.+3ACG.+3ACG")
> 
> print 
> p.reduce_plusminus_multi_digit(".+12ACGACGACGACG.+5CAACG.+3ACG.+3ACG")
> 
> 
> 
> 
> 
> HTH,
> 
> 
> 
> Nick
> 
> 
> 
> On Saturday, 5 January 2013 19:35:26 UTC+11, Sia  wrote:
> 
> > I have strings such as:
> 
> > 
> 
> > 
> 
> > 
> 
> > tA.-2AG.-2AG,-2ag
> 
> > 
> 
> > or
> 
> > 
> 
> > .+3ACG.+5CAACG.+3ACG.+3ACG
> 
> > 
> 
> > 
> 
> > 
> 
> > The plus and minus signs are always followed by a number (say, i). I want 
> > python to find each single plus or minus, remove the sign, the number after 
> > it and remove i characters after that. So the two strings above become:
> 
> > 
> 
> > 
> 
> > 
> 
> > tA..,
> 
> > 
> 
> > and
> 
> > 
> 
> > ...
> 
> > 
> 
> > 
> 
> > 
> 
> > How can I do that?
> 
> > 
> 
> > Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a specific sort of string modification. Can someone help?

2013-01-06 Thread Nick Mellor
Oops!

"You skip 2 + 11 characters, 2 digits in "12" and 11 letters following. And 
incidentally in: "

should read:

"You skip 2 + 11 characters, 2 digits in "11" and 11 letters following. And 
incidentally in: "

N

On Saturday, 5 January 2013 19:35:26 UTC+11, Sia  wrote:
> I have strings such as:
> 
> 
> 
> tA.-2AG.-2AG,-2ag
> 
> or
> 
> .+3ACG.+5CAACG.+3ACG.+3ACG
> 
> 
> 
> The plus and minus signs are always followed by a number (say, i). I want 
> python to find each single plus or minus, remove the sign, the number after 
> it and remove i characters after that. So the two strings above become:
> 
> 
> 
> tA..,
> 
> and
> 
> ...
> 
> 
> 
> How can I do that?
> 
> Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need a specific sort of string modification. Can someone help?

2013-01-06 Thread Nick Mellor
Hi Sia, 

Thanks for the problem! I hope you find these examples understandable.

Below, find an inflexible but fairly fast single-digit method and a slower (but 
still respectable) multi-digit method that copes with entirely absent digits 
after +/- and multi-digit skips such as 12 or 37 or 186 following letters 
rather than just 3 or 5 or 9. Not knowing your problem domain I'm not sure if 
these larger skips are likely or even possible, nor whether it's likely that 
there will be no digit.

Neither method flags the edge case where there are not enough letters to skip 
before the next +/-. They just swallow that chunk of the string entirely 
without error. Is that a problem?

Python 2.7 or later.

from string import maketrans
from itertools import takewhile

# function used by takewhile to detect digits
def is_digit(s): return s.isdigit()

class redux:

def __init__(self):
   intab = '+-'
   outtab = '  '
   self.trantab = maketrans(intab, outtab)


# simple-minded, fast, 1-digit algorithm
def reduce_plusminus(self, s):
list_form = [r[int(r[0]) + 1:] if r[0].isdigit() else r
for r
in s.translate(self.trantab).split()]
return ''.join(list_form)

# multi-digit algorithm
def reduce_plusminus_multi_digit(self, s):
chunks = s.translate(self.trantab).split()
digits = [list(takewhile(is_digit, r))
   for r
   in chunks]
# zero case ('else 0') is for missing digit(s)
numbers = [int(''.join(r)) if r else 0
   for r
in digits]
# how far to skip (number and skipped letters)
skips = [len(dig) + num
 for dig, num
 in zip(digits, numbers)]
return ''.join([sequence[skipover:]
for skipover, sequence
in zip(skips, chunks)])

if __name__ == "__main__":
p = redux()
print (p.reduce_plusminus(".+3ACG.+5CAACG.+3ACG.+3ACG"))
print (p.reduce_plusminus("tA.-5AG.-2AG,-2ag"))
print ('multi-digit...')
print (p.reduce_plusminus_multi_digit(".+3ACG.+5CAACG.+3ACG.+3ACG"))
print 
(p.reduce_plusminus_multi_digit(".+12ACGACGACGACG.+5CAACG.+3ACG.+3ACG"))
print 
(p.reduce_plusminus_multi_digit(".+12ACGACGACGACG.+5CAACG.+ACG.+3ACG"))

for n in range(10): 
p.reduce_plusminus_multi_digit(".+12ACGACGACGACG.+5CAACG.+3ACG.+3ACG")


Note that the multi-line version above tolerates missing digits: if the number 
is missing after the '+/-' it doesn't skip any letters. 

Explanation:

String slicing is good in Python, but list comprehensions are often the most 
powerful and efficient way to transform data. If you've come from another 
language or you're a newb to programming, it's well worth getting grips with 
list comprehensions [a for b in lst].

First, +/- are converted to spaces. Splitting the string into a list, breaking 
at spaces, effectively swallows the +/- characters and leaves us with chunks of 
string from which to drop the specified number of letters. Having dropped the 
letters, we convert the transformed list back into a string.

The single-digit version just assumes that the number is always present and 
always single-digit. If you allow multi-digits be ready to skip those multiple 
digits, as well as skipping letters, adding another stage to the calculation. 
E.g. in: 

+3ACG. -> . 

you skip 1 + 3 characters, 1 for the digit, 3 for the following letters as 
specified by the digit 3. In: 

-11ACGACGACGACG. -> G. 

You skip 2 + 11 characters, 2 characters in "11" and 11 characters following. 
And incidentally in: 

+ACG. -> ACG. 

there's no digit, so you skip 0 digits + 0 letters. If a lack of digits is a 
data error then it would be easy to test for-- just look for an empty list in 
the 'digits' list.

For each chunk (stuff between +/-) I use takewhile to separate the zero or more 
initial digits from the following letters. itertools.takewhile is a nice tool 
for matching stuff until the first time a condition ceases to hold. In this 
case I'm matching digits up until the first non-digit.

If takewhile doesn't find any digits at the start of the sequence, it returns 
the empty list []. ''.join(list) swallows empty lists so takewhile and 
''.join() do behind-the-scenes leg-work for me in detecting the case of absent 
digit(s).

For my money speed isn't bad for these two methods (again, I don't know your 
domain.) On my (ancient) hardware the 1-digit version does over 100,000/s for 
your longer string, the multi-digit about 35,000/s.

HTH,

Nick

On Saturday, 5 January 2013 19:35:26 UTC+11, Sia  wrote:
> I have strings such as:
> 
> 
> 
&g

Probabilistic unit tests?

2013-01-10 Thread Nick Mellor
Hi,

I've got a unit test that will usually succeed but sometimes fails. An 
occasional failure is expected and fine. It's failing all the time I want to 
test for.

What I want to test is "on average, there are the same number of males and 
females in a sample, give or take 2%."

Here's the unit test code:
import unittest
from collections import counter

sex_count = Counter()
for contact in range(self.binary_check_sample_size):
p = get_record_as_dict()
sex_count[p['Sex']] += 1
self.assertAlmostEqual(sex_count['male'],
   sex_count['female'],
   delta=sample_size * 2.0 / 100.0)

My question is: how would you run an identical test 5 times and pass the group 
*as a whole* if only one or two iterations passed the test? Something like:

for n in range(5):
# self.assertAlmostEqual(...)
# if test passed: break
else:
self.fail()

(except that would create 5+1 tests as written!)

Thanks for any thoughts,

Best wishes,

Nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Parent module adsite.adsiteviews.mainhanlder does not exist

2013-01-17 Thread Nick Dong
I created a django project using django 1.4.2. There is one 'app'(adsite) in 
this project. And It works. But when I copied some 'py' files into the 'app' 
folder, I got "Parent module adsite.adsiteviews.mainhanlder does not exist." 
Should I register the new files to __init__ in the 'app'? Did new coped files 
break the "import" rules?

views.py

from django.http import HttpResponse
from django.template import Context, loader
from adsite.models import UserInfo

def showusers(request):
userlist = UserInfo.objects.all()
c = Context({
'userlist':userlist,
})
t = loader.get_template('users.html')

return HttpResponse(t.render(c))

copied file: adsiteviews.py

class mainhanlder(TemplateView)
def get(self):
""" """
variables = {
'user': self.get_current_user(),
'mchosts' : MCHOSTS, 
'servers' : servers}

index_templ = tmpl_lookup.get_template("index.html")
body = index_templ.render(**variables)
self.write(body)

urls.py

urlpatterns = patterns('',
# Examples:
url(r'^$', 'adsite.adsiteviews.mainhandler.as_View()'),
url(r'^users/$', 'adsite.views.showusers'),

I have no clues about this problem. any suggestions would be appreciated. thx 
for your time.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Vote tallying...

2013-01-18 Thread Nick Cash
> I have a problem which may fit in a mysql database, but which I only
> have python as an alternate tool to solve... so I'd like to hear some
> opinions...

Is there a reason you can't use an RDBMS for this? MySQL would certainly be 
fine, although I always recommend PostgreSQL over it. Based on the amount of 
data you've specified, you really don't want to be rolling your own data 
storage system. If you absolutely cannot install any new software, Sqllite is 
built into Python and would work almost as well.

-- 
http://mail.python.org/mailman/listinfo/python-list


urllib2 FTP Weirdness

2013-01-23 Thread Nick Cash
Python 2.7.3 on linux

This has me fairly stumped. It looks like
urllib2.urlopen("ftp://some.ftp.site/path";).read()
will either immediately return '' or hang indefinitely. But
response = urllib2.urlopen("ftp://some.ftp.site/path";)
response.read()
works fine and returns what is expected. This is only an issue with urllib2, 
vanilla urllib doesn't do it.

The site I first noticed it on is private, but I can reproduce it with 
"ftp://ftp2.census.gov/";.

I've tested the equivalent code on Python 3.2.3 and get the same results, 
except that one time I got a socket error (may have been a spurious network 
blip, though). 


I'm at a loss as to how that could even work differently. My only guess is that 
by not having a reference to the addinfourl response object, something 
important is getting garbage collected or closed... that seems like a stretch, 
though. Is this a urllib2 bug, or am I crazy?

-Nick Cash


-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Split string first data have ",

2013-01-29 Thread Nick Cash
> >>> y = '"abc.p,zip.p",a,b'
> >>> print y
> "abc.p,zip.p",a,b
> >>>

>>> x = "what is your question??"
>>> print x

I'm guessing that you want to split on ",", but want the quoted section to be a 
single token? 
Have you looked at the CSV module (http://docs.python.org/3/library/csv.html)?

If my guess is wrong, or you're having difficulties with the csv module, a more 
specific question will help you get the answer you're looking for.

-Nick Cash

-- 
http://mail.python.org/mailman/listinfo/python-list


RE: (any)dbm module lacks a context manager

2013-01-31 Thread Nick Cash
> >>> import dbm
> >>> with dbm.open("mydb", 'c') as d:
> ... d["hello"] = "world"
> ...
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: '_dbm.dbm' object has no attribute '__exit__'

This error message is somewhat misleading... it actually means you're trying to 
use an object as a context manager, and it doesn't implement the context 
manager protocol (defined __enter__ and __exit__ methods). In this case, 
db.open() returns a dict -like object that is not a context manager. You'd need 
to refactor your code to something like:

import dbm
d = dbm.open("mydb", 'c')
d["hello"] = "world"
d.close() 

You may want to wrap any actions on d with a try-except-finally so you can 
always close the db. If dbm objects were real context managers, they would do 
this for you. 
This does seem like a useful enhancement. It might be slightly involved to do, 
as the dbm module has multiple implementations depending on what libraries are 
available on the OS.

-Nick Cash

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parsing a serial stream too slowly

2012-01-23 Thread Nick Dokos
M.Pekala  wrote:

> On Jan 23, 5:00 pm, Jon Clements  wrote:
> > On Jan 23, 9:48 pm, "M.Pekala"  wrote:
> >
> >
> >
> >
> >
> >
> >
> >
> >
> > > Hello, I am having some trouble with a serial stream on a project I am
> > > working on. I have an external board that is attached to a set of
> > > sensors. The board polls the sensors, filters them, formats the
> > > values, and sends the formatted values over a serial bus. The serial
> > > stream comes out like $A1234$$B-10$$C987$,  where "$A.*$" is a sensor
> > > value, "$B.*$" is a sensor value, "$C.*$" is a sensor value, ect...
> >
> > > When one sensor is running my python script grabs the data just fine,
> > > removes the formatting, and throws it into a text control box. However
> > > when 3 or more sensors are running, I get output like the following:
> >
> > > Sensor 1: 373
> > > Sensor 2: 112$$M-160$G373
> > > Sensor 3: 763$$A892$
> >
> > > I am fairly certain this means that my code is running too slow to
> > > catch all the '$' markers. Below is the snippet of code I believe is
> > > the cause of this problem...
> >
> > > def OnSerialRead(self, event):
> > >         text = event.data
> > >         self.sensorabuffer = self.sensorabuffer + text
> > >         self.sensorbbuffer = self.sensorbbuffer + text
> > >         self.sensorcbuffer = self.sensorcbuffer + text
> >
> > >         if sensoraenable:
> > >                 sensorresult = re.search(r'\$A.*\$.*', self.sensorabuffer 
> > > )
> > >                         if sensorresult:
> > >                                 s = sensorresult.group(0)
> > >                                 s = s[2:-1]
> > >                                 if self.sensor_enable_chkbox.GetValue():
> > >                                         self.SensorAValue = s
> > >                                 self.sensorabuffer = ''
> >
> > >         if sensorbenable:
> > >                 sensorresult = re.search(r'\$A.*\$.*', self.sensorbenable)
> > >                         if sensorresult:
> > >                                 s = sensorresult.group(0)
> > >                                 s = s[2:-1]
> > >                                 if self.sensor_enable_chkbox.GetValue():
> > >                                         self.SensorBValue = s
> > >                                 self.sensorbenable= ''
> >
> > >         if sensorcenable:
> > >                 sensorresult = re.search(r'\$A.*\$.*', self.sensorcenable)
> > >                         if sensorresult:
> > >                                 s = sensorresult.group(0)
> > >                                 s = s[2:-1]
> > >                                 if self.sensor_enable_chkbox.GetValue():
> > >                                         self.SensorCValue = s
> > >                                 self.sensorcenable= ''
> >
> > >         self.DisplaySensorReadings()
> >
> > > I think that regex is too slow for this operation, but I'm uncertain
> > > of another method in python that could be faster. A little help would
> > > be appreciated.
> >
> > You sure that's your code? Your re.search()'s are all the same.
> 
> Whoops you are right. the search for the second should be re.search(r'\
> $B.*\$.*', self.sensorbbuffer ), for the third re.search(r'\$C.*\$.*',
> self.sensorcbuffer )
> 

The regex is probably still wrong: r'\$A.*\$.*' will e.g. match all of
your initial example "$A1234$$B-10$$C987$", so s will lose the initial
and final '$' and end up as "1234$$B-10$$C987" - I doubt that's what you
want:

>>> sensor_result = "$A123$$B456$$C789$$A456$"
>>> r = re.search(r'\$A.*\$.*', sensor_result)
>>> s = r.group(0)
>>> s = s[2:-1]
>>> s
'123$$B456$$C789$$A456'

Is this perhaps closer to what you want?

>>> r = re.search(r'\$A[^$]+\$', sensor_result)
>>> r.group(0)
'$A123$'
>>> 

I'm sure there are more problems too - e.g. why are there three buffers?
If they all start empty and get modified the same way, they will all
contain the same string - are they modified differently in the part of
the program you have not shown? They will presumably need to be trimmed
appropriately to indicate which part has been consumed already. And, as
somebody pointed out already, the searches should probably be against
the *buffer* variables rather than the *enable* variables.

Nick

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Libxml2 Python Manual

2012-01-24 Thread Nick Dokos
Mauricio Martinez Garcia  wrote:

>   For libxml2, are there any manual. For this library?, i searched on
> google and just find the following URL xmlsoft.org Wich can not find
> any API manual.
> 

Did you check under "Reference Manual" at http://xmlsoft.org? That's the
second entry in the Main Menu.

Nick

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Determining version of OpenSSL linked against python?

2012-01-25 Thread Nick Dokos
Adam Mercer  wrote:

> On Wed, Jan 25, 2012 at 14:04, Terry Reedy  wrote:
> 
> > If you are not willing to tell Debian Squeeze users to install 2.7, or that
> > they cannot run your program, ask the bug reporter to tell you what version
> > of OpenSSL the system comes with and code it into your program.
> 
> I would like to only support python-2.7 as that would make a few other
> things easier but the powers that be think otherwise, I unfortunately
> need to target python-2.6.
> 
> > Or possibly, depending on what you do with the version info and what the
> > differences are between versions, replace 'if version ...' constructs with
> > 'try ... except...' constructs.
> 
> My code already has a try... except block that tries the
> ssl.OPENSSL_VERSION approach first but I wanted to have a fallback
> method that works with python-2.6. Looks like I may need to hardcode
> certain things.
> 

One other possibility is to parse the output of ssh -V:

,
| $ ssh -V
| OpenSSH_5.8p1 Debian-1ubuntu3, OpenSSL 0.9.8o 01 Jun 2010
| $ python
| Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) 
| [GCC 4.5.2] on linux2
| Type "help", "copyright", "credits" or "license" for more information.
| >>> import ssl
| >>> ssl.OPENSSL_VERSION
| 'OpenSSL 0.9.8o 01 Jun 2010'
| >>> 
`

This assumes that ssh and python would use the same version of openssl:
not guaranteed, but seems like a "reasonable" assumption to me.

Nick


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TypeError

2012-02-01 Thread Nick Dokos
Clark, Kathleen  wrote:



> TypeError: sequence item 1: expected string, NoneType found
> 
> The error message is referencing line 86 of my code:
> 
> ws.cell(row=row, column=1).value = ','.join([str(ino), fn, ln, sdob])
> 
> If I’m understanding this correctly, the code is expecting a string, but not 
> finding it.  I’m
> wondering, what is meant by a “string” and also how I can figure out the 
> problem and correct it. 

I'd guess that the sequence in question is the list that's the argument
of join(), in which case item 1 is fn: it should be a string but for some
reason, it is a None value:

,
| >>> ','.join([str(45), None, "bar", "foo"])
| Traceback (most recent call last):
|   File "", line 1, in 
| TypeError: sequence item 1: expected string, NoneType found
|>>> ','.join([str(45), "a string", "bar", "foo"])
|'45,a string,bar,foo'
`

Nick

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help writelines

2012-02-03 Thread Nick Dokos
Anatoli Hristov  wrote:

> Hi everyone,
> 
> I`m totaly new in python and trying to figure out - how to write a list to a 
> file with a newline at the end of each object.
> I tried alot of combinations :) like:
> users = ['toli','didi']
> fob=open('c:/Python27/Toli/username','w')
> fob.writelines(users) + '%s\N'
> fob.close()
>  or fob.writelines('\N' % users) 
> or fob.writelines('%s\N' % users)
> but nothing of dose works...
> 
> Could you help me find out the right syntaxes?
> 

From the docs:

 |  writelines(...)
 |  writelines(sequence_of_strings) -> None.  Write the strings to the file.
 |  
 |  Note that newlines are not added.  The sequence can be any iterable 
object
 |  producing strings. This is equivalent to calling write() for each 
string.

So *you* need to add the newlines, e.g. you can use a list comprehension:

   fob.writelines(["%s\n" % (x) for x in users])

or write in a loop:

   for u in users:
   fob.write("%s\n" % (u))

or join the list elements together with a newline separator (but you'll
need to add a final newline by hand):

   fob.writelines("\n".join(users) + "\n")

or ...

Nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python usage numbers

2012-02-12 Thread Nick Dokos
rusi  wrote:

> On Feb 12, 10:51 am, Steven D'Aprano  +comp.lang.pyt...@pearwood.info> wrote:
> > On Sun, 12 Feb 2012 15:38:37 +1100, Chris Angelico wrote:
> > > Everything that displays text to a human needs to translate bytes into
> > > glyphs, and the usual way to do this conceptually is to go via
> > > characters. Pretending that it's all the same thing really means
> > > pretending that one byte represents one character and that each
> > > character is depicted by one glyph. And that's doomed to failure, unless
> > > everyone speaks English with no foreign symbols - so, no mathematical
> > > notations.
> >
> > Pardon me, but you can't even write *English* in ASCII.
> >
> > You can't say that it cost you £10 to courier your résumé to the head
> > office of Encyclopædia Britanica to apply for the position of Staff
> > Coördinator. (Admittedly, the umlaut on the second "o" looks a bit stuffy
> > and old-fashioned, but it is traditional English.)
> >
> > Hell, you can't even write in *American*: you can't say that the recipe
> > for the 20¢ WobblyBurger™ is © 2012 WobblyBurgerWorld Inc.
> 
> [Quite OT but...] How do you type all this?
> [Note: I grew up on APL so unlike Rick I am genuinely asking :-) ]

[Emacs speficic]

Many different ways of course, but in emacs, you can select e.g. the TeX input 
method
with C-x RET C-\ TeX RET.
which does all of the above symbols with the exception of the cent
symbol (or maybe I missed it) - you type the thing in the first column and you
get the thing in the second column

\pounds £
\'e é
\ae æ
\"o ö
^{TM}   ™
\copyright ©

I gave up on the cent symbol and used ucs-insert (C-x 8 RET) which allows you 
to type
a name, in this case CENT SIGN to get ¢.

Nick


-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Where to set default data - where received, or where used

2012-06-11 Thread Nick Cash
This is really up to your programming style, but I'm of the opinion that 
defining all of the default values in one place keeps maintenance easier.

Of course, if it's done differently elsewhere in your code base, I would aim 
for consistency instead.

Thanks,
Nick Cash

-Original Message-
From: python-list-bounces+nick.cash=npcinternational@python.org 
[mailto:python-list-bounces+nick.cash=npcinternational@python.org] On 
Behalf Of Dennis Carachiola
Sent: Monday, June 11, 2012 13:38
To: python-list@python.org
Subject: Where to set default data - where received, or where used

I'm programming a project which will use a file to save parameters needed by 
the program.  There are already two previous file formats, each of which can 
only be run by the version of the program which created them.  I'm trying to 
avoid that problem in the future.  To do that, I intend to use a dictionary, 
and default data.  I believe that most new versions will add parameters.

Each version of the program will have reasonable default values for each key in 
the dictionary handled by that version.  If an older file is used, the data 
values in that file replace the keys that exist.
The program then can operate on the values supplied by the older data file and 
the default values.  Conversely, if a newer file is used, the data in the file 
replaces the keys in the dictionary.  The program then simply doesn't access 
the newer data values.  I'm hoping that this will make the file backward and 
forward compatible.

Here's my question.  I could do this by creating the dictionary with the 
default values, then read the file into it.  Or I could use a 'get' with 
default values at the location in the program where those values are used.

>From what I can see, creating the dictionary with default values puts
everything in one place.  While, supplying the default values at the place 
where they're used places the default values nearest the place where actually 
used.

I can't decide on one way over the other.  Can anyone give me some ideas if one 
is a preferred method, or other criteria I've overlooked?

Thanks,

Den
--
http://mail.python.org/mailman/listinfo/python-list


-- 
http://mail.python.org/mailman/listinfo/python-list


Problem porting class to python3.2

2011-06-02 Thread Nick Buchholz
Hi all,
I've been wandering through the DOCs for an hour and haven't found a 
solution to this
I'm just starting to convert from 2.5 to 3.2 and I have a problem. I have a 
code that looks like this.

from tkinter  import *
import time
import datetime
import string
import math
import random

print (time.localtime())

def foo():
print (time.localtime())

print(time.localtime())

class StarDate:
""" implements StarDates regular dates but with output in
the form: MMDD:HHMMSS.
or represented by a 6-Tuple (Yr, Mon, Day, Hour, Min, Sec)
"""
def __init__(self, tTuple=None):
tt=self
tt.tm_year = tt.tm_mon = tt.tm_mday = tt.tm_hour = 0
tt.tm_min  = tt.tm_sec = tt.tm_wday = tt.tm_yday = 0
tt.tm_isdst  = 0
if type(tTuple) == type(None):
tTuple = time.localtime()
elif ...

The two print statements work as expected, printing the tuple of the local time.
The function foo and the StarDate class definition both fail with the error.

   File "starDate.py", line 37 , in foo
  print(time.localtime())
NameError: global name 'time' is not defined
or
  File "starDate.py", line 103, in __init__
tTuple = time.localtime()
NameError: global name 'time' is not defined

What am I missing?  This is a long used and tested file and class that is used 
in several 
more complex python programs.
why doesn't the definition of time at the top level get recognized inside the 
class?
If I can't get a simple two class file working in 3.2, I despair of ever moving 
to 3.2

Please reply directly.

Nick
nbuchh...@noao.edu
Day phone: (520) 318-8203
"Time is an illusion, Lunchtime doubly so" - Ford Prefect
Time is an illusion perpetrated by the manufacturers of space.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem porting class to python3.2

2011-06-02 Thread Nick Buchholz
On Thu, 02 Jun 2011 09:18:18 -0700
 "Nick Buchholz"  wrote:
>Hi all,
>I've been wandering through the DOCs for an hour and haven't found a 
> solution to this
>I'm just starting to convert from 2.5 to 3.2 and I have a problem. I have a 
>code that looks like this.
> 
...code removed 
>
First thanks to all who replied. FYI the classes in the file have been working 
in various 
environments since I wrote them in python1.3 and updated them to python 2.x in 
2005.

I think I solved the problem, well not solved in that I don't know why the 
technique I used failed.
but at least the code works when used as an import.

Under my 2.5 system I had a startup file that included the line
ld = execfile

mostly because I got tired of typing execfile('filename') to load in a file I 
was testing

2to3 complained it couldn't parse this line so I changed to

def ld(filename):
exec(compile(open(file).read(), file, 'exec'))

when I tried 
ld('starDate.py') at the python3.2 prompt I got the indicated errors

if at the prompt I instead type 
import starDate

I get no errors and the classes and methods work as expected.  I'm sure this is 
a 
name space problem but I don't know what the problem is. Its obvious that the 
3.2 
replacement for execfile does not have the same effect as execfile.

Thanks again
Nick
nbuchh...@noao.edu
Day phone: (520) 318-8203
"Time is an illusion, Lunchtime doubly so" - Ford Prefect
Time is an illusion perpetrated by the manufacturers of space.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyCon

2011-03-11 Thread Nick Stinemates
http://blip.tv/search?q=pycon

<http://blip.tv/search?q=pycon>HTH
Nick

On Fri, Mar 11, 2011 at 4:45 AM, Rita  wrote:

> Hello,
>
> I noticed the old presentations at PyCon aren't avaliable anymore.
> http://us.pycon.org/2010/ http://us.pycon.org/2009/
>
> Does anyone know where else I can get these presentations?
>
> --
> --- Get your facts first, then you can distort them as you please.--
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Could I joined in this Happy family

2011-03-18 Thread Nick Stinemates
Welcome aboard !
On Mar 18, 2011 11:34 AM, "duxiu xiang"  wrote:
> Dear friends:
> I am in China.For some rearon,I cannot visit your Google Group.May
> I joint this mail list for help in learning Python?
>
> --
> 笑看嫣红染半山,逐风万里白云间。
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python time

2011-03-20 Thread Nick Stinemates
You should just use cron (or Windows Scheduled Tasks if that's your thing)
for job scheduling, allowing people the flexibility of the environment they
already know.

Nick

On Sun, Mar 20, 2011 at 6:19 PM, ecu_jon  wrote:

> I'm working on a script that will run all the time. at time specified
> in a config file, will kick-off a backup.
> problem is, its not actually starting the job. the double while loop
> runs, the first comparing date works. the second for hour/min does
> not.
>
> #python file
> import os,string,,time,getpass,ConfigParser
> from datetime import *
> from os.path import join, getsize
> from time import strftime,localtime
>
> config = ConfigParser.ConfigParser()
> config.read("config.ini")
> source = config.get("myvars", "source")
> destination = config.get("myvars", "destination")
> date = config.get("myvars", "date")
> time = config.get("myvars", "time")
> str_time=strftime("%H:%M",localtime())
>
> while datetime.now().weekday() == int(date):
>while str_time == time:
>print "do it"
>
> #config file
> #change the time variable to "now"+a min or two to observe
> #this needs to be where ever the actual python script is
> [myvars]
> #only set source if you want it to be different
> source: c:\users\jon
> destination: \\mothera\jon\
> #what day of the week to perform backup?where Monday is 0 and Sunday
> is 6
> date: 6
> #time to start
> time: 21:02
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


[OSys PL Labs] 3 UI/UX Research Engineer Positions for Progr. Languages and Tools (Remote)

2021-08-24 Thread Nick Papoylias
Dear colleagues,

The newly founded PL (Programming Languages) research Group at OutSystems

has a goal of exploring the UI/UX frontier of Programming Tools.

We are looking for 3 UI/UX Research Engineers for Programming Languages &
Tools (Remote) to join our group. Please forward to anyone you think might
be interested by our call:

Europe/EMEA:
https://www.outsystems.com/careers/job-detail/8a7887a87acffd16017b1cedb4930469/

US/Americas:
https://www.outsystems.com/careers/job-detail/8a7885a87b55f750017b7479ec9f365b/

India/APAC:
https://www.outsystems.com/careers/job-detail/8a7883a97ad004d8017b1011897d76de/

Best Regards,

Dr. Papoulias (@npapoylias )
*Director of Research **@OutSystems* 

==

*If you consider yourself (or aspire to be) a UI/UX expert with programming
experience that wants to: “Boldly go where no programmer has gone before”
don’t let any impostor syndrome stop you, apply to join us! What we are
looking for in our research group -- first and foremost -- is explorers.
Take a look at this short video to quickly learn more about
OutSystems: https://youtu.be/0gx3hMMDOZI. *



*Responsibilities:*


** Your base responsibility will be the development of research prototypes
from an engineering perspective. Nevertheless, the research nature of these
prototypes will almost always require you to either learn a new language, a
new system or way of working. You will always be given time and guidance
(bibliography, books and an engineering starting point) to do so. The
director of the group will always be there to guide you with all aspects of
your work.*


** Once this base responsibility is fulfilled your UI/UX experience and
expertise will help us go even further. What can we add to a good prototype
to bring aesthetics and usability to the mix ? What will make us smile
every time we use it ?*


** When you become comfortable with the above responsibilities you can
start proposing your own experiments to the team and guide our newest
members through the whole R&D process.*
** Finally, according to the group’s needs you will be tasked to present
our work to colleagues, internally or externally (to the wider industrial
and academic community), participate in conferences, publications and in
the general dissemination of our work.*
-- 
https://mail.python.org/mailman/listinfo/python-list


Wrong release date in 3.6 whats new docs?

2016-12-14 Thread Nick Sarbicki
Afternoon everyone.

Might be missing something obvious but the 3.6 What's New docs point to the
release date being the 12th.

https://docs.python.org/3.6/whatsnew/3.6.html#what-s-new-in-python-3-6

I got the team excited about Friday's release so that caused some confusion
here.

Guessing it's a typo?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Wrong release date in 3.6 whats new docs?

2016-12-14 Thread Nick Sarbicki
I'm aware of the the schedule in the PEP.

But if the date at the top of the What's New page is the last day it was
updated and not the release date then that is what has caused the confusion.

On Wed, 14 Dec 2016, 22:58 ,  wrote:

> On Wednesday, December 14, 2016 at 2:09:22 PM UTC, Nick Sarbicki wrote:
> > Afternoon everyone.
> >
> > Might be missing something obvious but the 3.6 What's New docs point to
> the
> > release date being the 12th.
> >
> > https://docs.python.org/3.6/whatsnew/3.6.html#what-s-new-in-python-3-6
> >
> > I got the team excited about Friday's release so that caused some
> confusion
> > here.
> >
> > Guessing it's a typo?
>
> Are you confusing the date on which the what's new was updated with the
> release schedule here https://www.python.org/dev/peps/pep-0494/ ?
>
> Kindest regards.
>
> Mark Lawrence.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Basic plugin architecture

2016-04-06 Thread Nick Sarbicki
Hi,

Question on how people here would design a basic plugin architecture:

I'm playing with the idea of having a pluggable system where the users can
create some simple classes which can then be accessed in a Django app.

I want to make it as __simple__ as possible for the user. Hopefully to the
point of being able to make a .py file and then drag and drop it into the
plugins folder. The result should be a dropdown later on with the list of
available classes.

Providing the list of classes once imported should be simple.

Actually importing the classes dynamically has caused a few issues.

I have a solution but wanted to know if anyone had better ideas.

Folder structure is:

├run.py
└loader/
  ├─plugins/
  │ ├─__init__.py
  │ ├─plugin1.py
  │ └─plugin2.py
  ├─__init__.py
  ├─models.py
  ├─views.py
  └─etc.py

My current solution is:

loader/plugins/__init__.py
> import glob
> import importlib
> import os
>
> def is_valid_plugin(plugin):
> return os.path.isfile(plugin) and not
os.path.basename(plugin).startswith('_')
>
> package = 'loader.plugins'
>
> plugins_to_import = [plugin for plugin in
glob.glob(os.path.dirname(__file__) + '/*.py') if is_valid_plugin(plugin)]
>
> plugins = [importlib.import_module('.' + os.path.basename(plugin)[:-3],
package) for plugin in plugins_to_import]

In relative terms I'm looking at the packages from the same position as
run.py, so would import as:

> from loader import plugins

plugins.plugins would then be a list of imported plugin modules.

With this I can use the __dict__ of each plugin module in plugins.plugins
to find which classes we want to use.

This works. But I wonder if there is a better way.

Any suggestions?

- Nick.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Average calculation Program *need help*

2016-05-13 Thread Nick Sarbicki
On Fri, 13 May 2016, 06:52 Jake Kobs,  wrote:

> Thank you for the help..I think I'm getting closer, but I feel like after
> they enter an invalid number, it should reset the invalid number(s)
> somehow. Here's my updated code:
>
> --
> #this function will get the total scores
> def getScores(totalScores, number):
> for counter in range(0, number):
> score = input('Enter their score: ')
> if (score < 100 and score > 0):
> totalScores = totalScores + score
> while (score > 100 or score < 0):
>
> print "Your scores must be between 0 and 100."
> score = input('Enter their score: ')
> score = input('Enter their score: ')
> totalScores = totalScores + score
>
>
> return totalScores
>
> 
> --
>

You're starting to get it which is good.

The if is a good idea to begin with, but your while loop still executes
after the for loop finishes as it is not properly indented.

As Michael said, indentation indicates what statement has ownership of a
block. Currently your while loop has it's own block outside the for loop.

This means it gets executed after your for loop has finished looping
through your range. You want the while to be held within the for loop so it
gets executed immediately after each input statement.

Think. Your if is inside the for loop and gets executed after every input.
Your input is inside the for loop. Your while and it's contents are not in
the for loop and get executed after the for loop finishes. The only
difference that matters here is indentation.

Try solve that bit first.

>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Recommendation for GUI lib?

2016-06-02 Thread Nick Sarbicki
>
>
> >
> > Do you have any recommendations? Primary platforms are OS X and Linux.
> >
> > I, of course, want to have "standard" widgets but a "calendar
> > view"/"date picker" is a plus.
>

I generally use PyQt which is one of two (the other being pyside) python
wrappers for the Qt libraries.

PyQt is the only one I know which currently supports Qt5+ so gets my vote.
There are loads of resources around - works well on all operating systems
(with most Qt5 having some focus on mobile). It comes with a ton of
utilities and a really nice GUI editor (
https://en.wikipedia.org/wiki/Qt_Creator).

There are a lot of resources around and, as predicted, already has some
examples of date pickers:

http://www.eurion.net/python-snippets/snippet/Calendar_Date%20picker.html

- Nick.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Recommendation for GUI lib?

2016-06-07 Thread Nick Sarbicki
>
> Qt Designer is certainly a good GUI builder, but not more than that.
> When you actually want to use the designed GUI in Python, you will find
> that this needs almost as much know how and work as if you did the GUI
> in code.
>

I think that's a bit of an unfair statement. Sure conversion can be a bit
of a pain and there is some setup for getting the classes working. But that
is generally a small static piece of code you can find all over the net,
which is then usable for most projects.

The code you get from Qt creator however can be a huge bulk of the work
which you thankfully don't need to nitpick over much at all.

Yes understanding how it works helps a lot and I'd recommend anyone to have
a look at how to build a decent GUI with Qt.

But for me, once past the understanding, coding GUIs by hand is about as
dull as it gets. Qt creator definitely makes the work go faster.

- Nick.

>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Guys, can you please share me some sites where we can practice python programs for beginners and Intermediate.

2016-06-22 Thread Nick Sarbicki
On Wed, Jun 22, 2016 at 9:42 AM Miki Tebeka  wrote:

> IMO you can do that at https://www.codecademy.com/learn/python
>

Some people might think differently but I wouldn't recommend a python
course which teaches 2.7 over 3.x.

It bugs me that learnpythonthehardway and codecademy - probably 2 of the
biggest platforms for learning python at the moment - both refuse to move
to python 3.
-- 
https://mail.python.org/mailman/listinfo/python-list


[CfP] DLS 2019 - 15th Dynamic Languages Symposium, co-located with SPLASH 2019

2019-03-23 Thread Nick Papoylias

Call for Papers

 DLS 2019 - 15th Dynamic Languages Symposium

 Co-located with SPLASH 2019, October 22, Athens, Greece

   https://conf.researchr.org/home/dls-2019
Follow us @dynlangsym


Dynamic Languages play a fundamental role in today’s world of software,
from the perspective of research and practice. Languages such as
JavaScript, R, and Python are vehicles for cutting edge research as well
as building widely used products and computational tools.

The 15th Dynamic Languages Symposium (DLS) at SPLASH 2019 is the
premier forum for researchers and practitioners to share research and
experience on all aspects on dynamic languages.

DLS 2019 invites high quality papers reporting original research and
experience related to the design, implementation, and applications of
dynamic languages.

Areas of interest are generally empirical studies, language design,
implementation, and runtimes, which includes but is not limited to:

- innovative language features
- innovative implementation techniques
- innovative applications
- development environments and tools
- experience reports and case studies
- domain-oriented programming
- late binding, dynamic composition, and run-time adaptation
- reflection and meta-programming
- software evolution
- language symbiosis and multi-paradigm languages
- dynamic optimization
- interpretation, just-in-time and ahead-of-time compilation
- soft/optional/gradual typing
- hardware support
- educational approaches and perspectives
- semantics of dynamic languages
- frameworks and languages for the Cloud and the IoT

Submission Details
--

Submissions must neither be previously published nor under review at
other events. DLS 2019 uses a single-blind, two-phase reviewing process.

Papers are assumed to be in one of the following categories:

  Research Papers:
  describe work that advances the current state of the art

  Experience Papers:
  describe insights gained from substantive practical
  applications that should be of a broad interest

  Dynamic Pearls:
  describe a known idea in an appealing way to remind the
  community and capture a reader’s interest

The program committee will evaluate each paper based on its
relevance, significance, clarity, and originality.
The paper category needs to be indicated during submission,
and papers are judged accordingly.

Papers are to be submitted electronically at https://dls19.hotcrp.com/
in PDF format. Submissions must be in the ACM SIGPLAN conference acmart
format, 10 point font, and should not exceed 12 pages. Please see full
details in the instructions for authors available at:

https://conf.researchr.org/home/dls-2019#Instructions-for-Authors

DLS 2019 will run a two-phase reviewing process to help authors make
their final papers the best that they can be. Accepted papers will be
published in the ACM Digital Library and will be freely available for
one month, starting two weeks before the event.

Important Deadlines
---

Abstract Submission:   May 29, 2019
Paper Submission:  June 5, 2019
First Phase Notification:  July 3, 2019
Final Notifications:   August 14, 2019
Camera Ready:  August 28, 2019



All deadlines are 23:59 AoE (UTC-12h).

AUTHORS TAKE NOTE: The official publication date is the date the
proceedings are made available in the ACM Digital Library. This date
may be up to two weeks prior to the first day of your conference.
The official publication date affects the deadline for any patent
filings related to published work.

Program Committee
-

Alexandre Bergel, University of Chile
Carl Friedrich Bolz-Tereick, Heinrich-Heine-Universität Düsseldorf
Chris Seaton, Oracle Labs
David Chisnall, Microsoft Research
Elisa Gonzalez Boix, Vrije Universiteit Brussel
Gregor Richards, University of Waterloo
Guido Chari, Czech Technical University
Hannes Payer, Google
James Noble, Victoria University of Wellington
Jeremy Singer, University of Glasgow
Joe Gibbs Politz, University of California San Diego
Juan Fumero, The University of Manchester
Julien Ponge, Red Hat
Mandana Vaziri, IBM Research
Manuel Serrano, Inria
Marc Feeley, Université de Montréal
Mark Marron, Microsoft Research
Na Meng, Virginia Tech
Nick Papoulias, Université Grenoble Alpes
Richard Roberts, Victoria University of Wellington
Sam Tobin-Hochstadt, Indiana University
Sarah Mount, Aston University
Sébastien Doeraene, École polytechnique fédérale de Lausanne
William Cook, University of Texas at Austin


Program Chair
-

Stefan Marr, University of Kent, United Kingdom
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Which editor is suited for view a python package's source?

2019-08-19 Thread Nick Sarbicki
PyCharm takes you to the source code within the editor for any
variables/functions/classes/modules if you ctrl+click on what you want to
see. It allows you to browse the relevant bits of code quickly, as well as
let you change them in your local environment if need be.

That way you don't have to download the source separately, you can just use
it as a normal dependency.

But if you want to view the source of a project in isolation I imagine any
common editor will suffice. Personally I'll tend to look where the source
is hosted (GitHub, GitLab etc) instead of downloading it. But I can
understand why some may not trust this.

On Mon, 19 Aug 2019, 10:17 ,  wrote:

> I like to download one package's source and study it in an editor. It
> allows me to open the whole package as a project and let me jump from a
> reference in one file to its definition in another file back and forth. It
> will be even better if it can handle the import modules too. (Maybe this is
> too much:-)
>
> Can anyone recommend such a tool?
>
> --Jach
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Which editor is suited for view a python package's source?

2019-08-19 Thread Nick Sarbicki
Yes the community edition works fine.

It seems to require a 64 bit version of Windows 7 or higher (I'm not sure
as I haven't used Windows in years).

On Tue, 20 Aug 2019, 03:27 ,  wrote:

> Nick Sarbicki於 2019年8月19日星期一 UTC+8下午5時33分27秒寫道:
> > PyCharm takes you to the source code within the editor for any
> > variables/functions/classes/modules if you ctrl+click on what you want to
> > see. It allows you to browse the relevant bits of code quickly, as well
> as
> > let you change them in your local environment if need be.
> >
> > That way you don't have to download the source separately, you can just
> use
> > it as a normal dependency.
> >
> > But if you want to view the source of a project in isolation I imagine
> any
> > common editor will suffice. Personally I'll tend to look where the source
> > is hosted (GitHub, GitLab etc) instead of downloading it. But I can
> > understand why some may not trust this.
> >
> > On Mon, 19 Aug 2019, 10:17 ,  wrote:
> >
> > > I like to download one package's source and study it in an editor. It
> > > allows me to open the whole package as a project and let me jump from a
> > > reference in one file to its definition in another file back and
> forth. It
> > > will be even better if it can handle the import modules too. (Maybe
> this is
> > > too much:-)
> > >
> > > Can anyone recommend such a tool?
> > >
> > > --Jach
> > > --
> > > https://mail.python.org/mailman/listinfo/python-list
> > >
>
> There is a free community version of PyCharm. Will it support the
> cross-reference of viewing different files in different subdirectory? and
> what Windows versions it requires?
>
> --Jach
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Recommendations for intro to python+programming lecture to Humanities MA students

2019-11-20 Thread Nick Sarbicki
Hi Goktug,

Firstly good luck, inspiring a crowd of people who have never learnt to
code (and probably never expected to) to want to code sounds like a
daunting task.

I think you have broadly the right idea in that you want to spend only a
little bit of time on the basic syntax before demoing what you can do with
the language. I would spend the beginning of the lecture focusing on how
readable code can be - an attempt to make it less scary to people who
haven't touched code before - and then spend the rest of the time showing
the fun things you can do with it.

I can't see trying to take students from no code to competent SciPy users
in one lecture as a possible feat. So it would be best to simply inspire
them to want to learn more themselves. In which case I'd encourage you to
have a think as to what would be the most inspiring examples? Are jupyter
notebooks on their own something that inspires? Probably not - although
they are nice for showcasing code in. Is ETL exciting? Maybe in extremely
rare cases... NLP, AI etc can be pretty fun and powerful. Graphing
libraries such as MatPlotLib as they are visual is always good as well. Can
demo some (probably useless) 3D charts or XKCD mode if you want.

RE Conda and distros - I'd forget about them, in my experience you may as
well learn to use pip and install what you need that way, in the long term
it is faster and more flexible. Python generally supplies a perfectly good
installer for most operating systems at python.org - no need for anything
else. Keeping it to just standard python (+ some libs you don't explicitly
need to explain) makes it less complex. Also - as biased as it sounds
coming from a Python developer - I'm not sure I'd want to discuss
alternatives (R, SPSS etc.) as it just provides more confusing choices.

In summary I'd aim to inspire not to teach - so show some basics at the
beginning to show how accessible it can be, and then feel free to jump off
into advanced python land to showcase what is possible using whatever you
are most comfortable with. Essentially show them they can learn python, and
then inspire them to want to learn python.

Feel free to ignore all of these thoughts, they are highly subjective.


On Wed, Nov 20, 2019 at 5:07 PM Andrew Z  wrote:

> Goktug,
>   Im not clear what is the objective of the lecture? I understand it is an
> intro, but what are you trying to achieve?
>
> I didnt read all the details, but maybe you can look into creating a
> docker/virtual box image with everything preinstalled.
> Good luck.
>
> On Wed, Nov 20, 2019, 11:54 Göktuğ Kayaalp  wrote:
>
> > Hi all,
> >
> > I am responsible of giving my colleagues in from linguistics MA
> > programme an intro to Python, and programming, with a focus on
> > statistics.  It’ll be a single lecture, and I probably won’t be able to
> > do more than give some demos and then some pointers to actually properly
> > learn how to use the tools.
> >
> > The problem is I’m a rather techie power user and my audience the exact
> > opposite, so I feel like I could make use of some guidance as to how to
> > bridge the gap and be useful.
> >
> > I want to stick to Python 3, demo them a few basics of programming, then
> > how to use matplotlib, Jupyter notebooks (is this what IPyNBs became?),
> > and some descriptive statistics.  All this needs to happen within the
> > span of a single lecture (tho if people are interested I’ll offer to do
> > a few more in our own time), so 45min~1h.
> >
> > The first problem is installation: apart from me, a Debian user,
> > everybody has Windows or Mac laptops, and IDK how you install Python on
> > them.  I feel like choosing one of the distros is a good idea: I could
> > just put the installers on a USB and hand it out, or just send them a
> > message with simple steps to follow and set themselves up beforehand.
> > Thing is, IDK nothing about distros.  Anaconda seems to be the best
> > options, but comes with complications like an IDE, as opposed to just
> > working with notebooks, and is huge.  Also, seems to include R stuff.
> > Spyder looks nice, but I don’t want to freak people out with such an
> > unfamiliar environment as an IDE just within the first few moments they
> > encounter programming.  These are all humanities people.  Another
> > problem is that Anaconda has ‘conda’, a non-standard package manager,
> > and I’m kinda vary of introducing that to people: should I talk of pip,
> > should I leave it out?  I feel like I should just stick to pip and leave
> > conda out, but IDK.  Python(x,y) is interesting, but it’s apparently
> > Py2k only, and that’s a no-no.
> >
> > So, am I better off telling people to install Anaconda, or plain Py3k +
> > a selection of packages (which maybe I make into a .zip or something)?
> >
> > Then, I need good pointers to hand out: links to good introductions to
> > Python, programming, and statistical use of Python.  Thing is, I’ve
> > always learned the hacker way, i.e. skip the docs, tinker with stuf

Re: Recommendations for intro to python+programming lecture to Humanities MA students

2019-11-21 Thread Nick Sarbicki
> The simplest thing is to use the 3.8.0 python.org installers.  This use
> pip to add anything you consider essential.

As mentioned previously, you do need to make sure that they tick the box to
add Python to the PATH on windows. It is almost guaranteed someone will not
do that and will then have a very hard time figuring out what has gone
wrong (happens to me every time I teach).

Considering that this is a lecture and not a workshop I'm assuming the
students aren't actively installing and running python while you are
teaching. In which case, whilst I would mention pip, I would probably just
have the required libs preinstalled on my computer ready to go. Learning
pip is easy to do and if they're interested later can be taught separately.
But watching someone installing packages on the terminal is not very
interesting. On the other hand if the students are actively following along
and running python within the lecture then they will obviously need to be
shown how to do this.

Also whilst the remit of the lecture is to showcase how to do statistics in
Python, I wouldn't take this as an absolute limit. I would go through
examples of graphs, probably taking inspiration from
https://www.tylervigen.com/spurious-correlations and using something like
dash (https://dash.plot.ly/). I would also try to show more creative ways
of playing with data - for instance I worked on this project dedicated to
showing data using GIFs (
https://datagifmaker.withgoogle.com/editor/racetrack - don't look too hard
at the representations though).

But instead of spending a whole lecture explicitly on statistics I would
probably use the last 10 minutes showcasing other uses of Python which are
(apologies to those who find statistics utterly encapsulating) a bit more
interesting. For instance I have a <200 LOC game of pong (technically a
_graphical_ user interface) which is usually fun to showcase (
https://gitlab.com/ndevox/pygame-pong/blob/master/pong.py). I'd also be
tempted to show off things like websites (which could display statistics
publicly), chatbots (which, if using something like an NLTK classifier, are
essentially statistical machines) etc. Think about what interests you the
most and see if you can display it on the screen in some way.

Essentially whilst it is very important to show them to make graphs in
various ways, you'll probably struggle to captivate the entire audience
with this. Whereas ending with some slightly wilder but more enticing
examples can make those who weren't interested in the statistics want to
pay more attention to what you have been saying.

- Nick

On Wed, Nov 20, 2019 at 11:33 PM MRAB  wrote:

> On 2019-11-20 21:58, Terry Reedy wrote:
> > On 11/20/2019 11:09 AM, Göktuğ Kayaalp wrote:
> >
> >> The first problem is installation: apart from me, a Debian user,
> >> everybody has Windows or Mac laptops, and IDK how you install Python on
> >> them.
> >
> > The simplest thing is to use the 3.8.0 python.org installers.  This use
> > pip to add anything you consider essential.
> >
> For Windows, I use "Windows x86-64 executable installer" for 64-bit and
> "Windows x86 executable installer" for 32-bit from
> https://www.python.org/downloads/windows/.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Regarding Python

2020-04-16 Thread Nick Kelley

I need to install python 3.7 or above version, however the previously installed 
version is python2.7
I tried many commands
sudo apt-get install python3.8
after running the command it fails
I removed pthon 2.7
but again when I run the command
Python --version
it again shows python 2.7
please suggest the commands
I have my python version 3.8 downloaded in the download folder



If you're using apt, "python" usually points to Python 2; try "python3" 
instead. You can also do


$ dpkg -L python3.8

...which will output a list of files installed with the python3.8 
package. If you compare this with your PATH environment variable, you 
should be able to compare which binary is being executed vs. which one 
you want to execute.


You may also want to look into using virtual environments, as using the 
system python often leads to confusion.

--
https://mail.python.org/mailman/listinfo/python-list


Re: [python-committers] Thank you Larry Hastings!

2020-10-06 Thread Nick Coghlan
Thank you, Larry!

Cheers,
Nick.
-- 
https://mail.python.org/mailman/listinfo/python-list


Python 3

2020-11-06 Thread Nick Li
Does anyone know how to turn a decimal number into duodecimal or if there is a 
function built-in for it? 
-- 
https://mail.python.org/mailman/listinfo/python-list


play audio on OSX?

2005-09-30 Thread Nick Parker
I'm attempting to play an mp3 file on OSX, but am running into some 
difficulty. When using py-mad and py-ao, I only get static with the 
following code (which is derived off another mailing that I found from 
this list's archives):

#!/usr/bin/env python

'''Requires:
py-mad (mp3 ability)
py-ao (system audio ability)
'''
import mad, ao, sys
mf = mad.MadFile(sys.argv[1])
dev = ao.AudioDevice('macosx')#osx device, linux: use "oss" or "alsa"
while 1:
 buf = mf.read()
 if buf is None:
 break
 dev.play(buf, len(buf))

Does anyone know why this produces static, or whether there's a better 
method of producing audio output that's also cross-platform (OSX, 
linux)? I've looked at pymedia, but they do not support OSX at the moment.

Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Circe 0.0.3b1 released

2005-11-08 Thread Nick D.
Matthew Nuzum  gmail.com> writes:

> 
> Hello,
> 
> I'm curious, does Circe use threading? I have been frustrated that
> some of the things I've wanted to do required threading, but haven't
> found much documentation or good examples of using threading with
> wxPy.
> 
> I'm eager to disect the source of something that successfully combines the 
> two.
> 
> --
> Matthew Nuzum
> www.bearfruit.org


Circe, as of this time, does not contain any threading code. We are planning in
the future to possibly add threading when we decide to implement DCC support.
Please check in when we have added that feature, we might have added some
threading.

Thanks,

Nick D.
http://circe.nick125.com

-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: PySizer 0.1

2005-11-13 Thread Nick Smallbone
I'd like to announce the first release of PySizer, a memory usage
profiler for Python code.
PySizer was written as part of Google's Summer of Code.

The source, documentation and so on are at http://pysizer.8325.org.
The current release is at
http://pysizer.8325.org/dist/sizer-0.1.tar.gz.
The code is kept in a Subversion repository at
http://codespeak.net/svn/user/nick8325/sizer.

The idea is to take a snapshot of memory use at some time, and then
use the functions of the profiler to find information about it.

Features

* You can make a snapshot of all reachable objects at a given time,
  organised as a tree (well, a graph, since there are cycles).

* For any given object, you can find out how much space it takes up,
  what objects it references and so on.

  With a patched version of Python, you can also find out what stack of
  function calls created an object, and what objects were created by
  each stack of calls.

* You can collect objects into groups. For example, you can group each
  object according to the module it appears to come from. Then you can
  treat each module as a single object.

* You can filter objects, find the amount of space used by instances of
  each type, find objects which appeared from one snapshot to the next,
  find the biggest objects/types/groups, and so on.

Requirements

See http://pysizer.8325.org/INSTALL.
The main one is Python 2.4 - I will port it to 2.3 soon.

Bugs, suggestions, comments, problems, anything else

You can contact me at [EMAIL PROTECTED] I would love to know if
you find a use for it, too.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PySizer 0.1

2005-11-14 Thread Nick Smallbone
Claudio Grondi wrote:

> A small hint about the Web-site:
> At least to me, the links to the documentation as e.g.
>
> http://pysizer.8325.org/doc/auto/home/nick/sizer-trunk/doc/auto/scanner.html
> are broken (no big thing, because the distro has it anyway).
> 

Oops. That should be fixed now.

-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   8   9   10   >