Re: wiki.python.org

2013-01-09 Thread Ken
On Wed, Jan 09, 2013 at 04:05:31PM +, Reed, Kevin wrote:
> Hello,
> 
> I have been unable to access wiki.python.org for two days.  Is there a 
> problem with the server, or is it me?
> 
> Thank you much,
> 
> Kevin C. Reed
> New Python User

Well, I just tried it twice and could not get there, so I would say it
is a problem on the server's end.

Ken


-- 
Corruption is not the #1 priority of the Police Commissioner.  His job
is to enforce the law and fight crime.
-- P. B. A. President E. J. Kiernan
-- 
http://mail.python.org/mailman/listinfo/python-list


Numerical Linear Algebra in arbitrary precision

2012-02-15 Thread Ken
Brand new Python user and a bit overwhelmed with the variety of
packages available.  Any recommendation for performing numerical
linear algebra (specifically least squares and generalized least
squares using QR or SVD) in arbitrary precision?  I've been looking at
mpmath but can't seem to find much info on built in functions except
for LU decomposition/solve.

Appreciate any comments.

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


strange problem

2006-10-24 Thread ken
This file has 1,000,000+ lines in it, yet when I print the counter 'cin' 
at EOF I get around 10,000 less lines. Any ideas?

lineIn = 
csv.reader(file("rits_feed\\rits_feed_US.csv",'rb'),delimiter='|')
 for emp in lineIn:
 cin=cin+1
 print cin
-- 
http://mail.python.org/mailman/listinfo/python-list


Get my airlines boarding pass

2006-06-09 Thread Ken
rh0dium wrote:
> Hi all,
> 
> Has any of you fine geniuses figured out a nice python script to go to
> the Southwest airlines website and check in, and retrieve your boarding
> pass - automatically 24 hours in advance
> 

I just wrote such a script in python and tested it successfully. Where
should I post it?
  Ken

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


urlopen.read()

2007-04-20 Thread ken
Hi,

When I call urlopen.read() like this:

data = urlopen("http://localhost";).read().

Does that mean I will read the whole document to data, regardless how
many data being sent back?

Thank you.

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


how can I find out the value of an environment variable?

2007-03-05 Thread ken
how can I find out the value of an environment variable in my pythong
script?

Thank you.

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


What is the timeout value of HTTP

2007-03-29 Thread ken
Can you please tell me what is the timeout value of httplib.HTTP?

i.e. how long python will wait for a response in the below code?

   h = httplib.HTTP(self.url, 8080)
h.putrequest('GET', '/sample/?url=' + self.url)
h.endheaders()

Thank you.

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


how to remove specified cookie in cookie jar?

2007-03-30 Thread ken

How to remove specified cookie (via a given name) in cookie jar?

I have the following code, but how can I remove a specified cookie in
the cookie jar?
 cj = cookielib.LWPCookieJar()

 if cj is not None:
 if os.path.isfile(COOKIEFILE):
print 'Loading Cookie--'
cj.load(COOKIEFILE)

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


Question about using urllib2 to load a url

2007-04-01 Thread ken
Hi,

i have the following code to load a url.
My question is what if I try to load an invalide url ("http://
www.heise.de/"), will I get an IOException? or it will wait forever?

Thanks for any help.

 opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)

