Using Python from Cocoa App via PyObjc - numbers dont match...
Hi, I managed to create a python class and instantiate that from my Objective C Cocoa App (its not a python app). Essentially, i made two classes in IB and then another class(ogle) with outlets for these two. Now here is the implementation for ogle.m -(void)awakeFromNib { NSNumber *n=[NSNumber numberWithFloat:40.4]; NSLog(@"%@",n); NSNumber *b=[it2 printNok:n]; NSLog(@"%@",b); // } The first output in the console is 40.4 and the second -40.4152587891. If i change the NSLog(s) to "%f",[n floatValue] (and the second likewise) the first is 40.42 and the second is -40.42. Why does this happen? Thanks Saptarshi p.s the python routine printNok, just returns the negative of the number i.e printNok: def printNok_(self, obj): return -obj -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python from Cocoa App via PyObjc - numbers dont match...
Hi, Well not a complaint as such but a question. Thank you for the response however and the link. I have seen it before but never got around to reading it... Further to this, if i was writing a python module and c function and suppose the python module and the c function called each other back and forth exchanging results from float calculations - would not the results then become flawed? How would one pass floats between different languages - using special purpose data structures understood by both the python module and c code? I asked this question without reading the link, so if it stinks of ignorance please forget it. Thank you Saptarshi Michael Ash wrote: > In comp.lang.objective-c sapsi <[EMAIL PROTECTED]> wrote: > > The first output in the console is 40.4 and the second > > -40.4152587891. > > > > If i change the NSLog(s) to "%f",[n floatValue] (and the second > > likewise) the first is 40.42 and the second is -40.42. > > I assume you are complaining about the fact that it's not printing exactly > 40.4, and wondering where the error is coming from. (It helps if you > actually state this yourself, so we don't have to assume it, rather than > just laying out the circumstances.) > > The answer is that floating point numbers are inherently imprecise. Read > through this essential resource: > > http://docs.sun.com/source/806-3568/ncg_goldberg.html > > -- > Michael Ash > Rogue Amoeba Software -- http://mail.python.org/mailman/listinfo/python-list
Dispatching a method using PyobjC Selectors/Methods
Hi, I am writing a SIMBL plugin for Mail.app, so far it loads and the correct method has been swizzled. However, i would like to call the original method and that is where the problem lies. If you could see the code(below), in console.app, i get the following error because of old(x) " 2007-06-26 03:42:04.053 Mail[2600] *** NSRunLoop ignoring exception 'exceptions.TypeError: 'int' object is not callable' that raised during posting of delayed perform with target 5bd1b10 and selector '_finalSetup' " #saved as MailDump.py import objc from Foundation import * from AppKit import * WebMessageEditor = objc.lookUpClass('WebMessageEditor') old=1 swizzled = {} #http://end.com/svn/BionicDOM/tags/1.0/ BionicDOMPalette.py def swizzle(cls, SEL, func): NSLog(cls) oldIMP = cls.instanceMethodForSelector_(SEL) oldMethod = objc.selector(oldIMP.__call__, selector=oldIMP.selector, signature=oldIMP.signature) newMethod = objc.selector(func, selector=oldIMP.selector, signature=oldIMP.signature) objc.classAddMethod(cls, 'OLD'+SEL, oldMethod) objc.classAddMethod(cls, SEL, newMethod) swizzled[(cls, SEL, func)] = (oldMethod, newMethod, oldIMP) return(oldMethod) def updateContentsToShowSignature_(self,x): NSLog("OHMYGOD") old(x) class MWM(NSObject): plugin = None # We will retain a pointer to the plugin to prevent it being garbage-collected @classmethod def sharedInstance(cls): # not strictly necessary, but we only need one instance of our object if not cls.plugin: cls.plugin = cls.alloc().init() return cls.plugin @classmethod def initialize(cls): old=swizzle(WebMessageEditor, 'updateContentsToShowSignature:', updateContentsToShowSignature_) #setup.py # from distutils.core import setup # import py2app # plist = dict( # NSPrincipalClass='MWM', # CFBundleName='MWM', # SIMBLTargetApplications=[dict(BundleIdentifier='com.apple.mail', MinBundleVersion='000', MaxBundleVersion='20')], # ) # setup( # plugin=['MailDump.py'], # options=dict(py2app=dict( # extension='.bundle', # plist=plist, # )), # ) #Run the following #python2.4 setup.py py2app -A #and copy the dist/MailDump.bundle to ~/Library/Application Support/ SIMBL/Plugins/ -- http://mail.python.org/mailman/listinfo/python-list
Using struct timeval in python
Hi, I am using a library (pcapy) that returns a timeval object T= (seconds,microseconds) where microseconds is always < 1e6. Is there a Python class that can handle timeval structs? Specifically, I wish to subtract two T (defined above) objects, taking into account the large values of T[0] and T[1] (esp T[0])? At one point, I would have to step in, since T[0] rolls back to zero (after some time). Any pointers? Thanks in advance Saptarshi -- http://mail.python.org/mailman/listinfo/python-list
Re: Using struct timeval in python
The timedelta module did the job just fine. Thank you -- http://mail.python.org/mailman/listinfo/python-list
Sets in Python
Hello, I recently tried using the set function in Python and was surprised to find that a=[ 1, 2,3, [1,2] ] doesn't work with 'set', throwing TyperError (unhashable exception). I found out that this is because lists can't be hashed. So,this implies 'a' cannot be a set in python which i think is quite unfortunate, after all 'a' does look like a mathematical set. My question is, 1) Why can't lists be hashed? and 2) This is not related, but is there i neat way (without pop and list comprehension) to convert a set into a list? I say neat because i'm guessing using list comprehension might turn out be slow and there might be other methods which are faster. Thank you for your time SM -- http://mail.python.org/mailman/listinfo/python-list
Python,SWIG and libjvm
Hello, I'm not sure if this the correct list but here goes (and sorry for the noise). I've been attempting to wrap python around libhdfs. So far so good (i've attached the SWIG template at the end). The compilation works without errors and the shared objects do have references to all the functions. However, when importing into python import pyhdfs i get the following error: Traceback (most recent call last): File "", line 1, in ? File "/home/sguha/tmp/b/hdfs.py", line 7, in ? import _hdfs ImportError: libjvm.so: cannot open shared object file: No such file or directory However, libjvm.so is located in /home/sguha/mine/jdk1.6.0_02/jre/lib/ amd64/server which is present in the PYTHONPATH and sys.path. I can understand it complaining while loading the libjvm.so but python doesn't locate it even when in the path. As an aside, the build command for hdfs.c has " -ljvm " - this should affect SWIG, right? Meaning if my program (e.g) links to a library and i want a wrapper around my program (to python) i need SWIG templates for my headers only and not for the linked library...right? ( I guess the answer is i dont otherwise that would be quite a nightmare of work) Thank you for your time Saptarshi Attachments: SWIG template %module pyhdfs %{ #include "hdfs.h" %} %include "hdfs.h" -- http://mail.python.org/mailman/listinfo/python-list
Re: Python,SWIG and libjvm
On Sep 20, 7:00 pm, sapsi <[EMAIL PROTECTED]> wrote: > Hello, > I'm not sure if this the correct list but here goes (and sorry for the > noise). I've been attempting to wrap python around libhdfs. > So far so good ( I should point out that libhdfs is a c library to Hadoop Distributed FileSystem. Thank you Saptarshi -- http://mail.python.org/mailman/listinfo/python-list
Re: Python,SWIG and libjvm
On Sep 20, 8:22 pm, sapsi <[EMAIL PROTECTED]> wrote: > On Sep 20, 7:00 pm, sapsi <[EMAIL PROTECTED]> wrote: > > > Hello, > > I'm not sure if this the correct list but here goes (and sorry for the > > noise). I've been attempting to wrap python around libhdfs. > > So far so good ( > > I should point out that libhdfs is a c library to Hadoop Distributed > FileSystem. > Thank you > Saptarshi Hmm,here goes, you need -Wl,--rpart -Wl,path-to-jvm in the LDFLAGS in the compile process. HTH Saptarshi -- http://mail.python.org/mailman/listinfo/python-list
Re: Sets in Python
Thank you everyone for the assistance and for the very informative discussion Regards SM -- http://mail.python.org/mailman/listinfo/python-list
LoopingCall vs internet.TimerService (Twisted)
Hi, I guess this is not the most appropriate forum but i tried the twisted forum to not avail so here goes. I have written a server which accepts connections from clients, takes requests and adds them to a Queue (a python object of Queue.Queue). Now i have two approaches a) At startup, my server(a subclass of pb.Root) runs a "dispatcher" function using task.LoopingCall(dispatcher).start(0.1) b)Create a separate subclass of internet.TimerService whose function is dispatcher [INFO: dispatcher has methods like obj.callRemote, addCallback and addErrback] I checked the source and it seems Loopingcall is implemented through callLaters//Callbacks and TimerService has LoopingCall in it. So which is better, neater, safer? loopingcall of timerservice? also is it safe to do the calls mentioned in INFO within dispatcher? Thank you for your time Saptarshi -- http://mail.python.org/mailman/listinfo/python-list
Passing all extra commandline arguments to python program, Optparse raises exception
Hello, Im using optparse and python 2.6 to parse some options, my commandline looks like prog [options] start|stop extra-args-i-will-pas-on The options are --b --c --d The extra options are varied are are passed onto another program e.g -- quiet --no-command , my program doesnt care what these are but instead passes them onto another program. I know these will always follow start|stop. However optparse tries to process them and throws an exception - how can i prevent this without placing all the extra-args in quotes. Thank you Saptarshi -- http://mail.python.org/mailman/listinfo/python-list
Reading Java byte[] data stream over standard input
Hello, I am using HadoopStreaming using a BinaryInputStream. What this basically does is send a stream of bytes ( the java type is : private byte[] bytes) to my python program. I have done a test like this, while 1: x=sys.stdin.read(100) if x: print x else: break Now, the incoming data is binary(though mine is actually merely ascii text) but the output is not what is expected. I expect for e.g all/86000/114.310.151.209.60370-121.110.5.176.113\n62485.9718 118.010.241.12 60370 128.210.5.176 However i get a 1 before all and a 4 just after \n and before the 6. My question is : how do i read binary data(Java's byte stream) from stdin? Or is this actually what i'm getting? Thanks Sapsi -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading Java byte[] data stream over standard input
I should also mention that for some reason there are several binay values popping in between for some reason. This behavior (for the inputr stream) is not expected > Now, the incoming data is binary(though mine is actually merely ascii > text) but the output is not what is expected. I expect for e.g > > all/86000/114.310.151.209.60370-121.110.5.176.113\n62485.9718 > 118.010.241.12 60370 128.210.5.176 > > However i get a 1 before all and a 4 just after \n and before the 6. > > My question is : how do i read binary data(Java's byte stream) from > stdin? > Or is this actually what i'm getting? > > Thanks > Sapsi -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading Java byte[] data stream over standard input
Yes, that could be the case. Browsing through hadoop's source, i see stdin in the above code is reading from piped Java DataOutputStream. I read of a libray on the net Javadata.py that reads this but it has disappeared. What is involved in reading from a Dataoutputstream? Thank you Sapsi -- http://mail.python.org/mailman/listinfo/python-list
Numpy, adding a row to a matrix
Hello, I have a numpy array (2 rows 3 colums) import numpy a=numpy.array( [ [1,2,3] , [3,3,1] ]) I wish to add a row, this is how i do it s=a.shape numpy.resize(a,s[0]+1,s[1]) a[s[0]]=new row vector. Q: Is this a costly operation? What happens if i have to it several (and unknown) number of times? is there a simpler way to add a row? Thank you in advance Saptarshi -- http://mail.python.org/mailman/listinfo/python-list
Re: Numpy, adding a row to a matrix
Hello, Thank you. Yes, I will post to the numpy mailing list in future. Regards Saptarshi On Jun 9, 4:04 pm, Robert Kern <[EMAIL PROTECTED]> wrote: > sapsi wrote: > > Hello, > > I have a numpy array (2 rows 3 colums) > > > import numpy > > a=numpy.array( [ [1,2,3] , [3,3,1] ]) > > > I wish to add a row, this is how i do it > > > s=a.shape > > numpy.resize(a,s[0]+1,s[1]) > > a[s[0]]=new row vector. > > > Q: Is this a costly operation? > > It can be if you have large arrays. > > > What happens if i have to it several > > (and unknown) number of times? > > is there a simpler way to add a row? > > numpy.vstack([a, newrow]) > > Generally speaking, you shouldn't resize numpy arrays. If you need to > construct > an array by appending, build up a list instead and use vstack() (or hstack() > or > dstack() or column_stack() or concatenate() depending on the geometry). > > We also have a numpy mailing list, which you should direct future numpy > questions to: > > http://www.scipy.org/Mailing_Lists > > -- > 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
A Question about ctypes and a function f(void **)
Hello, I have a C function f(void**,int *), in which it writes some information (it is a RGB32 image). Here is what i do rowlength=c_int() data=c_void_p() d=pointer(data) f(d,byref(rowlength) The call works (no segmentation fault), now how do i access the data in d? Because i need to pass it to a another function QImage that takes void* as its first parameter. If i do d.contents i get c_void_p(3067478024L) All suggestions welcome. Regards Saptarshi -- http://mail.python.org/mailman/listinfo/python-list
sqlite empty inserts
Hello, I created a table like: create table __saved_query__ (vdb_name text , query_table_name text PRIMARY KEY, query text) and then I insert as follows self.cursor.execute( "insert into __saved_query__(vdb_name, query_table_name, query) values (?,?,?)", (vdbname, foldername,where_query)) self.conn.commit() Now for some reason, the first insert works, but thereafter all inserts result in empty rows e.g sqlite> select * from __saved_query__; TestVDB|test_b|title regexp 'boo' || || The last two rows are from the 2nd and 3rd inserts. The values i;m inserting are non null. Any ideas? Thank you for your time Saptarshi -- http://mail.python.org/mailman/listinfo/python-list
Re: sqlite empty inserts
Hi, Thank you for the tip, you're absolutely right.I;m getting an exception that the name must not be null. However, this is some debug output --- logging.debug(" %s %s %s" % (vdbname, foldername,where_query)) OUTPUT: TestVDB test_b title regexp 'tit' --- print vdbname.__class__, foldername.__class__,where_query.__class__ OUTPUT: --- self.cursor.execute( "insert into __saved_query__(vdb_name, query_table_name, query) values (?,?,?)", (vdbname, foldername,where_query)) OUTPUT: __saved_query__.vdb_name may not be NULL I honestly don't get it!. Why should this occur? Regards Saptarshi > > Change the query to ... query_table_name text PRIMARY KEY NOT NULL ... to > verify that assertion before you look any further. > > Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: sqlite empty inserts
I forgot to mention that i was creating a view just before this i.e sql="create view %s as %s" % (foldername, query) # self.cursor.execute(sql) self.cursor.execute(sql) Now if i remove this, the insert code works fine. Regards Saptarshi -- http://mail.python.org/mailman/listinfo/python-list
Re: sqlite empty inserts
On Aug 16, 11:20 am, Peter Otten <[EMAIL PROTECTED]> wrote: > sapsi wrote: > > [please don't top-post] > > > > > Thank you for the tip, you're absolutely right.I;m getting an > > exception that the name must not be null. However, this is some debug > > output > > --- logging.debug(" %s %s %s" % (vdbname, foldername,where_query)) > > OUTPUT: TestVDB test_b title regexp 'tit' > > --- print vdbname.__class__, > > foldername.__class__,where_query.__class__ > > OUTPUT: > > > --- self.cursor.execute( "insert into __saved_query__(vdb_name, > > query_table_name, query) values (?,?,?)", (vdbname, > > foldername,where_query)) > > > OUTPUT: __saved_query__.vdb_name may not be NULL > > > I honestly don't get it!. Why should this occur? > > Because vbdname is None? > > Seriously, it's hard for us to tell what's going on without the relevant > code. If you don't provide enough context you are on your own. > > Peter Actualy, vdbname is not none. I checked the value before entering. I found out that by closing the connection and reopening after creating VIEW solved the problem. Not a nice solution but it works and not a hassle given the low frequency of the operation. Regards Saptarshi --code self.cursor.execute( "insert into __smartfolder__ values (?,?,?,?)", (vdbname, foldername,where_query,hrform)) self.conn.commit() self.cursor.execute("CREATE VIEW %s AS %s" % (foldername, query) ) self.conn.close() self.connect_to_db() --- If i didn't close and reopen, the second time i try inserting i get the aforementioned error -- http://mail.python.org/mailman/listinfo/python-list
QT, ctypes dll and SEG Faults
Hello, Below is a small class using ctypes and libspectre to read a postscript file. My program is a PyQT 4.4 application and when the user clicks on a entry in a QTableWidget, i run PostScriptImage( filename_as_contained_in_clicked_tableWidgetItem ) However on i get a segfault while trying document_load. Surprisingly, before i run sys.exit(app.exec_()) (i.e before the app starts) if run PostScriptImage(command_line_specified_ps_file) it works! I know the ctypes so file works with QT since i wrote an application using it, but i hadn't separated the ctypes stuff into separate class (i.e the spectre code was in the widget method). Any ideas why the crash? Regards Saptarshi --Python Code-- class PostScriptImage: def __init__(self,filename): print "Doc New" self.document=libspec.spectre_document_new() print "Load Doc" , filename #crashed in the following line# libspec.spectre_document_load(self.document,filename) print "Done load doc" if libspec.spectre_document_status(self.document): return False self.scale=[1.0,1.0] self.quicksetup() def quicksetup(self): print "RC" rc=libspec.spectre_render_context_new() print "Get 0th Page" page=libspec.spectre_document_get_page (self.document, 0) if libspec.spectre_document_status(self.document): raise Exception("Spectre:Setup Document Error") w= c_int() h= c_int() print "Page Size" libspec.spectre_page_get_size(page, byref(w),byref(h)) self.initialSize=(h.value*1.0,w.value*1.0) self.initialAspect=float(h.value)/float(w.value) self.npages=libspec.spectre_document_get_n_pages(self.document) -- http://mail.python.org/mailman/listinfo/python-list
Re: QT, ctypes dll and SEG Faults
On Aug 16, 11:37 pm, sapsi <[EMAIL PROTECTED]> wrote: > Hello, > Below is a small class using ctypes and libspectre to read a > postscript file. > My program is a PyQT 4.4 application and when the user clicks on a > entry in a QTableWidget, i run > > PostScriptImage( filename_as_contained_in_clicked_tableWidgetItem ) > However on i get a segfault while trying document_load. > Surprisingly, before i run sys.exit(app.exec_()) (i.e before the app > starts) if run PostScriptImage(command_line_specified_ps_file) it > works! > > I know the ctypes so file works with QT since i wrote an application > using it, but i hadn't separated the ctypes stuff into separate class > (i.e the spectre code was in the widget method). > > Any ideas why the crash? > > Regards > Saptarshi > --Python Code-- > class PostScriptImage: > def __init__(self,filename): > print "Doc New" > self.document=libspec.spectre_document_new() > print "Load Doc" , filename > #crashed in the following > line# > libspec.spectre_document_load(self.document,filename) > print "Done load doc" > if libspec.spectre_document_status(self.document): > return False > self.scale=[1.0,1.0] > self.quicksetup() > > def quicksetup(self): > print "RC" > rc=libspec.spectre_render_context_new() > print "Get 0th Page" > page=libspec.spectre_document_get_page (self.document, 0) > if libspec.spectre_document_status(self.document): > raise Exception("Spectre:Setup Document Error") > w= c_int() > h= c_int() > print "Page Size" > libspec.spectre_page_get_size(page, byref(w),byref(h)) > self.initialSize=(h.value*1.0,w.value*1.0) > self.initialAspect=float(h.value)/float(w.value) > > self.npages=libspec.spectre_document_get_n_pages(self.document) To answer my own question, partially, i found out if i replace filename with a hard coded value it doesn't crash. Now why is that? Does python lose the reference? Should i store filename as attributed of the object? Regards Saptarshi -- http://mail.python.org/mailman/listinfo/python-list
Write binary data to standard error?
Hello, This is probably a basic question, but how does one write binary data to standard error e.g int as network order (4 bytes)? Much thanks Saptarshi -- http://mail.python.org/mailman/listinfo/python-list