txheaders = {'User-agent': 'Mozilla/5.0 (X11; U; Linux i686; en-
US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3'}

try:
req = Request(url, txdata, txheaders)
handle = urlopen(req)
except IOError, e:
print e
print 'Failed to open %s' % url
return 0;

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


how can I create/set a 'file' reference in a attribute of a class

2007-02-26 Thread ken
Hi,
i have a class:

class LogHandler(ContentHandler):
# a reference to a file open by some other function/class
outputFile;


def endElement(self, name):
 doSomething(self, "GroupResultList", self.text, outputFile)


First, I get an error saying 'NameError: global name 'outputFile' is
not defined' , how can I declare outputFile as a 'file reference'?

Second , how can I set this file reference after I create the object
'LogHandler'?

How can I do that?
f = open('dummyFile.txt');
curHandler = LogHandler()
curHandler.file = f

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


Re: Garbage collection

2008-02-18 Thread Ken
Simon Pickles wrote:
> Hi,
>
> I'm building a server with python, but coming from a c++ background, 
> garbage collection seems strange.
>
> For instance, I have a manager looking after many objects in a dict. 
> When those objects are no longer needed, I use del manager[objectid], 
> hoping to force the garbage collector to perform the delete.
>
> However, this doesn't trigger my overloaded __del__ destructor. Can I 
> simply rely on the python garbage collector to take it from here?
>   
Objects are deleted at some undefined time after there are no references 
to the object.

You will need to change your thinking about how destructors work.  It is 
very different from C++.

The good news is that you almost never have to do anything to clean up.  
My guess is that you might not even need to overload __del__ at all.  
People from a C++ background often mistakenly think that they have to 
write destructors when in fact they do not.  What is your __del__ method 
doing?
> Is there a way to find how many references exist for an object?
>   
yes:

  from sys import getrefcount
  print getrefcount(x)


> Thanks
>
> Simon
>
>   

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


Re: Adobe CS3

2008-02-26 Thread Ken
Yeah, those are all very good points. There is really no excuse for top 
posting.


Jeff Schwab wrote:

D'Arcy J.M. Cain wrote:
  

On Tue, 26 Feb 2008 12:58:53 -0800
Tobiah <[EMAIL PROTECTED]> wrote:


A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?


But then again, when just adding a quip to a long thread in which
the readers have already seen the previous comments, top posting
can be an advantage to the reader.
  

Unless, of course, you know how to trim quoted text.



And unless the reader (like me) tends to scroll immediately to the 
bottom of the post anyway, without looking for a one-line comment at the 
top.
  


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

list of attributes

2008-03-07 Thread Ken
I have a class with a __getattr__ method that returns various methods.  
I also have the ability to determine the list of method names that are 
supported by my __getattr__ method (this list would be dynamically 
generated as it depends on the current state).

What I would like to know is if there is a way overload the behavior of 
dir(instance) to include this dynamically generated list of method 
names.  Ideally this would have the effect of making these methods 
visible to the autocomplete feature of debuggers in most modern IDEs.

It looks like this would be __dir__ in 2.6, is that right?

Ken

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


Re: Image Libraries

2008-03-08 Thread Ken
PB wrote:
> I have been using PIL for generating images, however it does not
> easily support operations with transparency etc.
>
> I tried to install aggdraw but it wouldn't compile.
>
> Ideally I'd like something open source so I can adapt it, hopefully
> mostly written in python rather than C.
>
> Is there any other decent image libraries for python?
>
>   
I use PIL, and I haven't had any difficulty with alpha channel 
transparency. But maybe I'm using it for different things than you 
(blitting PGN(RGBA) antialiased images mostly). What problems are you 
having specifically?

Ken Seehart


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


Re: Does python hate cathy?

2008-03-23 Thread Ken

Yup, I think Carsten got it. Mystery solved!

You could replace Person with self.__class__ instead of type(self) if 
Person is an old-style class (since the class won't be collected until 
after all the instances are collected (because each instance references 
it's class)). Note that when the name "Person" is set to None, the 
Person class has it's reference count reduced by one but it is not yet 
collected.


Alternatively, if you name your locals to start with "_" (e.g. _cathy) 
you avoid this problem
/"Starting with version 1.5, Python guarantees that globals whose name 
begins with a single underscore are deleted from their module before 
other globals are deleted; if no other references to such globals exist, 
this may help in assuring that imported modules are still available at 
the time when the __del__() method is called."/


But in general, I have this to say: IMO __del__ should not be taught to 
beginners (other than to say "don't use __del__ yet; you have much to 
learn first young jedi"). It should always be put in the "advanced 
topics" section when included in beginning python books along with 
threads, process control, and extending/embedding. If you think you need 
it, you probably don't.


It is an advanced concept that requires a basic understanding of garbage 
collection. Beginners shouldn't really have to know much about garbage 
collection. The whole point is that it is automatic.


__del__ is particularly dangerous for experienced C++ programmers 
starting to learn Python. People look for analogies and when they see 
__del__ they think "destructor" which is sort of vaguely right, but 
completely wrong in practice. The practical difference is that in C++ 
you actually have to deal with implementing destructors all of the time, 
and you can't get very far as a C++ programmer without using them, 
whereas in python you almost never have to deal with destructors. In 
C++, destructors are usually predictable (in correct code), but in 
python code they are somewhat harder to predict because they are invoked 
implicitly at the whim of the python implementation.


In practice you don't need to use __del__ unless you are doing something 
exotic like explicitly implementing your own memory model, or tuning 
resource allocation in a large system. If you are doing ordinary 
day-to-day programming don't even think about __del__.


Ken Seehart


Carsten Haese wrote:

On Sun, 2008-03-23 at 17:42 -0700, George Sakkis wrote:
  

That's really weird... it's reproducible on Windows too. It doesn't
make any sense why the name of the variable would make a difference.
My guess is you hit some kind of obscure bug.



This is not a bug, just an unexpected feature:
http://mail.python.org/pipermail/python-list/2005-January/304873.html

What's happening is that at the end of the script, all objects in the
global namespace are set to None (in order to decrease their reference
count and trigger garbage collection). This happens in the order in
which the names appear as keys in the globals dictionary. It randomly
happens that "swaroop", "kalam", and "cath" all are hashed in front of
"Person", but "cathy" is hashed after "Person".

Hence, if Catherine is named cath, Python "None's" all the instances
first and then the type last, and all is well. However, if Catherine is
called cathy, Person is set to None before cathy. Then, in the lookup of
the global name "Person" during cathy.__del__, Person is None, which
doesn't have a "population" attribute, causing the AttributeError.

Possible workarounds are:
1) Explicitly delete the global names for the instances before the
script runs out.
2) Don't refer to the "Person" type by its global name in __del__, but
indirectly as type(self). (This requires Person to be a new-style class,
though.)

  


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

Quetion about flags of socket.recv(bufsize, [flags])

2009-02-08 Thread Ken
I want to receive 4 bytes from a connected socket, I code like this:

data = sock.recv(4)

There is a problem with above code. The recv method will not block until it
get all 4 bytes. So I use the second param of recv method like this

data = sock.recv(4, socket.MSG_WAITALL)

This works fine on linux with python 2.5, while on windows, the interpreter
tells me 'AttributeError: 'module' object has no attribute 'MSG_WAITALL''.
How can I work this out, or there is another way to get certain bytes from a
socket and block if it hasn't got enough bytes?

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


select error 10093 on winxp

2009-02-09 Thread Ken
I was testing select on windows xp with python 2.6.1, the code is simple:

import sys
import select

def testSelect():
r = select.select([sys.stdin], [], [], 5.0)
print r

if __name__ == "__main__":
try:
testSelect()
except select.error, e:
print e

While an error raised like this:

(10093, '\xd3\xa6\xd3\xc3\xb3\xcc\xd0\xf2\xc3\xbb\xd3\xd0\xb5\xf7\xd3\xc3
WSAStartup\xa3\xac\xbb\xf2\xd5\xdf WSAStartup')

What is this about?

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


Re: python3 tutorial for newbie

2009-02-11 Thread Ken

"Gabriel Genellina"  wrote in message 
news:mailman.9312.1234332608.3487.python-l...@python.org...
> En Tue, 10 Feb 2009 16:22:36 -0200, Gary Wood  
> escribió:
>
>> Can someone recommend a good tutorial for Python 3, ideally that has 
>> tasks or assignments at the end of each chapter.
>
> I don't know of any specifically targetted to Python 3, except the 
> official one at http://www.python.org/doc/3.0/
>
> For the most part, any Python tutorial should be fine. Perhaps the only 
> visible change (at the tutorial level) is that "print" became a function:
>
> # 2.x syntax:
> print "Hello", "world!"
>
> # 3.x syntax:
> print("Hello", "world!")
>
> That said, Python 3.0 is so recent that isn't widely used yet, and many 
> third party libraries aren't available for 3.0 at this moment. This 
> certainly will change in the future, but in the meantime, perhaps you 
> should stick to Python 2.6 for a while.
>
> -- 
> Gabriel Genellina

Several links here:

http://wiki.python.org/moin/Python3.0Tutorials
> 


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


Re: Programming exercises/challenges

2008-11-22 Thread Ken

How about this:  http://www.pythonchallenge.com/

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi guys,
>
> I'm learning Python by teaching myself, and after going through several 
> tutorials I feel like I've learned the basics. Since I'm not taking a 
> class or anything, I've been doing challenges/programs to reinforce the 
> material and improve my skills. I started out with stuff like "Guess my 
> number" games, hangman, etc. and moved on to making poker and card games 
> to work with classes. For GUIs I created games like minesweeper, and a GUI 
> stock portfolio tracker. I am out of ideas and am looking for programming 
> projects, challenges, or programs that have helped you'll learn. I'm 
> working on the project Euler problems, but I find that they don't really 
> help my programming skills; they are more math focused. Suggestions? What 
> has been useful or interesting to you? I'd also welcome sources of 
> textbook type problems, because the ones provided in tutorials tend to be 
> repetitive.
>
> Thanks,
> Ben 


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


Any other web mail accessor like libgmail?

2009-03-31 Thread Ken
Is there other python wrapper such as libhotmail or libyahoomail?

curiously ask. :p
--
http://mail.python.org/mailman/listinfo/python-list


is there a rwlock implementation in python library?

2009-04-08 Thread Ken
I need a read-write-lock, is there already an implementation in the standard
library?
--
http://mail.python.org/mailman/listinfo/python-list


Re: function that accepts any amount of arguments?

2008-04-24 Thread Ken

"Steve Holden" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> globalrev wrote:
>> if i want a function that can take any amount of arguments how do i
>> do?
>>
>> lets say i want a function average that accepts any number of integers
>> and returns the average.
>
> Use a parameter of the form *args - the asterisk tells the interpreter to 
> collect positional arguments into a tuple. Untested:
>
> def mean(*x):
> total = 0.0
> for v in x:
> total += v
> return v/len(x)
>

 think you want total/len(x) in return statement


> regards
>  Steve
> -- 
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC  http://www.holdenweb.com/
> 


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


POST value related question

2009-10-12 Thread ken
hello
i have some problem to send POST value by use mechanize.
i can't write my article to my blog site.

here is full source. and what i want to do is, im posting my article
to my blog site.
thanks in advance.

# -*- coding: cp949 -*-
import mechanize
import cookielib

# Browser
br = mechanize.Browser()

# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)

# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(),
max_time=1)

# Want debugging messages?
#br.set_debug_http(True)
#br.set_debug_redirects(True)
#br.set_debug_responses(True)

# User-Agent (this is cheating, ok?)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-
US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

# Open some site, let's pick a random one, the first that pops in
mind:
r = br.open('http://nid.naver.com/nidlogin.login')
html = r.read()
#print html


# Show the source
#print html
# or
#print br.response().read()

# Show the html title
#print br.title()

# Show the response headers
#print r.info()
# or
#print br.response().info()

# Show the available forms
for f in br.forms():
print f

# Select the first (index zero) form
br.select_form(nr=0)

# Let's search
br.form['id']='lbu142vj'
br.form['sID']=['on']
br.form['pw']='wbelryl'
br.submit()
#print br.response().read()
r = br.open("http://www.naver.com";)
rs = r.read().decode('utf-8')
#print rs
r = br.open("http://blog.naver.com/PostWriteForm.nhn?
Redirect=Write&blogId=lbu142vj&widgetTypeCall=true")
rs = r.read()
print rs

for f in br.forms():
print f

br.select_form(nr=0)
br.form['post.category.categoryNo']="[*1]"
br.form['post.title']='subject'
br.form['contents.contentsValue'] = 'content'
br.submit()
-- 
http://mail.python.org/mailman/listinfo/python-list


POST value related question

2009-10-12 Thread ken
hello
i have some problem to send POST value by use mechanize.
i can't write my article to my blog site.

here is full source. and what i want to do is, im posting my article
to my blog site.
thanks in advance.

# -*- coding: cp949 -*-
import mechanize
import cookielib

# Browser
br = mechanize.Browser()

# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)

# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(),
max_time=1)

# Want debugging messages?
#br.set_debug_http(True)
#br.set_debug_redirects(True)
#br.set_debug_responses(True)

# User-Agent (this is cheating, ok?)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686;
en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/
3.0.1')]

# Open some site, let's pick a random one, the first that pops in
mind:
r = br.open('http://nid.naver.com/nidlogin.login')
html = r.read()
#print html


# Show the source
#print html
# or
#print br.response().read()

# Show the html title
#print br.title()

# Show the response headers
#print r.info()
# or
#print br.response().info()

# Show the available forms
for f in br.forms():
print f

# Select the first (index zero) form
br.select_form(nr=0)

# Let's search
br.form['id']='lbu142vj'
br.form['sID']=['on']
br.form['pw']='wbelryl'
br.submit()
#print br.response().read()
r = br.open("http://www.naver.com";)
rs = r.read().decode('utf-8')
#print rs
r = br.open("http://blog.naver.com/PostWriteForm.nhn?
Redirect=Write&blogId=lbu142vj&widgetTypeCall=true")
rs = r.read()
print rs

for f in br.forms():
print f

br.select_form(nr=0)
br.form['post.category.categoryNo']="[*1]"
br.form['post.title']='subject'
br.form['contents.contentsValue'] = 'content'
br.submit()
-- 
http://mail.python.org/mailman/listinfo/python-list


mechanize.browser() click or submit related problem

2010-04-12 Thread ken
Hello All.
im making some website login function with mechanize.browser() module.
but problem is i can't send submit or click submit button with
mechanize click() function, it not working.
how can i submit button or click() function make it work?
i can make it work mechanize.Request and mechanize.urlopen() 's POST
function,but
this time i want to make it work mechanize.browser() which emulate web
browser.
please help me!
thanks in advance


# -*- coding: utf-8 -*-
import sys,os
import mechanize, urllib
import cookielib
from BeautifulSoup import BeautifulSoup,BeautifulStoneSoup,Tag
import datetime, time
import re,sys,os,mechanize,urllib,threading,time, socket
br = mechanize.Browser()
# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)

# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(),
max_time=1)

# Want debugging messages?
br.set_debug_http(True)
br.set_debug_redirects(True)
br.set_debug_responses(True)

br.addheaders = [('User-agent', 'Mozilla/4.0 (compatible; MSIE 7.0b;
Windows NT 5.1)')]

br.clear_history()

br.open('http://xo.nate.com/login.jsp')
html = br.response().read()
#print html
 #Show the available forms
for f in br.forms():
print f

# Select the first (index zero) form
#br.select_form(nr=1)
br.select_form(name='f_login')
# Let's search
br.form['ID']= 'prudy'
#br.form['user_password']=['on']
br.form['PASSWD']= 'sotkfkd'
print br.geturl()
br.submit()
html = br.response().read()
print html
-- 
http://mail.python.org/mailman/listinfo/python-list


python urllib mechanize post problem

2010-05-23 Thread ken
hello ALL

im making some simple python post script but it not working well.

there is 2 part to have to login.

first login is using 'http://mybuddy.buddybuddy.co.kr/userinfo/
UserInfo.asp' this one.

and second login is using 'http://user.buddybuddy.co.kr/usercheck/
UserCheckPWExec.asp'

i can login first login page, but i couldn't login second page
website.

and return some error 'illegal access' such like .

i heard this is related with some cooke but i don't know how to
implement to resolve this problem.

if anyone can help me much appreciated!! Thanks!

import re,sys,os,mechanize,urllib,time
import datetime,socket


params = urllib.urlencode({'ID':'ph896011', 'PWD':'pk1089' })
rq = mechanize.Request("http://mybuddy.buddybuddy.co.kr/userinfo/
UserInfo.asp", params)
rs = mechanize.urlopen(rq)
data = rs.read()

logged_fail = r';history.back();'  in
data
if not logged_fail:
 print 'login success'
 try:
  params = urllib.urlencode({'PASSWORD':'pk1089'})
  rq = mechanize.Request("http://user.buddybuddy.co.kr/usercheck/
UserCheckPWExec.asp", params )
  rs = mechanize.urlopen(rq)
  data = rs.read()
  print data
 except:
  print 'error'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Static Maps from Lat Long data in XLS file

2013-05-21 Thread Ken Bolton
On Tue, May 21, 2013 at 9:12 AM,  wrote:

> Hello,
>
> I'm new to Python, but I think it can solve my problem and I am looking
> for a someone to point me to tutorial or give me some tips here.
>

Hi! I am a first-time poster to python-list, but I think I can help you.


> I have an xls file that has about 1,000 latitude and longitude points. I
> want to do one of two things: 1) Save a static maps and street view image
> from the coordinates, or 2) create an html file with the map and street
> view image side by side.


If you save your xls file as a csv (comma-separated values), you can use
python's built-in csv module, documented here -
http://docs.python.org/2/library/csv.html, to read the file line by line.
Store the values and substitute the strings into a new list of URLs.


> I need the urls to look like this:
>
> Map with a pin in the centre:
>
> http://maps.googleapis.com/maps/api/staticmap?center=43.65162,-79.40571&zoom=16&size=600x600&markers=color:blue%7Clabel:S%7C43.65162,-79.40571&sensor=false
>
> Image:
>
> http://maps.googleapis.com/maps/api/streetview?location=43.65162,%20-79.40571&size=600x600&sensor=false


I was able to use curl to grab the images you linked. I believe you can use
urllib (or, better, requests - http://docs.python-requests.org/en/latest/)
to get and save the images.

hth.

best,
ken
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A computer programmer, web developer and network admin resume

2013-05-22 Thread Ken Bolton
On Wed, May 22, 2013 at 7:25 PM, Gregory Ewing
wrote:

> Tim Chase wrote:
>
>> So a pirate programmer walks into a bar with a bird on his shoulder.
>> The bird repeatedly squawks "pieces of nine! pieces of nine!".  The
>> bartender looks at him and asks "what's up with the bird?" to which
>> the pirate says "Arrr, he's got a parroty error."
>>
>
> No, he's just using half-open ranges.


That is the punchline for the one about the cowboy programmer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: avoid the redefinition of a function

2012-09-12 Thread Ken Seehart
Use lambda expressions to define some constraints:


gt = lambda x: lambda y: x>y
eq = lambda x: lambda y: x==y

constraints = [gt(2), eq(1)]
data = [3,1]

for i,c in enumerate(constraints):
print c(data[i])
   
   

On 9/12/2012 5:56 AM, Jabba Laci wrote:
> Hi,
>
> I have an installer script that contains lots of little functions. It
> has an interactive menu and the corresponding function is called. Over
> time it grew long and when I want to add a new function, I should give
> a unique name to that function. However, Python allows the
> redefinition of functions:
>
> #!/usr/bin/env python
>
> def step_1():
> print 1
>
> def step_1():
> print 2
>
> step_1()
>
> This will call the 2nd function. Now my functions are called step_ID
> (like step_27(), step_28(), etc.). How to avoid the danger of
> redefinition? Now, when I write a new function, I search for its name
> to see if it's unique but there must be a better way.
>
> Thanks,
>
> Laszlo
> P.S.: the script is here ( https://github.com/jabbalaci/jabbatron ) if
> you are interested. It's made for Ubuntu.




smime.p7s
Description: S/MIME Cryptographic Signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Boolean function on variable-length lists

2012-09-12 Thread Ken Seehart
Putting a few of peoples ideas together...


gt = lambda x: lambda y: x>y
eq = lambda x: lambda y: x==y

def constrain(c,d):
return all({f(x) for f, x in zip(c, d)})

constraints = [gt(2), eq(1)]
data0 = [1,1]
data1 = [3,1]
   
print constrain(constraints, data0)
print constrain(constraints, data1)




On 9/12/2012 6:37 AM, Jussi Piitulainen wrote:
> Libra writes:
>> On Wednesday, September 12, 2012 3:02:44 PM UTC+2, Jussi Piitulainen wrote:
>>  
>>> So you would associate each constraint with an index. You could
>>> maintain a list of constraints and apply it to the values as
>>> follows:
>> Yes, even though there could be more constraints for each value in
>> the list (at least 1 constraint for each value)
> Either you write more complex constraint functions, or you use more
> complex data structures to hold them.
>
>> cs = [ lambda x : x >= 1, lambda x : x <= 3, lambda x : x == 2,
>>> ...lambda x : x >= 3 ]
>>>
>> { f(x) for f, x in zip(cs, [1,2,3,4]) }
>> Just to understand, with f(x) you are defining a function f with
>> argument x, right? I didn't know it was possible to define functions
>> in this way. Is this a case of anonymous function?
> The value of each lambda expression is a function. f(x) is a function
> call, evaluated for each pair (f, x) from the list of pairs that the
> zip returns.
>
> { ... for ... in ... } creates a set of the values, no duplicates.
> [ ... for ... in ... ] creates a list of the values.
>
>>> {False, True}
>> Actually, I don't understand the output. Why it is both False and
>> True?
> It's a set containing False and True. The False comes from the f(x)
> where f = lambda x : x == 2, and x is 3. There is only one True
> because I requested a set of the values.




smime.p7s
Description: S/MIME Cryptographic Signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to correctly pass “pointer-to-pointer” into DLL via ctypes?

2012-10-27 Thread zlchen . ken
On Thursday, November 18, 2010 8:03:57 PM UTC+8, Grigory Petrov wrote:
> Hello.
> 
> I have a DLL that allocates memory and returns it. Function in DLL is like 
> this:
> 
> void Foo( unsigned char** ppMem, int* pSize )
> {
>   * pSize = 4;
>   * ppMem = malloc( * pSize );
>   for( int i = 0; i < * pSize; i ++ ) (* pMem)[ i ] = i;
> }
> 
> Also, i have a python code that access this function from my DLL:
> 
> from ctypes import *
> Foo = windll.mydll.Foo
> Foo.argtypes = [ POINTER( POINTER( c_ubyte ) ), POINTER( c_int ) ]
> mem = POINTER( c_ubyte )()
> size = c_int( 0 )
> Foo( byref( mem ), byref( size ) ]
> print size, mem[ 0 ], mem[ 1 ], mem[ 2 ], mem[ 3 ]
> 
> I'm expecting that print will show "4 0 1 2 3" but it shows "4 221 221
> 221 221" O_O. Any hints what i'm doing wrong?

I am wondering in Python how you free the memory which is allocated in your DLL 
?
Thanks 
-- 
http://mail.python.org/mailman/listinfo/python-list


ctypes free memory which is allocated in C DLL

2012-10-27 Thread zlchen . ken
Hi Guys,

I have a DLL which written in C language, one of the function is to allocate a 
structure, fill the members and then return the pointer of the structure.

After Python called this function, and done with the returned structure, I 
would like to free the returned structure. How can I achieve this ? Basically, 
I tried that I wrote a corresponding free interface in the DLL, it works, but 
calling the libc.free in Python doesn't work.

my_dll.return_structure_ptr.restypes = POINTER(Dummy)
res_ptr = my_dll.return_structure_ptr()
windll.msvcrt.free(res_ptr)  < doesn't work, memory violation 
my_dll.free_dummy_struture(res_ptr)  <== This works.

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


Re: ctypes free memory which is allocated in C DLL

2012-10-27 Thread Ken Chen
On Saturday, October 27, 2012 10:56:54 PM UTC+8, Chris Angelico wrote:
> On Sun, Oct 28, 2012 at 1:42 AM,   wrote:
> 
> > Hi Guys,
> 
> >
> 
> > I have a DLL which written in C language, one of the function is to 
> > allocate a structure, fill the members and then return the pointer of the 
> > structure.
> 
> >
> 
> > After Python called this function, and done with the returned structure, I 
> > would like to free the returned structure. How can I achieve this ? 
> > Basically, I tried that I wrote a corresponding free interface in the DLL, 
> > it works, but calling the libc.free in Python doesn't work.
> 
> 
> 
> As a general rule, you should always match your allocs and frees. Use
> 
> the same library to free the memory as was used to allocate it.
> 
> Nothing else is safe. If your DLL exposes an API that allocates
> 
> memory, your DLL should expose a corresponding API to free it. So what
> 
> you have is the best way :)
> 
> 
> 
> ChrisA

Thanks a lot, Chris!
Yes, I agree writing a corresponding API to free the memory is the best 
practice and best bet.
Sometimes, the third party API may not provide that.

After digging the Python manual again and again.
I finally figure out why windll.msvcrt.free is failing.

As the manual stated below, the DLL is using another version of msvcrt lib 
which is different than the builtin windll.msvcrt. After I explicitly load the 
msvcrt which built the DLL, things are getting function now.

"ctypes.util.find_msvcrt() 
Windows only: return the filename of the VC runtype library used by Python, and 
by the extension modules. If the name of the library cannot be determined, None 
is returned.

If you need to free memory, for example, allocated by an extension module with 
a call to the free(void *), it is important that you use the function in the 
same library that allocated the memory."

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


Re: ctypes free memory which is allocated in C DLL

2012-10-27 Thread zlchen . ken
On Sunday, October 28, 2012 6:26:28 AM UTC+8, Nobody wrote:
> On Sat, 27 Oct 2012 07:42:01 -0700, zlchen.ken wrote:
> 
> 
> 
> > I have a DLL which written in C language, one of the function is to
> 
> > allocate a structure, fill the members and then return the pointer of
> 
> > the structure. 
> 
> > 
> 
> > After Python called this function, and done with the returned structure,
> 
> > I would like to free the returned structure. How can I achieve this ?
> 
> > Basically, I tried that I wrote a corresponding free interface in the
> 
> > DLL, it works, but calling the libc.free in Python doesn't work.
> 
> > 
> 
> > my_dll.return_structure_ptr.restypes = POINTER(Dummy) res_ptr =
> 
> > my_dll.return_structure_ptr() windll.msvcrt.free(res_ptr)  < doesn't
> 
> > work, memory violation my_dll.free_dummy_struture(res_ptr)  <== This
> 
> > works.
> 
> 
> 
> On Windows, a process may have multiple versions of the MSVCRT DLL (which
> 
> provides malloc/free). If an executable or DLL is linked against multiple
> 
> DLLs, each DLL could be using a different version of MSVCRT.
> 
> 
> 
> Different versions of MSVCRT may have separate heaps, so anything which
> 
> is allocated with malloc() (or calloc() or realloc()) from a specific
> 
> version of MSVCRT must be passed to free() from the same version of MSVCRT.
> 
> windll.msvcrt refers to the version of MSVCRT against which the Python DLL
> 
> is linked, which isn't necessarily the version against which my_dll is
> 
> linked.
> 
> 
> 
> If a function in a DLL returns a pointer to memory which it allocated
> 
> with malloc(), that DLL must also provide a function which can be used to
> 
> free that memory. It can't leave it to the application (or higher-level
> 
> DLL) to call free(), because the application may not be using the same
> 
> version of MSVCRT as the DLL.

Thank you for the details.
This is really useful!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: something about performence

2011-06-20 Thread Ken Seehart
On 6/20/2011 7:59 PM, king6c...@gmail.com wrote:
> Hi,
> I have two large files,each has more than 2 lines,and each
> line consists of two fields,one is the id and the other a value,
> the ids are sorted.
>
> for example:
>
> file1
> (uin_a y)
> 1 1245
> 2 12333
> 3 324543
> 5 3464565
> 
>
>
> file2
> (uin_b gift)
> 1 34545
> 3 6436466
> 4 35345646
> 5 463626
> 
>
> I want to merge them and get a file,the lines of which consists of an
> id and the sum of the two values in file1 and file2。
> the codes are as below:
>
> uin_y=open('file1')
> uin_gift=open(file2')
>
> y_line=uin_y.next()
> gift_line=uin_gift.next()
>
> while 1:
> try:
> uin_a,y=[int(i) for i in y_line.split()]
> uin_b,gift=[int(i) for i in gift_line.split()]
> if uin_a==uin_b:
> score=y+gift
> print uin_a,score
> y_line=uin_y.next()
> gift_line=uin_gift.next()
> if uin_a print uin_a,y
> y_line=uin_y.next()
> if uin_a>uin_b:
> print uin_b,gift
> gift_line=uin_gift.next()
> except StopIteration:
> break
>
>
> the question is that those code runs 40+ minutes on a server(16
> core,32G mem),
> the time complexity is O(n),and there are not too much operations,
> I think it should be faster.So I want to ask which part costs so much.
> I tried the cProfile module but didn't get too much.
> I guess maybe it is the int() operation that cost so much,but I'm not
> sure
> and don't know how to solve this.
> Is there a way to avoid type convertion in Python such as scanf in C?
> Thanks for your help :)

Unfortunately python does not have a scanf equivalent AFAIK. Most use
cases for scanf can be handled by regular expressions, but that would
clearly useless for you, and just slow you down more since it does not
perform the int conversion for you.

Your code appears to have a bug: I would expect that the last entry will
be lost unless both files end with the same index value. Be sure to test
your code on a few short test files.

I recommend psyco to make the whole thing faster.

Regards,
Ken Seehart

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


Re: something about performence

2011-06-20 Thread Ken Seehart
On 6/20/2011 10:31 PM, Ken Seehart wrote:
> On 6/20/2011 7:59 PM, king6c...@gmail.com wrote:
>> Hi,
>> I have two large files,each has more than 2 lines,and each
>> line consists of two fields,one is the id and the other a value,
>> the ids are sorted.
>>
>> for example:
>>
>> file1
>> (uin_a y)
>> 1 1245
>> 2 12333
>> 3 324543
>> 5 3464565
>> 
>>
>>
>> file2
>> (uin_b gift)
>> 1 34545
>> 3 6436466
>> 4 35345646
>> 5 463626
>> 
>>
>> I want to merge them and get a file,the lines of which consists of an
>> id and the sum of the two values in file1 and file2。
>> the codes are as below:
>>
>> uin_y=open('file1')
>> uin_gift=open(file2')
>>
>> y_line=uin_y.next()
>> gift_line=uin_gift.next()
>>
>> while 1:
>> try:
>> uin_a,y=[int(i) for i in y_line.split()]
>> uin_b,gift=[int(i) for i in gift_line.split()]
>> if uin_a==uin_b:
>> score=y+gift
>> print uin_a,score
>> y_line=uin_y.next()
>> gift_line=uin_gift.next()
>> if uin_a> print uin_a,y
>> y_line=uin_y.next()
>> if uin_a>uin_b:
>> print uin_b,gift
>> gift_line=uin_gift.next()
>> except StopIteration:
>> break
>>
>>
>> the question is that those code runs 40+ minutes on a server(16
>> core,32G mem),
>> the time complexity is O(n),and there are not too much operations,
>> I think it should be faster.So I want to ask which part costs so much.
>> I tried the cProfile module but didn't get too much.
>> I guess maybe it is the int() operation that cost so much,but I'm not
>> sure
>> and don't know how to solve this.
>> Is there a way to avoid type convertion in Python such as scanf in C?
>> Thanks for your help :)
>
> Unfortunately python does not have a scanf equivalent AFAIK. Most use
> cases for scanf can be handled by regular expressions, but that would
> clearly useless for you, and just slow you down more since it does not
> perform the int conversion for you.
>
> Your code appears to have a bug: I would expect that the last entry
> will be lost unless both files end with the same index value. Be sure
> to test your code on a few short test files.
>
> I recommend psyco to make the whole thing faster.
>
> Regards,
> Ken Seehart
>
Another thought (a bit of extra work, but you might find it worthwhile
if psyco doesn't yield a sufficient boost):

Write a couple filter programs to convert to and from binary data (pairs
of 32 or 64 bit integers depending on your requirements).

Modify your program to use the subprocess module to open two instances
of the binary conversion process with the two input files. Then pipe the
output of that program into the binary to text filter.

This might turn out to be faster since each process would make use of a
core. Also it gives you other options, such as keeping your data in
binary form for processing, and converting to text only as needed.

Ken Seehart

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


Re: something about performence

2011-06-21 Thread Ken Seehart
On 6/20/2011 11:56 PM, king6c...@gmail.com wrote:
> Thanks for your reply,Ken :)
> I found the two files ends with the same id……so I am lazy^-^
> I tried psyco,and unfortunately it costs nearly the same time as before.
> Is it true that we can only get str from files in Python?
>
Nope^_* . There are many applications such as image processing that
involve working with binary data.

(^_* well, technically yes actually: read() does in fact return str, but
the str can contain binary data)

But in order to do this, you need to use any of several modules that
allow python to operate on flat data.

Two standard modules exist for this purpose: *array *and *struct*. In
addition there are others such as *numpy *(for mathematical
applications) and *ctypes *(for interoperability between python and C/C++).

For your application, the *struct *module is sufficient.

>>> fout = open('junk.dat', 'wb') # open for writing binary
>>> fout.write(struct.pack('LL', 123,234))
>>> fout.write(struct.pack('LL', 123,234))
>>> fout.write(struct.pack('LL', 3,4))
>>> fout.close()

>>> fin = open('junk.dat', 'rb') # open for reading binary
>>> print struct.unpack('LL', fin.read(8))
(123, 234)
>>> print struct.unpack('LL', fin.read(8))
(123, 234)
>>> print struct.unpack('LL', fin.read(8))
(3, 4)
>>> print struct.unpack('LL', fin.read(8)) # raises struct.error at end
of file (because 0 bytes were read)
Traceback (most recent call last):
File "", line 1, in 
struct.error: unpack requires a string argument of length 8
>>>


>
> 在 2011年6月21日 下午1:50,Ken Seehart  <mailto:k...@seehart.com>>写 道:
>
> On 6/20/2011 10:31 PM, Ken Seehart wrote:
>> On 6/20/2011 7:59 PM, king6c...@gmail.com
>> <mailto:king6c...@gmail.com> wrote:
>>> Hi,
>>> I have two large files,each has more than 2 lines,and
>>> each line consists of two fields,one is the id and the other a
>>> value,
>>> the ids are sorted.
>>>
>>> for example:
>>>
>>> file1
>>> (uin_a y)
>>> 1 1245
>>> 2 12333
>>> 3 324543
>>> 5 3464565
>>> 
>>>
>>>
>>> file2
>>> (uin_b gift)
>>> 1 34545
>>> 3 6436466
>>> 4 35345646
>>> 5 463626
>>> 
>>>
>>> I want to merge them and get a file,the lines of which consists
>>> of an id and the sum of the two values in file1 and file2。
>>> the codes are as below:
>>>
>>> uin_y=open('file1')
>>> uin_gift=open(file2')
>>>
>>> y_line=uin_y.next()
>>> gift_line=uin_gift.next()
>>>
>>> while 1:
>>> try:
>>> uin_a,y=[int(i) for i in y_line.split()]
>>> uin_b,gift=[int(i) for i in gift_line.split()]
>>> if uin_a==uin_b:
>>> score=y+gift
>>> print uin_a,score
>>> y_line=uin_y.next()
>>> gift_line=uin_gift.next()
>>> if uin_a>> print uin_a,y
>>> y_line=uin_y.next()
>>> if uin_a>uin_b:
>>> print uin_b,gift
>>> gift_line=uin_gift.next()
>>> except StopIteration:
>>> break
>>>
>>>
>>> the question is that those code runs 40+ minutes on a server(16
>>> core,32G mem),
>>> the time complexity is O(n),and there are not too much operations,
>>> I think it should be faster.So I want to ask which part costs so
>>> much.
>>> I tried the cProfile module but didn't get too much.
>>> I guess maybe it is the int() operation that cost so much,but
>>> I'm not sure
>>> and don't know how to solve this.
>>> Is there a way to avoid type convertion in Python such as scanf
>>> in C?
>>> Thanks for your help :)
>>
>> Unfortunately python does not have a scanf equivalent AFAIK. Most
>> use cases for scanf can be handled by regular expressions, but
>> that would clearly useless for you, and just slow you down more
>> since it does not perform the int conversion for you.
>>
>> Your code appears to have a bug: I would expect that the last
>> entry will be lost unless both files end with the same index
>> value. Be sure to test your code on a few short test files.
>>
>> I re

Re: LDAP: How get all users belongs to a group.

2011-06-23 Thread Ken Watford
On Thu, Jun 23, 2011 at 9:14 AM, sajuptpm  wrote:
> Hi,
> How get all users belongs to a group using python ldap module.

Depends on what you mean by "users" and "group", what information you
already have, and what information you want to get. I'll assume you
mean posix accounts and groups, and that you already know how to
connect to the LDAP server.

If you already know the distinguished name of the group, you can get a
list of the member names like so (ignoring error handling):

dn, entry = connection.search_s(group_dn, ldap.SCOPE_BASE)[0]
member_list = entry['memberUid']

That will only get you the usernames. If you need to get the user's
entry (or don't know the group_dn above), then you'll have to do a bit
more searching.

To find a user's entry given their uid:

results = connection.search_s(base_dn, ldap.SCOPE_SUBTREE, "(uid=*)")
for dn, entry in results:
 if uid in entry['uid']:
 # this is your guy. return, or break, or whatever

The "(uid=*)" filter just means to only find entries that have user id
fields. If you wanted to be more specific about it, you could limit it
to only posixAccount objects with "(objectClass=posixAccount)". This
would probably be necessary if you wanted to search for groups (via
"(objectClass=posixGroup)" ), since those don't have a special field
for their name - they usually just use the cn (common name) field for
that. A slightly more complex filter could be written to avoid the
python loop.

If your groups are not posixGroup objects but instead groupOfNames,
then the appropriate attribute is "member" rather than "memberUid",
and the values there are user DNs instead of uids. In that case, if
you need the uid you'll have to look up those users and pull it out.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: perceptron feed forward neural networks in python

2011-07-11 Thread Ken Watford
On Mon, Jul 11, 2011 at 2:31 PM, Igor Begić  wrote:
> Hi,
> I,m new to Python and i want to study and write programs about perceptron
> feed forward neural networks in python. Does anyone have a good book or link
> for this?

Try Stephen Marsland's "Machine Learning: An Algorithmic Perspective".
All example code is done in Python, and there's a chapter on
multilayer perceptrons.

The code for the book is available online here:
http://www-ist.massey.ac.nz/smarsland/MLbook.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wondering in the Python Forrest

2011-07-30 Thread Ken Watford
On Sat, Jul 30, 2011 at 7:13 AM, ray  wrote:
> I found that structured data could be presented in Python using a module in
> wxPython.
>
> Where am I?  I do not know the relationships between the Pythons.  I
> feel that I am missing something.  I started with Python as it has so
> much functionality and a huge user group of very helpful individuals
> and sites.  Now that I have delved deeper, it seems I need different
> Pythons.

I think the name has caused you some confusion. wxPython is not a
different Python, it's a package for Python that displays GUI
components using the C++ "wxWidgets" library.

While there are other Pythons out there, for scientific work you
should have everything you need in the one you've got. You may have to
install an additional package now and then, but that's it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replace all references to one object with references to other

2011-08-05 Thread Ken Watford
On Fri, Aug 5, 2011 at 3:37 PM, Jack Bates  wrote:
> I have two objects, and I want to replace all references to the first
> object - everywhere - with references to the second object. What can I
> try?

If using PyPy instead of CPython is an option, the "thunk" object
space's "become" function can apparently do this:
http://doc.pypy.org/en/latest/objspace-proxies.html#the-thunk-object-space

In CPython, this might be a tad difficult. At the C level, a reference
to a python object is just a pointer to it. You could iterate through
the entire address space looking for values that equal a particular
pointer, but changing them would be dangerous, since memory isn't
labeled by type - you can't tell if the memory is a pointer to your
object or an important part of some other data structure.

If you could narrow down what you want to accomplish, this might be
easier. For instance, if all you need is to replace module-level
references to the object, that can be done.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacement for the shelve module?

2011-08-19 Thread Ken Watford
On Fri, Aug 19, 2011 at 11:31 AM, Forafo San  wrote:
> Folks,
> What might be a good replacement for the shelve module, but one that
> can handle a few gigs of data. I'm doing some calculations on daily
> stock prices and the result is a nested list like:

For what you're doing, I would give PyTables a try.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dpkg

2011-08-26 Thread Ken Watford
On Fri, Aug 26, 2011 at 10:43 AM, Verde Denim  wrote:
> Looking for this with find / -name libclntsh.so.11.1 -print produces
> /usr/lib/oracle/11.2/client64/lib/libclntsh.so.11.1
>
> I'm confused as to why Python doesn't see it...

Try running "sudo ldconfig".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyCon

2011-03-11 Thread Ken Seehart

On 3/11/2011 7:45 AM, Rita wrote:

http://us.pycon.org/2010/ http://us.pycon.org/2009/

Try the wayback machine:

http://replay.waybackmachine.org/20100701160843/http://us.pycon.org/2010/about/
--
http://mail.python.org/mailman/listinfo/python-list


Regex in if statement.

2011-03-20 Thread Ken D'Ambrosio
Hey, all -- I know how to match and return stuff from a regex, but I'd
like to do an if, something like (from Perl, sorry):

if (/MatchTextHere/){DoSomething();}

How do I accomplish this in Python?

Thanks!

-Ken




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


Dump interpreter history?

2011-03-25 Thread Ken D'Ambrosio
Hey, all.  A co-worker asked me a question, and I've got no idea how (or
if) it can be done.  Bottom line: he'd like to save off the text from an
interpreter session, his thinking being that you've already tried to get
what you want, and now you just need to gussy it up in an editor.

Can this be done?

Thanks!

-Ken




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


Re: Function __defaults__

2011-04-24 Thread Ken Seehart

On 4/24/2011 2:58 AM, Steven D'Aprano wrote:

Consider this in Python 3.1:



def f(a=42):

... return a
...

f()

42

f.__defaults__ = (23,)
f()

23


Is this an accident of implementation, or can I trust that changing
function defaults in this fashion is guaranteed to work?


This is documented in python 3, so I would expect it to be stable (until 
python 4, that is)

http://docs.python.org/py3k/whatsnew/3.0.html#operators-and-special-methods
http://docs.python.org/py3k/library/inspect.html#types-and-members

The f.__defaults__ attribute was previously known as f.func_defaults (in 
python 2.x), which has been around, documented and stable for quite a while.


So it's probably just as safe as any other monkey patching technique. :)

Best of luck,
Ken

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


Re: Function __defaults__

2011-04-24 Thread Ken Seehart
Good point, Benjamin.  I didn't think of testing on Jython before 
answering.  For practical purposes it's a really good idea to test 
obscure features against all potential target platforms.


In this case, I would argue that**Benjamin's test demonstrates a bug in 
Jython.


One could counter by pointing out that the documentation does not 
specify that the __defaults__ attribute is writable.  However, in that 
case, Jython should explicitly make that attribute read only (as well as 
any other magic attributes where modification is silently ignored).  
That way, at least it would raise an exception in Jython.


Therefore, I would also suggest that the behavior of writable magic 
attributes should be added to the documentation and the python test suite.


On the other hand, if for some reason it is decided that support for 
such functionality is not desired in Python, then write access to such 
attributes should be deprecated and later removed.  However, I happen to 
like the ability to do this kind of thing, so I would vote for 
specifying the current CPython 3 behavior (as demonstrated in Steven's 
initial post) in the Python documentation.


On 4/24/2011 10:02 AM, Benjamin Kaplan wrote:

On Sun, Apr 24, 2011 at 5:58 AM, Steven D'Aprano
  wrote:

Consider this in Python 3.1:



def f(a=42):

... return a
...

f()

42

f.__defaults__ = (23,)
f()

23


Is this an accident of implementation, or can I trust that changing
function defaults in this fashion is guaranteed to work?



--
Steven

Jython 2.5.1 (Release_2_5_1:6813, Sep 26 2009, 13:47:54)
[Java HotSpot(TM) 64-Bit Server VM (Apple Inc.)] on java1.6.0_24
Type "help", "copyright", "credits" or "license" for more information.

def f(a=42) :

...return a
...

f()

42

f.__defaults__ = (23,)
f()

42

I'm going to go with implementation detail.


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



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


Re: Function __defaults__

2011-04-24 Thread Ken Seehart

Oops, I must correct myself.  Please ignore my previous post.

As Daniel points out, Writable is specified in the Python 3 
documentation.  Apparently I was reading the documentation with only my 
right eye open, and the Writable tag fell on my blind spot.
I concur that this unambiguously implies that the attribute should work 
as advertised after being written.


This is not a bug in Jython.  As Daniel points out the attribute was 
renamed from func_defaults to __defaults__ in python 3.


Jython 2.5.2 (Release_2_5_2:7206, Mar 2 2011, 23:12:06)
[Java HotSpot(TM) Client VM (Sun Microsystems Inc.)] on java1.6.0_24
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo(x=4):
...   print x
...
>>> foo()
4
>>> foo.func_defaults
(4,)
>>> foo.func_defaults = (3,)
>>> foo()
3
>>>

So it works correctly in Jython 2.x.

Conclusion: Not an implementation detail, and safe to use.

Ken

On 4/24/2011 10:18 AM, Daniel Kluev wrote:

http://docs.python.org/dev/reference/datamodel.html
Callable types
...
Special attributes:
...
__defaults__A tuple containing default argument values for those
arguments that have defaults, or None if no arguments have a default
value   Writable

I don't see any 'implementation detail' mark there, and 'Writable'
IMHO means it can be used.

On Mon, Apr 25, 2011 at 4:02 AM, Benjamin Kaplan
  wrote:

Jython 2.5.1 (Release_2_5_1:6813, Sep 26 2009, 13:47:54)

In 2.x it was func_defaults (http://docs.python.org/reference/datamodel.html)
__defaults__ is 3.x feature



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


Re: Function __defaults__

2011-04-24 Thread Ken Seehart

Gotta love that email latency. :-D
Ken

On 4/24/2011 2:47 PM, Daniel Kluev wrote:

On Mon, Apr 25, 2011 at 8:21 AM, Ken Seehart  wrote:

Good point, Benjamin.  I didn't think of testing on Jython before
answering.  For practical purposes it's a really good idea to test obscure
features against all potential target platforms.

In this case, I would argue that Benjamin's test demonstrates a bug in
Jython.

It doesn't. __defaults__ was added in 3.x (and it is documented).
Prior to that, in 2.x, there was func_defaults.

Jython is not in 3.x yet, so you should not expect 3.x features there.
As for func_defaults, its there and supported as documented:

Jython 2.5.1+ (Release_2_5_1:exported, Mar 21 2010, 01:00:17)
[Java HotSpot(TM) Server VM (Sun Microsystems Inc.)] on java1.6.0_22
Type "help", "copyright", "credits" or "license" for more information.

def test(a=123):

... return a
...

test()

123

test.func_defaults

(123,)

test.func_defaults = (456,)
test()

456



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


Re: Function __defaults__

2011-04-25 Thread Ken Seehart

On 4/25/2011 4:59 AM, Colin J. Williams wrote:

On 24-Apr-11 13:07 PM, Ken Seehart wrote:

On 4/24/2011 2:58 AM, Steven D'Aprano wrote:

Consider this in Python 3.1:



def f(a=42):

... return a
...

f()

42

f.__defaults__ = (23,)
f()

23


Is this an accident of implementation, or can I trust that changing
function defaults in this fashion is guaranteed to work?


This is documented in python 3, so I would expect it to be stable (until
python 4, that is)
http://docs.python.org/py3k/whatsnew/3.0.html#operators-and-special-methods 


http://docs.python.org/py3k/library/inspect.html#types-and-members

The f.__defaults__ attribute was previously known as f.func_defaults (in
python 2.x), which has been around, documented and stable for quite a
while.

So it's probably just as safe as any other monkey patching technique. :)

Best of luck,
Ken



Wouldn't it make more sense to return a dictionary instead of a tuple?

Colin W.



I assume you mean making the value of f.__defaults__ a dictionary 
instead of a tuple.


A dictionary would be slower to process since it would have to iterate 
the dictionary keys and assign arguments by name.
Since argument defaults can only be applied to the rightmost contiguous 
sequence of zero or more parameters (excluding *args,**kwargs),  a tuple 
is sufficient to cover all cases, so a dictionary would provide no 
advantage.
Also, a dictionary would produce an unnecessary error case (if a key in 
the dictionary is not the name of an argument).


Good question though.

Cheers,
Ken

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


Re: I think I found a mistake in the official language reference documentation -- or I am missing somethig???

2011-04-27 Thread Ken Watford
On Wed, Apr 27, 2011 at 4:02 PM, Igor Soares  wrote:
> Reading the section "6.11. The import statement"
> http://docs.python.org/py3k/reference/simple_stmts.html#the-import-statement
>
> I found:
> """
> Import statements are executed in two steps: (1) find a module, and
> initialize it if necessary; (2) define a name or names in the local
> namespace (of the scope where the import statement occurs).
> (...)
> The first form (without from) repeats these steps for each identifier
> in the list. The form with from performs step (1) once, and then
> performs step (2) repeatedly.
> """
> In the last sentence, isn't it the opposite?
> With the "from" form it would find/initialize all the modules and
> define just the name after "from".
> Or am I missing something?

Judging only by what you've quoted, the forms would be:

1) import os, sys, glob
2) from os.path import exists, split, join

In the first form, one or more modules come after the 'import'. In the
second form, a single module comes after the 'from', and then multiple
names from within that module come after the 'import'. Looks fine to
me.
-- 
http://mail.python.org/mailman/listinfo/python-list


bug in ''.format()

2017-11-02 Thread Ken Kundert
I just encountered this:

>>> '{:0s}'.format('hello')
Traceback (most recent call last):
  File "", line 1, in 
ValueError: '=' alignment not allowed in string format specifier

The exception goes away if I do not specify a width of the string:

>>> '{:s}'.format('hello')
'hello'

My reading of the documentation says I should be able to specify a width
when interpolating a string.

I have tried this in 2.7.13, 3.6.1 and 3.6.2 and it fails in all of them.

Is this a bug or am I confused?
-Ken
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: bug in ''.format()

2017-11-02 Thread Ken Kundert
Sure enough. There is it, right there in the documentation. I did not
read far enough.

My bad.

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


exec and traceback

2018-01-22 Thread ken . py



I'm using exec() to run a (multi-line) string of python code. If an  
exception occurs, I get a traceback containing a stack frame for the  
string. I've labeled the code object with a "file name" so I can  
identify it easily, and when I debug, I find that I can interact with  
the context of that stack frame, which is pretty handy.


What I would like to also be able to do is make the code string  
visible to the debugger so I can look at and step through the code in  
the string as if it were from a python file.


Lest this topic forks into a security discussion, I'll just add that  
for my purposes the data source is trusted. If you really want to talk  
about the security of using exec and eval, fine, but start another  
thread (BTW, I've written a simple secure eval())


Thanks in advance,
Ken



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


Re: Mailing list activity low

2021-10-13 Thread Ken Peng
Maybe bounced by your mail provider. Try changing to another ESP such as
gmail.

On Wed, Oct 13, 2021 at 1:45 AM Antoon Pardon  wrote:

> Have I missed something and has the maillinglist been moved. Activity is
> very low here, about one message every five days.
>
> Antoon Pardon.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


f-string anomaly

2018-05-13 Thread Ken Kundert
I am seeing an unexpected difference between the behavior of the string
format method and f-strings.

Here is an example:

import sys, os
from inform import error, os_error

class mydict(dict):
def __format__(self, template):
print('Template:', template)
return ', '.join(template.format(v, k=k, v=v) for k, v in
self.items())


d = mydict(bob='239-8402', ted='371-8567', carol='891-5810',
alice='552-2219')

print('Using format():')
print('Email: {0:{{k}}: {{v}}}'.format(d))
print()
print('Using f-string:')
print(f'Email: {d:{{k}} {{v}}}')
print()
print('Using f-string:')
print(f'Email: {d:{{k}} {{v}}}', k=6, v=9)


It generates the following response:

Using format():
Template: {k}: {v}
Email: bob: 239-8402, ted: 371-8567, carol: 891-5810, alice: 552-2219

Using f-string:
Traceback (most recent call last):
File "tryit", line 18, in 
print(f'Email: {d:{{k}} {{v}}}')
NameError: name 'k' is not defined

Essentially I am using a format string as the template that indicates
how to format each member of a dictionary, {{k}} should interpolate the
key and {{v}} interpolates the value.  This format string is embedded
inside another format string, so the braces are doubled up so that they
will be ignored by the outer format string.

This idea seems to work okay when using the format() method. You can see
I added a print statement inside __format__ that shows that the method
is being called.

However, trying the same idea with f-strings results in a NameError.  It
appears that the escaping does not work when used within the template.
It appears the error occurs before __format__ is called (there is no
output from the print function).

Does anybody know why the format() method would work in this case but
the f-string would not?

Is this a bug in f-strings?

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


f-string anomaly

2018-05-13 Thread Ken Kundert
I am seeing an unexpected difference between the behavior of the string
format method and f-strings in Python3.6.

Here is an example:

import sys, os
from inform import error, os_error

class mydict(dict):
def __format__(self, template):
print('Template:', template)
return ', '.join(template.format(v, k=k, v=v) for k, v in
self.items())


d = mydict(bob='239-8402', ted='371-8567', carol='891-5810',
alice='552-2219')

print('Using format():')
print('Email: {0:{{k}}: {{v}}}'.format(d))
print()
print('Using f-string:')
print(f'Email: {d:{{k}} {{v}}}')
print()
print('Using f-string:')
print(f'Email: {d:{{k}} {{v}}}', k=6, v=9)


It generates the following response:

Using format():
Template: {k}: {v}
Email: bob: 239-8402, ted: 371-8567, carol: 891-5810, alice: 552-2219

Using f-string:
Traceback (most recent call last):
File "tryit", line 18, in 
print(f'Email: {d:{{k}} {{v}}}')
NameError: name 'k' is not defined

Essentially I am using a format string as the template that indicates
how to format each member of a dictionary, {{k}} should interpolate the
key and {{v}} interpolates the value.  This format string is embedded
inside another format string, so the braces are doubled up so that they
will be ignored by the outer format string.

This idea seems to work okay when using the format() method. You can see
I added a print statement inside __format__ that shows that the method
is being called.

However, trying the same idea with f-strings results in a NameError.  It
appears that the escaping does not work when used within the template.
It appears the error occurs before __format__ is called (there is no
output from the print function).

Does anybody know why the format() method would work in this case but
the f-string would not?

Is this a but in f-strings?

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


Re: f-string anomaly

2018-05-13 Thread Ken Kundert
Terry,
Thanks for your response.

I apologize about the double posting. I am well aware how doing so is
bad form. My double posting was unintentional; it occurred when my news
reader misbehaved.

What I did in my code was to put double braces inside the format_spec,
which the syntax specification in the f-string documentation does not
allow, and so it should be a syntax error. But it does not generate a
syntax error. So the question becomes, how does it interpret {{k}} and
{{v}} in the format spec. I was expecting it to treat the double braces
as escaped braces, and that is what the format method does. And by the
last sentence in the following paragraph, it seems like f-strings should
as well.

Top-level format specifiers may include nested replacement fields.
These nested fields may include their own conversion fields and
format specifiers, but may not include more deeply-nested
replacement fields. The format specifier mini-language is the same
as that used by the string .format() method.

> All names in the expression are resolved in the local namespace of the
> f string.  There are other differences.  Nesting can only be one level
> deep.

I tried adding k and v to the local namespace:

...
k = 6
v = 9
print(f'Email: {d:{{k}} {{v}}}')

I still got:

NameError: name 'k' is not defined

I don't know where it is looking for k, but it is not in the local
namespace.

And I don't think the comment on nesting applies. The format string does
not include nested references. Rather "{{k}} {{v}}" is meant to be
treated as a literal string that should de-escaped and passed to the
__format__ method, but no values should be interpolated. What the
__format__ method does with the format spec is not in anyway restricted
by the f string as long as __format__ returns a string.

The comment that the mini-language is the same between the format method
and the f string seems compelling to me. I think this is a bug. I think
the f-string syntax should be updated to explicitly allow escaped braces
in the format_spec, and the implementation of f-strings should be
updated to be consistent with the syntax specification, and with the
format method.

-Ken



On 05/13/2018 07:08 PM, Terry Reedy wrote:
> On 5/13/2018 3:22 PM, Ken Kundert wrote:
> 
> Please do not double post.
> 
>> I am seeing an unexpected difference between the behavior of the string
>> format method and f-strings.
> 
> Read
> https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals
> carefully.
> 
>> Here is an example:
>>
>>  import sys, os
>>  from inform import error, os_error
>>
>>  class mydict(dict):
>>  def __format__(self, template):
>>  print('Template:', template)
>>  return ', '.join(template.format(v, k=k, v=v) for k, v in
>> self.items())
>>
>>
>>  d = mydict(bob='239-8402', ted='371-8567', carol='891-5810',
>> alice='552-2219')
>>
>>  print('Using format():')
>>  print('Email: {0:{{k}}: {{v}}}'.format(d))
>>  print()
>>  print('Using f-string:')
>>  print(f'Email: {d:{{k}} {{v}}}')
>>  print()
>>  print('Using f-string:')
>>  print(f'Email: {d:{{k}} {{v}}}', k=6, v=9)
>>
>>
>> It generates the following response:
>>
>>  Using format():
>>  Template: {k}: {v}
>>  Email: bob: 239-8402, ted: 371-8567, carol: 891-5810, alice:
>> 552-2219
>>
>>  Using f-string:
>>  Traceback (most recent call last):
>>  File "tryit", line 18, in 
>>  print(f'Email: {d:{{k}} {{v}}}')
>>  NameError: name 'k' is not defined
> 
> This is what I expected.
> 
>> Essentially I am using a format string as the template that indicates
>> how to format each member of a dictionary, {{k}} should interpolate the
>> key and {{v}} interpolates the value.  This format string is embedded
>> inside another format string, so the braces are doubled up so that they
>> will be ignored by the outer format string.
> 
> "The parts of the string outside curly braces are treated literally,
> except that any doubled curly braces '{{' or '}}' are replaced with the
> corresponding single curly brace. " note 'outside'
> 
>> This idea seems to work okay when using the format() method. You can see
>> I added a print statement inside __format__ that shows that the method
>> is being called.
>>
>> However, trying the same idea with f-strings results in a NameError.  It
>> appears that the escaping does not work when used within the template.
>> It appears the error occurs before __format__ is called (there is no
>> output from the print function).
>>
>> Does anybody know why the format() method would work in this case but
>> the f-string would not?
> 
> All names in the expression are resolved in the local namespace of the f
> string.  There are other differences.  Nesting can only be one level deep.
> 
>> Is this a bug in f-strings?
> 
> Not to me.
> 
> 

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


Re: f-string anomaly

2018-05-14 Thread Ken Kundert
Lele,
I'm afraid I was unclear. The ... in the code snippet was intended
to imply that these lines were appended to the end of the original code,
where d was defined.

-Ken

On 05/14/2018 12:30 AM, Lele Gaifax wrote:
> Ken Kundert  writes:
> 
>> I tried adding k and v to the local namespace:
>>
>> ...
>> k = 6
>> v = 9
>> print(f'Email: {d:{{k}} {{v}}}')
>>
>> I still got:
>>
>> NameError: name 'k' is not defined
> 
> This is not what I get:
> 
> Python 3.6.5 (default, May 11 2018, 13:30:17) 
> [GCC 7.3.0] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>> k=1
> >>> v=2
> >>> print(f'this is {{k}} and {{v}}')
> this is {k} and {v}
> >>> print(f'this is {k} and {v}')
> this is 1 and 2
> >>> print(f'Email: {d:{{k}} {{v}}}')
> Traceback (most recent call last):
>   File "", line 1, in 
> NameError: name 'd' is not defined
> 
> ciao, lele.
> 

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


Re: f-string anomaly

2018-05-14 Thread Ken Kundert
Lele,
I am using Python3.6. d has to be an object of mydict.

Here is the code that exhibits the problem:

 import sys, os
 from inform import error, os_error

 class mydict(dict):
 def __format__(self, template):
 print('Template:', template)
 return ', '.join(template.format(v, k=k, v=v) for k, v in
self.items())


 d = mydict(bob='239-8402', ted='371-8567', carol='891-5810',
alice='552-2219')

 print('Using format():')
 print('Email: {0:{{k}}: {{v}}}'.format(d))
 print()
 print('Using f-string:')
 print(f'Email: {d:{{k}} {{v}}}')
 print()
 print('Using f-string:')
 k=6
 v=9
 print(f'Email: {d:{{k}} {{v}}}')

The result is:

NameError: name 'k' is not defined

-Ken





On 05/14/2018 12:24 PM, Lele Gaifax wrote:
> Ken Kundert  writes:
> 
>> Lele,
>> I'm afraid I was unclear. The ... in the code snippet was intended
>> to imply that these lines were appended to the end of the original code,
>> where d was defined.
> 
> Ok, but then I get a different behaviour:
> 
> Python 3.6.5 (default, May 11 2018, 13:30:17) 
> [GCC 7.3.0] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>> k=1
> >>> v=2
> >>> d=3
> >>> print(f'Email: {d:{{k}} {{v}}}')
> Traceback (most recent call last):
>   File "", line 1, in 
> ValueError: Invalid format specifier
> 
> Which Python version are you using?
> 
> ciao, lele.
> 

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


PEP proposal: sequence expansion support for yield statement: yield *

2016-04-20 Thread Ken Seehart
Currently the common pattern for yielding the elements in a sequence is as 
follows:

  for x in sequence: yield x

I propose the following replacement (the result would be identical):

  yield *sequence

The semantics are somewhat different from argument expansion (from which the 
syntax is borrowed), but intuitive: yield all of the elements of a sequence (as 
opposed to yield the sequence as a single item). This doesn't appear to have 
any syntactical collisions, as it is currently a syntax error.

Motivation: More compact notation, and the compiler can produce more efficient 
bytecode than the former representation (the loop overhead is omitted). This 
pattern is very common in recursive generators, so a compact notation would be 
nice.

Also, there is precedent: the proposed notation is implemented in javascript 
with identical semantics (though in javascript, the conventional spacing is 
different: yield* sequence ).

Examples:
  yield *(1,2,3)
... instead of :
  yield 1; yield 2; yield 3
... or:
  for x in (1,2,3): yield x


  yield *chain(seq1, seq2)
... instead of :
  for x in chain(seq1, seq2) yield x

~ Ken Seehart

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


Python 3.73 cannot install py3exiv2

2019-05-01 Thread Ken Martell
I’m a retired aerospace engineer. I’m a Windows 10 user & have zero experience 
with Python. My goal is to learn, get this working & run lens distortion 
correction routines using Python. I’ve tried or many hours and read as much as 
I can but cannot get the py3exiv2 module to install. Other needed modules 
installed fine. It appears the Python version 2 of evix2 is needed as a 
dependent for the version 3 but neither pip or pip3 will install old or new. 
Sorry for taking your time but I’m a newbie just trying to help my fellow 
photographers correct  lens distortion problems in post-processing as well as 
my own.

Any help much appreciated!

Thank you
Ken Martell

This is the error I get :

D:\>pip3 install py3exiv2
Collecting py3exiv2
  Using cached 
https://files.pythonhosted.org/packages/eb/c4/675823a2c23d8f138e7dc2b7574d09f26959f641d0b59c3ec7faa65764e5/py3exiv2-0.7.0.tar.gz
Installing collected packages: py3exiv2
  Running setup.py install for py3exiv2 ... error
    Complete output from command d:\apps\python37\python.exe -u -c "import 
setuptools, 
tokenize;__file__='C:\\Users\\Ken\\AppData\\Local\\Temp\\pip-install-swqqye4_\\py3exiv2\\setup.py';f=getattr(tokenize,
 'open', open)(__file__);code=f.read().replace('\r\n', 
'\n');f.close();exec(compile(code, __file__, 'exec'))" install --record 
C:\Users\Ken\AppData\Local\Temp\pip-record-4ki8wmrk\install-record.txt 
--single-version-externally-managed --compile:
    FIND: Invalid switch
    FIND: Invalid switch
    FIND: Invalid switch
    running install
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.7
    creating build\lib.win-amd64-3.7\pyexiv2
    copying src\pyexiv2\exif.py -> build\lib.win-amd64-3.7\pyexiv2
    copying src\pyexiv2\iptc.py -> build\lib.win-amd64-3.7\pyexiv2
    copying src\pyexiv2\metadata.py -> build\lib.win-amd64-3.7\pyexiv2
    copying src\pyexiv2\preview.py -> build\lib.win-amd64-3.7\pyexiv2
    copying src\pyexiv2\utils.py -> build\lib.win-amd64-3.7\pyexiv2
    copying src\pyexiv2\xmp.py -> build\lib.win-amd64-3.7\pyexiv2
    copying src\pyexiv2\__init__.py -> build\lib.win-amd64-3.7\pyexiv2
    running build_ext
    building 'libexiv2python' extension
    creating build\temp.win-amd64-3.7
    creating build\temp.win-amd64-3.7\Release
    creating build\temp.win-amd64-3.7\Release\src
    C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe 
/c /nologo /Ox /W3 /GL /DNDEBUG /MD -Id:\apps\python37\include 
-Id:\apps\python37\include "-IC:\Program Files (x86)\Microsoft Visual Studio 
14.0\VC\INCLUDE" "-IC:\Program Files (x86)\Windows 
Kits\10\include\10.0.10240.0\ucrt" "-IC:\Program Files (x86)\Windows 
Kits\8.1\include\shared" "-IC:\Program Files (x86)\Windows Kits\8.1\include\um" 
"-IC:\Program Files (x86)\Windows Kits\8.1\include\winrt" /EHsc 
/Tpsrc/exiv2wrapper.cpp 
/Fobuild\temp.win-amd64-3.7\Release\src/exiv2wrapper.obj -g
    cl : Command line warning D9002 : ignoring unknown option '-g'
    exiv2wrapper.cpp
    
c:\users\ken\appdata\local\temp\pip-install-swqqye4_\py3exiv2\src\exiv2wrapper.hpp(32):
 fatal error C1083: Cannot open include file: 'exiv2/image.hpp': No such file 
or directory
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 
14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2

    
Command "d:\apps\python37\python.exe -u -c "import setuptools, 
tokenize;__file__='C:\\Users\\Ken\\AppData\\Local\\Temp\\pip-install-swqqye4_\\py3exiv2\\setup.py';f=getattr(tokenize,
 'open', open)(__file__);code=f.read().replace('\r\n', 
'\n');f.close();exec(compile(code, __file__, 'exec'))" install --record 
C:\Users\Ken\AppData\Local\Temp\pip-record-4ki8wmrk\install-record.txt 
--single-version-externally-managed --compile" failed with error code 1 in 
C:\Users\Ken\AppData\Local\Temp\pip-install-swqqye4_\py3exiv2\
You are using pip version 19.0.3, however version 19.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' 
command.


Sent from Mail for Windows 10

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


Re: PyQT installation

2005-01-01 Thread Ken Godee
John J. Lee wrote:
[EMAIL PROTECTED] (Alex Martelli) writes:
[...]
Basically: if you want it on Windows for free, forget Qt

Correct.
I believe the book "C++ GUI programming Qt3" comes
with a windows Qt gpl 3.x version. Just have to buy
the book. No PyQt version to match thou.
Blackadder from the Kompany, while not free, is still
a pretty good deal. Like < $100 for personal and around
$350 for commercial version. Include current windows/linux
versions of (Qt)PyQt along with converted Qt C++ to PyQt docs.
 > Not correct.  It's driven by KDE, and it's more ambitious than that:
http://kde-cygwin.sourceforge.net/qt3-win32/roadmap.php
IIRC, people have already run some KDE apps under Windows (though
still needing X, so far).
I wonder how TrollTech will react as (and if) it progresses.
I don't think your giving TrollTech any credit here, yes they have
a business model and need to make money, but not everybody is
Microsoft. They are fully aware and supportive of the project
and I remember reading not to long ago they struck an aggrement
with the project that if anything ever happened to TrollTech they
would release Qt to project under gpl, or something like that.
--
http://mail.python.org/mailman/listinfo/python-list


Re: pyQT 4

2005-07-25 Thread Ken Godee

> My question is : does anybody know when pyqt 4 will be distributed ?
> 

http://www.riverbankcomputing.co.uk/pyqt/roadmap.php
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ideas for university project ??

2005-08-28 Thread Ken Starks
Jon Hewer wrote:

> Hi
> 
> I'm about to start my third, and final, year in computer science at
> cambridge uni, and i need to come up with an idea for a software
> project, but i'm really struggling for ideas, and i was wondering
> whether anyone here had any suggestions.
> 
> I'd say i'm probably most experienced in Java, but I have started
> learning Python, and although i haven't got very far yet, I plan on
> doing some more in the next few weeks.
> 
> Areas of interested include AI, distributed systems.  Most of all i
> want something that is interesting, and actually useful (thats
> probably stating the obvious!)
> 
> Cheers
> Jon

I'd like you to write a Python-SOAP-based interface to data-loggers and
interface boxes used in the UK at school level. For example, those
produced by Phillip Harris, which are normally connected by way of a
serial cable.

The idea is to keep an old computer with the data-logger attached, and
the SOAP server installed, in the field or lab. Am I correct in saying
that Java is too security-bound for this role?

Personally, I would feed the resulting XML into Cocoon, which already has
SOAP input, and from there into dataframes in 'R' among other places. Once
it has entered a Cocoon pipeline, it is already in a very flexible form, and
Data analysis can be done anywhere that can reach the Cocoon server. 

You may wish to develop that end of the pipeline either using your Java
skills, or by using XSLT to create Prolog facts or whatever.





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


Re: Need help with C extension module

2005-09-13 Thread Ken Seehart
chris wrote:
> This is my first attempt at undertaking a C extension module.  I want
> to wrap an existing C library so I can call the functions from Python.
> There are only two functions I'm interested in calling.  I did mess
> with Pyrex a bit and Swig, to no avail, so I turned to doing it by
> hand.  Using the example in Programming Python, I did get the easier of
> the two functions working--only takes a string parameter.  I'm stuck
> now on the other function and not sure how to wrap it, because it
> involves some structs.  Here's a simplified version of the C:
> 
> struct In
> {
>   int x;
>   char* s;
>   ... (only primitive data types)
> };
> 
> struct Out
> {
>   int y;
>   char* s;
>   ... (only primitive data types)
> };
> 
> Out* func(In* x, Out* y);
> 
> So the function takes pointers to the two structs, and fills out the
> output struct and also returns the pointer to it.  I would envision the
> Python looking like
> 
> in = In()
> in.y = 1
> in.s = "abc"
> ...
> 
> out = func(in)
> 
> maybe?  Just no idea how to deal with the structs in the C extension
> module code.
> 
> Any tips appreciated.
> 
> Thanks,
> Chris
> 

Since others have responded about Pyrex, I'll just add my two cents,
which may or not apply to you.

The idea of filling in a struct, passing it to a function, then
returning a struct, is a typical c-ism.  If the only purpose of the
structs is to pass data to the function and receive the result, read on.
  On the other hand, if the structures represent "things" in the
object-oriented sense, just ignore what I am saying.

I would wrap the function such that the python code simply takes a set
of parameters and returns a tuple.  This is much more pythonic, and much
easier to code.

y,s,... = func(x,s,...)

My untested pseudocode would look something like this:

static PyObject *map_sweep(map__object *self, PyObject *args)
{
   In input;
   Out output;

   if (PyArg_ParseTuple(args, "is...", &(In.x), &(In.s), ...))
   {
 return NULL;
   }

   func(&In, &Out);

   return Py_BuildValue("is...", Out.y, Out.s, ...);
}



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


Python for ARM7?

2005-09-13 Thread Ken Seehart
Hello.  Where might I find python binaries for ARM7 (Linux 2.4)?

I don't have an ARM7 compiler, and I probably don't have enough disk
space (about 3MB of flash available) for the complete build anyway.

My plan is to just copy the files I need.  This approach seems to work
on Windows XP, where I have a working python executable with the
libraries I need (python.exe, SimpleHTTPServer.py and dependencies), all
in about 1 MB.  The application is basically a web server.

If I absolutely have to build my own python, I would probably use a
cygwin (or maybe linux) cross-compiler for ARM7, but that seems like a
daunting task.  I'd much rather find someone who has already done it who
has the binaries :)

I'm pretty sure the only files I actually need are the python executable
and the _socket shared library.

Thanks,
- Ken


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


Re: Python for ARM7?

2005-09-13 Thread Ken Seehart
Sybren Stuvel wrote:
> Ken Seehart enlightened us with:
> 
>>Hello.  Where might I find python binaries for ARM7 (Linux 2.4)?
> 
> 
> Check http://www.vanille.de/projects/python.spy
> 
> 
>>If I absolutely have to build my own python, I would probably use a
>>cygwin (or maybe linux) cross-compiler for ARM7, but that seems like a
>>daunting task.
> 
> 
> It is. From the above URL:
> 
> : The build process of Python compiles a core part of it (the parser
> : generator pgen) and tries to execute that later in the build
> : process. This - of course - doesn't work for cross compiling.
> 
> Sybren

Wow thanks!

Two more questions:

1. How do I know whether to use sharprom or modern?

2. What do I do with ipk files?  I surfed around and found that in one 
example, the command is "ipkg install foo.ipk", but ipkg doesn't seem to 
exist on my hardware.

Thanks again!
- Ken

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


Re: Python for ARM7?

2005-09-13 Thread Ken Seehart
Sybren Stuvel wrote:
> Ken Seehart enlightened us with:
> 
>>1. How do I know whether to use sharprom or modern?
>  
> If it works, use it.

That makes sense :)

>>2. What do I do with ipk files?  I surfed around and found that in
>>one example, the command is "ipkg install foo.ipk", but ipkg doesn't
>>seem to exist on my hardware.
> 
> ipkg doesn't have anything to do with your hardware. It's just a shell
> script. Anyway, an ipkg file is nothing more than a tarball with a
> certain content.

> Sybren

That was a dumb way for me to put it :)  What I mean is that the linux 
installation on my hardware is so stripped down I don't have various 
files such as ipkg.  It's helpful to know that ipkg is a shell script 
instead of a binary, but I am also missing tar, ar, and gcc (which I 
assume I need libraries from).

I could try to unpack them on another (non-ARM7) linux box and then move 
the files over to the ARM7 device.  Better yet, can I unpack them on 
windows XP somehow?

If for some reason that is not possible, i suppose my next step is to 
find a compatible ARM7 linux installation to unpack on another machine 
to steal files from.  Unfortunately I don't have access to another ARM7 
computer, and I don't have room for a full linux installation on the 
ARM7 device that I am working with (it has a total of 4MB).  It there an 
easy to obtain the files I need without attempting to reintall linux?

The files I know about are:
   libgcc1 (>= 3.4.3)  (exact file name unknown)
   libc6 (>= 2.3.2+cvs20040726)  (exact file name unknown)
   ipkg (the shell script)
   tar
   ar
   (any other commands that ipkg runs)

- Ken


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


Re: which is more 'pythonic' / 'better' ?

2005-09-13 Thread Ken Seehart
Will McGugan wrote:
> gabor wrote:
> 
>> hi,
>>
>> there are 2 versions of a simple code.
>> which is preferred?
>>
>>
>> ===
>> if len(line) >= (n+1):
>> text = line[n]
>> else:
>> text = 'nothing'
>> ===
>>
>>
>> ===
>> try:
>> text = line[n]
>> except IndexError:
>> text = 'nothing'
>> ===
>>
>>
>> which is the one you would use?
> 
> 
> I would actualy use the following for this particular case..
> 
> text = line[n:n+1] or 'nothing'
> 
> But in general I think it is best to use exceptions like that only where 
>  you expect the code to _not_ throw the exception the majority of times. 
> Otherwise the simple condition is better. Although I expect there is not 
> much difference either way..
> 
> 
> Will McGugan
> -- 
> http://www.kelpiesoft.com

Hey are you a perl programmer?  That looks perlish to me.  A python 
programmer would never use "or" that way (even though it works).  :)

It's okay, I used to be a perl programmer too.  It's nothing to be 
ashamed of. :)

- Ken

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


Re: Creating Pie Chart from Python

2005-09-15 Thread Ken Seehart
Thierry Lam wrote:
> Let's say I have the following data:
> 
> 500 objects:
> -100 are red
> -300 are blue
> -the rest are green
> 
> Is there some python package which can represen the above information
> in a pie chart?
> 
> Thanks
> Thierry
> 

What is the user interface context?

Is it a web page?  Do you want to create image files with pie chart?  If 
  yes to either of these, try gdchart.

http://www.icewalkers.com/Linux/Software/52020/GDChart.html
http://athani.pair.com/msteed/software/gdchart/download.html




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


Re: wxPython vs. pyQt

2005-03-17 Thread Ken Godee
tc wrote:
Has anyone compiled binaries for qt/pyqt/eric3. i'd really like to try
it. at the moment i work with wxWindows and BoaConstructor which i'm
actually not so happy with. design of gui's with wx is not very
efficient...
so is there already a binary for qt/pyqt/eric3 available or when can i
excpect qt4 to be released?
tc
http://kde-redhat.sourceforge.net/
apt/yum/etc. repositories
qt-3.3.3-16.3.3.kde.i386.rpm
sip-4.1.1-0.2.3.kde.i386.rpm
PyQt-3.13-2.0.3.kde.i386.rpm
PyKDE-3.11.3-0.5.3.kde.i386.rpm
qscintilla-1.4-0.1.3.kde.i386.rpm
eric-3.6.1-0.fdr.1.3.i386.rpm
and more

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


Re: threading, qt, and the freakout

2004-11-29 Thread Ken Godee
Ben Floyd wrote:
Hey everyone,
Why doesn't this work? The code speaks much more clearly than I do,
so i shortened it and pasted it below.  Running this
and clicking on 'Break Me' will... freak out the window...
You can not mix GUI threads and non GUI threads.
Just changing text may seem to work, but
even that will get you eventually.
Here's an article that explains how to do it...
http://www.informit.com/articles/article.asp?p=30708

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


Re: Class Variable Inheritance

2004-12-08 Thread Ken Rowlands
On Wed, 08 Dec 2004 15:55:09 -0900, Brian Jones wrote:

> I'm sure the solution may be obvious, but this problem is driving me 
> mad.  The following is my code:
> 
> class a(object):
> 
>   mastervar = []
> 
>   def __init__(self):
>   print 'called a'
> 
> class b(a):
> 
>   def __init__(self):
>   print 'called b'
>   self.mapvar()
> 
>   def mapvar(self):
>   self.mastervar.append(['b'])
> 
> class c(b):
> 
>   def __init__(self):
>   print 'called c'
>   self.mapvar()
> 
>   def mapvar(self):
>   super(c, self).mapvar()
>   self.mastervar.append(['c'])
> 
> if __name__ == '__main__':
> 
>   a1 = a()
>   b1 = b()
>   c1 = c()
>   d1 = c() # Call C again
> 
>   print a1.mastervar
>   print b1.mastervar
>   print c1.mastervar
>   print d1.mastervar
> 
> What I don't understand is why mastervar gets modified by each _seperate 
> instance_ of classes that happen to extend the base class 'a'. 
> Shouldn't mastervar be contained within the scope of the inheriting 
> classes?  Why is it being treated like a global variable and being 
> modified by the other instances?
> 
> 
> Thanks,
> 
> Brian "bojo" Jones


Brian,

This is the first time I've responded to a post in this newsgroup so bear
with me.

First of all I believe that the place you declare mastervar is important.
As you have placed it above (or outside) any class methods/functions it
becomes a class variable. This gives it class scope and ALL instances of
that class (and sub-classes I think) will reference the SAME variable. If,
instead, you declare it inside the __init__ function of the class a object
it will be an instance variable and inheritable.

Secondly, in order to inherit methods and functions from base classes it
is important to remember to call the base class __init__ function in the
sub-class __init__ function.

If you do both these things, that is declare mastervar as 'self.mastervar
= []' inside class a.__init__ and call a.__init__ from b.__init__ (and
likewise for b in c) then you should get the expected result. I hope.

All I can say at this point is that I and not what you would call a
programmer, and I could be quite wrong in my explanation. However if this
doesn't help then there are many folk here who are better qualified to
give you the correct solution.


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


Re: Need Help: Server to pass py objects

2005-03-29 Thread Ken Godee
>I have a legacy system with data stored in binary files on a remote 
>server.
>I need to access and modify the content of those files from a webserver
>running on a different host.  (All Linux)
>
>I would like to install a server on the legacy host that would use my 
>python
>code to translate between the legacy files and Python Objects that 
>represent
>the subset of data I care about, then pass those Python objects back >and
>forth to my webserver, which would then manage the http I/F to various
>clients.
>
>My organization prefers to use open source software.
>
>Can anyone suggest some products to research further?


Take a look here
http://pyro.sourceforge.net/
--
http://mail.python.org/mailman/listinfo/python-list


Re: workaround for generating gui tools

2005-04-10 Thread Ken Godee
Jeremy Bowers wrote:
On Sun, 10 Apr 2005 13:57:26 +0200, Diez B. Roggisch wrote:

Domain-specific abstractions do that *faster* than GUI designers, not
slower. And better, too, since every iteration tends to be fully
functional and not just a "let's see what this looks like" prototype.
Can you show me some working, in-use example for that?  I _seriously_ doubt
that the process of rearranging and tuning the layout can be done faster in
the text-world than with a good designer like qt-designer. But I'm all ears
for better solutions.

Regrettably, no. I have them but they are all unsharable, either because
the real owner would consider them proprietary, or because they are an
unreleased and at the moment unfinished product I can't give the code out
for.
But I can help some.
This guys gotta be a politician or english major or something! :)
155 lines, 1706 words, 9493 character reply, but his method is so simple
he still can't show us an example!
The original poster was just asking for an example of
how to sub class his code generated form into his program
for easy future updates, a "VERY STANDARD" way of doing it.
I tried at first to follow this "Great Way" of doing it,
but I guess I'm to simple minded, or just got to damed borded.
Hey, that's just me. I guess I'll just be stuck zapping out
forms with qt designer, the old fashion way.

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


Command Line Inputs from Windows

2015-01-02 Thread Ken Stewart

Court of King Arthur,

I’d appreciate any help you can provide.  I’m having problems passing 
command line parameters from Windows 7 into a Python script (using Python 
3.4.2).  It works correctly when I call the interpreter explicitly from the 
Windows command prompt, but it doesn’t work when I enter the script name 
without calling the Python interpreter.


This works:
python myScript.py arg1 arg2 arg3

This doesn’t work:
myScript.py arg1 arg2 arg3

The Windows PATH environment variable contains the path to Python, as well 
as the path to the Script directory.  The PATHEXT environment variable 
contains the Python extension (.py).


There are other anomalies too between the two methods of invoking the script 
depending on whether I include the extension (.py) along with the script 
name.  For now I’m only interested in passing the arguments without 
explicitly calling the Python interpreter.



Here is the script:

#! python

import sys

def getargs():
   sys.stdout.write("\nHello from Python %s\n\n" % (sys.version,))
   print ('Number of arguments =', len(sys.argv))
   print ('Argument List =', str(sys.argv))

if __name__ == '__main__':
   getargs()


Result_1 (working correctly):

C:\Python34\Scripts> python myScript.py arg1 arg2 arg3

Hello from Python 3.4.2 (v3.4.2:ab2c023a9432, Oct  6 2014, 22:15:05) [MSC 
v.1600 32 bit (Intel)]


   Number of arguments = 4
   Argument List = ['myScript.py', 'arg1', 'arg2', 'arg3']


Result_ 2 (Fail)

C:\Python34\Scripts> myScript.py arg1 arg2 arg3

Hello from Python 3.4.2 (v3.4.2:ab2c023a9432, Oct  6 2014, 22:15:05) [MSC 
v.1600 32 bit (Intel)]


   Number of arguments = 1
   Argument List = ['C:\\Python34\\Scripts\\myScript.py']

As a beginner I’m probably making a mistake somewhere but I can’t find it. 
I don’t think the shebang does anything in Windows but I’ve tried several 
variations without success.  I’ve tried writing the script using only 
commands, without the accouterments of a full program (without the def 
statement and without the if __name__ == ‘__main__’ …) to no avail.  I’m out 
of ideas.  Any suggestions?


Ken Stewart

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


Re: Command Line Inputs from Windows

2015-01-03 Thread Ken Stewart

Chris, Dennis, James, and Mark:

SUCCESS!  Thanks for your suggestions.  It was the registry.  Kudos to 
Dennis.  The data strings for a lot of different "command" keys in the 
registry were missing the %* (percent star) characters.  Thanks Chris for 
the explanation on why the %* string is needed.


Here is a sample key:
S1-5-21-1560217580-722697556-320042093-1000-Classes
   py_auto_file
   shell
   open
   command

The corrected data for the key looks like this:

"C:\Python34\python.exe" %1 %*

I used the 'find' tool in regedit to search for python in the registry. 
There were many hits on the word python but only a handful had data fields 
similar to the one above.  Every instance was missing the %* string.  I 
modified them all.  My script didn't start working until after I'd modified 
the very last one.  Happily, my computer still boots after mucking around in 
the registry.


I haven't yet investigated the launcher suggested by Chris and Mark.  That 
may well be the proper solution.  At the moment it looks like the Python 
installer didn't create these registry entries properly in Windows 7.


Thanks again

Ken Stewart

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


Re: Trees

2015-01-20 Thread Ken Seehart
Exactly. There are over 23,000 different kinds of trees. There's no way 
you could get all of them to fit in a library, especially a standard 
one. Instead, we prefer to provide people with the tools they need to 
grow their own trees.


http://caseytrees.org/programs/planting/ctp/
http://www.ncsu.edu/project/treesofstrength/treefact.htm
http://en.wikipedia.org/wiki/Tree

On 1/19/2015 3:01 PM, Mark Lawrence wrote:

On 19/01/2015 22:06, Zachary Gilmartin wrote:

Why aren't there trees in the python standard library?



Probably because you'd never get agreement as to which specific tree 
and which specific implementation was the most suitable for inclusion.




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


Re: Trees

2015-01-21 Thread Ken Seehart

Hash Table, Christiania
(a table with many kinds of hash)

On 1/20/2015 12:19 PM, Devin Jeanpierre wrote:

There are similarly many kinds of hash tables.

For a given use case (e.g. a sorted dict, or a list with efficient
removal, etc.), there's a few data structures that make sense, and a
library (even the standard library) doesn't have to expose which one
was picked as long as the performance is good.

-- Devin

On Tue, Jan 20, 2015 at 12:15 PM, Ken Seehart  wrote:

Exactly. There are over 23,000 different kinds of trees. There's no way you
could get all of them to fit in a library, especially a standard one.
Instead, we prefer to provide people with the tools they need to grow their
own trees.

http://caseytrees.org/programs/planting/ctp/
http://www.ncsu.edu/project/treesofstrength/treefact.htm
http://en.wikipedia.org/wiki/Tree

On 1/19/2015 3:01 PM, Mark Lawrence wrote:

On 19/01/2015 22:06, Zachary Gilmartin wrote:

Why aren't there trees in the python standard library?


Probably because you'd never get agreement as to which specific tree and
which specific implementation was the most suitable for inclusion.


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


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


Printing to printer, windows 7

2015-02-16 Thread ken . hessel
Would seem to be a simple problem.  I just want to print to my printer instead 
of the console using Python 2.7, Windows 7.  Hours of looking through FAQ's and 
Google haven't yielded a solution.  Any suggestions appreciated --
-- 
https://mail.python.org/mailman/listinfo/python-list


Building a python extension on Windows

2015-10-27 Thread Ken Brooks
I checked out a copy of svn.python.org/projects/stackless/trunk because it 
seems to have a good sample project (PC/example_nt) for building a Python 
extension on Windows. That directory has a Microsoft Visual C++ solution file 
which can be updated to my Visual C++ version (8, of 2005).

First I tried cd-ing to that directory, as they recommend, and saying "python 
setup.py install". The result? A very common complaint, "Unable to find 
vcvarsall.bat". A search using Windows would suggest that that file doesn't 
exist anywhere on my system.

So I followed the VC++ build instructions, and copied the example_nt directory 
up one level in the tree before building it. But when I actually try to build 
the solution it wants to look in the PCBuild directory for python27.lib, which 
isn't there. Nor can I find that library anywhere else.

What gives? Is this project somehow hopelessly out of date? And more to the 
point, can someone direct me to a nice, fresh example project that will build a 
little Python extension on Windows?

Thanks,

Ken

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


Re: Yet another attempt at a safe eval() call

2013-03-14 Thread Ken Seehart
On 1/4/2013 5:33 AM, Steven D'Aprano wrote:
> On Fri, 04 Jan 2013 07:24:04 -0500, Terry Reedy wrote:
>
>> On 1/3/2013 6:25 PM, Grant Edwards wrote:
>>> I've written a small assembler in Python 2.[67], and it needs to
>>> evaluate integer-valued arithmetic expressions in the context of a
>>> symbol table that defines integer values for a set of names.  The
>>> "right" thing is probably an expression parser/evaluator using ast, but
>>> it looked like that would take more code that the rest of the assembler
>>> combined, and I've got other higher-priority tasks to get back to.
>> Will ast.literal_eval do what you want?
> No. Grant needs to support variables, not just literal constants, hence 
> the symbol table.
>
>
Apologies for the delayed response...

Seems like it would be a bit safer and easier to approach this problem
by stretching the capability of ast.literal_eval() rather than
attempting to sandbox eval().

How about ast.literal_eval after performing lexical substitution using
the symbol table?

Assignment into the symbol table, and error handling, are exercises left
to the reader.

Something vaguely like this:

/pseudocode:/

def safe_eval(s, symbols={}):
while search(s, r'\w+'):
replace match with '('+repr(symbols[match])+')' in s
return ast.literal_eval(s)

- Ken

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


advice required re migrating php app to python and most likely zope

2006-01-05 Thread Ken Guest
Hi,
I've two relatively small web applications that are currently implemented in
PHP and needed to be migrated to python and most likely zope afterwards as
we're getting a third-party Zope powered CMS later this year.

There isn't an immediate need for them to be developed as zope
modules/extensions so I was wondering what the best approach might me -
especially as they'd be deployed in the middle of a PHP driven website.

Would I be best off to enable mod_python inside apache for the moment, writing
good modular reusable code that may|should need minimum tweaks for when our
Zope CMS comes on-line or should I go the full way and design the web apps for
Zope from day zero?

k.


-- 
Ken Guest
Mobile: +353 86 8252 141http://blogs.linux.ie/kenguest/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: advice required re migrating php app to python and most likely zope

2006-01-06 Thread Ken Guest
On Thu, Jan 05, 2006 at 10:10:39PM +0100, Diez B. Roggisch wrote:
> Ken Guest schrieb:
> > Hi,
> > I've two relatively small web applications that are currently implemented in
> > PHP and needed to be migrated to python and most likely zope afterwards as
> > we're getting a third-party Zope powered CMS later this year.
> > 
> > There isn't an immediate need for them to be developed as zope
> > modules/extensions so I was wondering what the best approach might me -
> > especially as they'd be deployed in the middle of a PHP driven website.
> > 
> > Would I be best off to enable mod_python inside apache for the moment, 
> > writing
> > good modular reusable code that may|should need minimum tweaks for when our
> > Zope CMS comes on-line or should I go the full way and design the web apps 
> > for
> > Zope from day zero?
> 
> If you want ZOPE, the only way is to use it right from the start. There 
> is not much you can write as "good modular reusable code", as ZOPE 
> imposes quite a few constraints on the way things _have_ to happen. That 
> isn't a bad thing! Its just that with ZOPE, you've got to grok what it 
> is about to use it, and much things are different from the simple 
> one-page-one-script-stuff you ususally come up with in PHP.
> 

Well it'll be zope/plone to be more exact - good to know I should start off
with zope sooner rather than later, thanks Diez.

k.

-- 
Ken Guest
Mobile: +353 86 8252 141http://blogs.linux.ie/kenguest/
-- 
http://mail.python.org/mailman/listinfo/python-list


installing numpy: problems with lapack, blas etc

2006-07-24 Thread Ken Dere
I am trying to install numpy-0.9.8 prior to installing scipy (0.4.9) on a
machine running Suse 10.0 with Python 2.4

I am able to get numpy installed to the point when I import it I can do the
following:


numpy.show_config()
atlas_threads_info:
  NOT AVAILABLE

blas_opt_info:
libraries = ['f77blas', 'cblas', 'atlas']
library_dirs = ['/usr/lib/atlas']
define_macros = [('ATLAS_INFO', '"\\"3.6.0\\""')]
language = c

atlas_blas_threads_info:
  NOT AVAILABLE

lapack_opt_info:
libraries = ['lapack', 'f77blas', 'cblas', 'atlas']
library_dirs = ['/usr/lib/atlas']
define_macros = [('ATLAS_INFO', '"\\"3.6.0\\""')]
language = c

atlas_info:
libraries = ['lapack', 'f77blas', 'cblas', 'atlas']
library_dirs = ['/usr/lib/atlas']
language = c

lapack_mkl_info:
  NOT AVAILABLE

blas_mkl_info:
  NOT AVAILABLE

atlas_blas_info:
libraries = ['f77blas', 'cblas', 'atlas']
library_dirs = ['/usr/lib/atlas']
language = c

mkl_info:
  NOT AVAILABLE

It is clear that I have much but not all that is needed.  I have already
downloaded lapack and compiled the blas and lapack libraries and put them
in /usr/lib/atlas and defined BLAS and LAPACK so I am not sure what I have
missed.

Thanks

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


modifying __new__ of list subclass

2006-08-14 Thread Ken Schutte
Hi,

I'm been trying to create some custom classes derived from some of 
python's built-in types, like int and list, etc.  I've run into some 
trouble, which I could explain with a couple simple examples.  Lets say 
I want an int-derived class that is initilized to one greater than what 
it's constructor is given:

class myint(int):
   def __new__(cls, intIn):
 newint = int(intIn+1)
 return int.__new__(cls, newint)

print myint(3), myint(10)


Okay, seems to do what I want.  Now, lets say I want a list class that 
creates a list of strings, but appends "_" to each element.  I try the 
same thing:


class mylist(list):
   def __new__(cls, listIn):
 newlist = list()
 for i in listIn:
   newlist.append(str(i) + "_")
 print "newlist: ", newlist
 return list.__new__(cls, newlist)

print mylist(("a","b","c"))

Doesn't seem to work, but that print statement shows that the newlist is 
what I want...   Maybe what I return from __new__ is overwritten in 
__init__?   Could someone enlighten me as to why - and why this is 
different than the int case?

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


Re: modifying __new__ of list subclass

2006-08-15 Thread Ken Schutte
Steven Bethard wrote:
> 
> The __new__ method is for immutable types.  So things like str and int 
> do their initialization in __new__.  But for regular mutable types, you 
> should do your initialization in __init__::
> 

I see... So, is there a use for __new__ in mutable types?   From my 
list-derirved class, it was obviously being called, but it's return 
value is totally ignored?

Thanks for the reply.

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


Re: modifying __new__ of list subclass

2006-08-15 Thread Ken Schutte
Steven Bethard wrote:
> So even though your __new__ method returns the object you want, the 
> __init__ method is clearing out all the items you've added and then 
> re-adding them as it normally would. To prove this to yourself, take a 
> look at what happens when we override __init__::
> 

Okay, I see what's happening now.  Steve and Alex - thanks for the great 
explanations.

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


Re: The Semicolon Wars as a software industry and human condition

2006-08-17 Thread Ken Tilton


Xah Lee wrote:

> 
> • What Languages to Hate, Xah Lee, 2002
> http://xahlee.org/UnixResource_dir/writ/language_to_hate.html

Nonsense. This is technology, not religion. Technologists in fact have a 
responsibility to identify and use the best tools available.

Xah, you are getting soft in your old age. :)

hth, kenny

-- 
Cells: http://common-lisp.net/project/cells/

"I'll say I'm losing my grip, and it feels terrific."
-- Smiling husband to scowling wife, New Yorker cartoon
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: logo design

2006-11-01 Thread Ken Tilton


alex23 wrote:
> Xah Lee wrote:
> 
>>No personal offense intended, but human animal's history is what? 3000
>>years at least in recorded history? And, all you can think of is what,
>>the view points of a fraction of your personal life span?
> 
> 
> Thank god evolution spat you out to lead us all to the light, huh?
> 
> No personal offense intended, but you're a boring, elitist prick.

Actually, no, Xah is pretty cool, give him a chance.

hth, kt

-- 
Cells: http://common-lisp.net/project/cells/

"I'll say I'm losing my grip, and it feels terrific."
-- Smiling husband to scowling wife, New Yorker cartoon
-- 
http://mail.python.org/mailman/listinfo/python-list


Regular Expression question

2006-06-07 Thread ken . carlino
Hi,
I am new to python regular expression, I would like to use it to get an
attribute of an html element from an html file?

for example, I was able to read the html file using this:
   req = urllib2.Request(url=acaURL)
f = urllib2.urlopen(req)

data = f.read()

my question is how can I just get the src attribute value of an img
tag?
something like this:
(.*)(.*)

I need to get the href of the image source.

Thanks.

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


Exeucte a system command in python script

2006-06-08 Thread ken . carlino
Hi,

I would like to execute a shell command like this in python:
cmd = 'ant release -Dbuild=build_proxyonly -Drev=5.1.130f
-Dprops=\"-MIDP20_LARGE;PUSH_FEATURE=false;MIDlet-Version=5.0;version=5.0;MIDlet-Icon=midicon15x15.png;-FOUR_WAY_NAV_FEATURE\"
-DThree_Branding=true'

Which of the execl command described here should I use?
http://pydoc.org/1.6/os.html

Thank you for any help.

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


Re: Exeucte a system command in python script

2006-06-08 Thread ken . carlino
Thanks I get this error 'NameError: global name 'call' is not defined"

I already import 'subprocess'.

Can you pleaes tell me what am I missing?

Robert Kern wrote:
> [EMAIL PROTECTED] wrote:
> > Hi,
> >
> > I would like to execute a shell command like this in python:
> > cmd = 'ant release -Dbuild=build_proxyonly -Drev=5.1.130f
> > -Dprops=\"-MIDP20_LARGE;PUSH_FEATURE=false;MIDlet-Version=5.0;version=5.0;MIDlet-Icon=midicon15x15.png;-FOUR_WAY_NAV_FEATURE\"
> > -DThree_Branding=true'
> >
> > Which of the execl command described here should I use?
> > http://pydoc.org/1.6/os.html
>
> None. You should use the subprocess module in 2.4 (I really do hope that 
> you're
> not using 1.6).
>
>   http://docs.python.org/lib/module-subprocess.html
>
> It also works in Pythons as old as 2.2, but you'll have to install it
> separately. The website for the separate release is down at the moment, but 
> when
> it comes back up:
>
>   http://www.lysator.liu.se/~astrand/popen5/
>
> --
> Robert Kern
>
> "I have come to believe that the whole world is an enigma, a harmless enigma
>  that is made terrible by our own mad attempt to interpret it as though it had
>  an underlying truth."
>   -- Umberto Eco

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


Re: Exeucte a system command in python script

2006-06-08 Thread ken . carlino
I am using python 2.4, so I don' t need to insteall that module
separately.

[EMAIL PROTECTED] wrote:
> Thanks I get this error 'NameError: global name 'call' is not defined"
>
> I already import 'subprocess'.
>
> Can you pleaes tell me what am I missing?
>
> Robert Kern wrote:
> > [EMAIL PROTECTED] wrote:
> > > Hi,
> > >
> > > I would like to execute a shell command like this in python:
> > > cmd = 'ant release -Dbuild=build_proxyonly -Drev=5.1.130f
> > > -Dprops=\"-MIDP20_LARGE;PUSH_FEATURE=false;MIDlet-Version=5.0;version=5.0;MIDlet-Icon=midicon15x15.png;-FOUR_WAY_NAV_FEATURE\"
> > > -DThree_Branding=true'
> > >
> > > Which of the execl command described here should I use?
> > > http://pydoc.org/1.6/os.html
> >
> > None. You should use the subprocess module in 2.4 (I really do hope that 
> > you're
> > not using 1.6).
> >
> >   http://docs.python.org/lib/module-subprocess.html
> >
> > It also works in Pythons as old as 2.2, but you'll have to install it
> > separately. The website for the separate release is down at the moment, but 
> > when
> > it comes back up:
> >
> >   http://www.lysator.liu.se/~astrand/popen5/
> >
> > --
> > Robert Kern
> >
> > "I have come to believe that the whole world is an enigma, a harmless enigma
> >  that is made terrible by our own mad attempt to interpret it as though it 
> > had
> >  an underlying truth."
> >   -- Umberto Eco

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


Re: What is Expressiveness in a Computer Language

2006-06-09 Thread Ken Tilton


Joe Marshall wrote:
> Xah Lee wrote:
> 
>>in March, i posted a essay "What is Expressiveness in a Computer
>>Language", archived at:
>>http://xahlee.org/perl-python/what_is_expresiveness.html
>>
>>I was informed then that there is a academic paper written on this
>>subject.
>>
>>On the Expressive Power of Programming Languages, by Matthias
>>Felleisen, 1990.
>>http://www.ccs.neu.edu/home/cobbe/pl-seminar-jr/notes/2003-sep-26/expressive-slides.pdf
>>
>>Has anyone read this paper? And, would anyone be interested in giving a
>>summary?
> 
> 
> The gist of the paper is this:  Some computer languages seem to be
> `more expressive' than
> others.  But anything that can be computed in one Turing complete
> language can be computed in any other Turing complete language.
> Clearly the notion of
> expressiveness isn't concerned with ultimately computing the answer.
> 
> Felleisen's paper puts forth a formal definition of expressiveness in
> terms of semantic
> equivilances of small, local constructs.  In his definition, wholescale
> program transformation is
> disallowed so you cannot appeal to Turing completeness to claim program
> equivalence.
> 
> Expressiveness isn't necessarily a good thing.  For instance, in C, you
> can express the
> addresses of variables by using pointers.  You cannot express the same
> thing in Java, and
> most people consider this to be a good idea.
> 

Thanks for the summary.

Me, I would like to see a definition of expressiveness that would 
exclude a programming mechanism from "things to be expressed".

If the subject is programmer productivity, well, I write programs to get 
some behavior out of them, such as operating an ATM cash dispenser. If I 
need to keep a list of transactions, I need to express the abstraction 
"list" in some data structure or other, but below that level of 
abstraction I am just hacking code, not expressing myself -- well, that 
is the distinction for which I am arguing.

heck, in this case I will even give you as "thing to express" getting 
back multiple values from a function. That comes up all the time, and it 
can be an aggravation or a breeze. But then I would score C down because 
it does not really return multiple values. One still has some heavy 
lifting to do to fake the expressed thing. But I would still give it an 
edge over java because Java's fakery would have to be a composite object 
-- one could not have a primary return value as the function result and 
ancillary values "somewhere else".

kt

-- 
Cells: http://common-lisp.net/project/cells/

"I'll say I'm losing my grip, and it feels terrific."
-- Smiling husband to scowling wife, New Yorker cartoon
-- 
http://mail.python.org/mailman/listinfo/python-list


TONIGHT! Lisp group beerfest in NYC, PyCells to be discussed

2006-06-13 Thread Ken Tilton
The royal We has just learned that His Kennyness will be honoring the 
boozehounds of LispNYC with His Presence tonight (deets below).

He will come bearing Celtk and news of PyCells, though the top billing 
tonight goes to SoC student Extraordinaire Samantha Kleinberg.

kenzo

> Please join us for our next meeting on Tuesday, June 13th from 7:00
> to 9:00 at Westside Brewery.
> 
> With Summer of Code being here, this is a great opportunity to talk and
> drink regarding the students and their projects!
> 
> Hope to see you there!
> 
> 
> 
> Directions:
> 
>  Westside Brewery in the VIP room
>  340 Amsterdam Ave.
>  (On the West side of Amsterdam Ave., 76th-77th)
> 
> Directions by subway: 1-2-3-9 (the red line) to 72nd or 79th and
> Broadway.  From 72nd, walk up Amsterdam (not Broadway).  From 79th, walk
> east one long block to Amsterdam and turn right/south.
> 
> Directions by car: 79th street exit from west side highway, down West
> End Ave or Broadway to 76th, turn left and one or two blocks to
> Amsterdam.

-- 
Cells: http://common-lisp.net/project/cells/

"I'll say I'm losing my grip, and it feels terrific."
-- Smiling husband to scowling wife, New Yorker cartoon
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reddit broke - should have remained on Lisp?

2006-06-29 Thread Ken Tilton


Luis M. González wrote:
> Alok wrote:
> 
>>While posting a comment on http://www.reddit.com I got an error page
>>with the following curious statement on it.
>>
>>"reddit broke (sorry)"
>>"looks like we shouldn't have stopped using lisp..."
>>
>>See screenshot at
>>http://photos1.blogger.com/blogger/1773/1980/1600/reddit-broke.jpg
>>
>>Whether they truly repent not using lisp or otherwise, their site
>>appears to be 3 times slower ...
>>
>>Alok
> 
> 
> 
> I don't know if this is true or not, but blaming a language for a poor
> development is a little bit ridiculous...
> 

Well, Reddit said it, not us, and they were probably joking, but it may 
well be that the bug would not have happened if they were using Lisp. 
Could an infinite number of engineers doing code reviews eventually 
found the bug before the end of the universe? The reality is that every 
project has finite resources, all the better reason not to stress the 
team with the wrong language.

kenny (making Rahul happy by being f'ed by OpenGL bugs)

-- 
Cells: http://common-lisp.net/project/cells/

"I'll say I'm losing my grip, and it feels terrific."
-- Smiling husband to scowling wife, New Yorker cartoon
-- 
http://mail.python.org/mailman/listinfo/python-list


Setting "value" of an int-derived class

2006-09-02 Thread Ken Schutte
Lets say I want an integer class that lets you attach arbitrary 
attributes.  I can simply do:

class foo(int): pass

x = foo(5)
x.text = "okay"
print x, x.text   # prints "5 okay"

So, that's good.  But, how can I change the value of x from 5 to 
something else, without creating a new instance?

I suppose I could create a function that creates a new "foo" and copies 
its attributes, but is there a more direct way?  Is the value "5" stored 
in some special attribute I can just directly modify?

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


  1   2   3   4   >