Search Results

Search found 73 results on 3 pages for 'ctypes'.

Page 2/3 | < Previous Page | 1 2 3  | Next Page >

  • How do I convert a Python list of lists of lists into a C array by using ctypes?

    - by pc05
    As seen here How do I convert a Python list into a C array by using ctypes? this code will take a python array and transform it to a C array. import ctypes arr = (ctypes.c_int * len(pyarr))(*pyarr) Which would the way of doing the same with a list of lists or a lists of lists of lists? For example, for the following variable list3d = [[[40.0, 1.2, 6.0, 0.3], [50.0, 4.2, 0, 0]], [[40.0, 1.2, 6.0, 0.3], [50.0, 4.2, 0, 0]], [[40.0, 1.2, 6.0, 0.3], [50.0, 4.2, 0, 0]]] I have tried the following with no luck: ([[ctypes.c_double * 4] *2]*3)(*list3d) # *** TypeError: 'list' object is not callable (ctypes.c_double * 4 *2 *3)(*list3d) # *** TypeError: expected c_double_Array_4_Array_2 instance, got list Thank you! EDIT: Just to clarify, I am trying to get one object that contains the whole multidimensional array, not a list of objects. This object's reference will be an input to a C DLL that expects a 3D array.

    Read the article

  • ctypes and pointer manipulation

    - by Chris
    I am dealing with image buffers, and I want to be able to access data a few lines into my image for analysis with a c library. I have created my 8-bit pixel buffer in Python using create_string_buffer. Is there a way to get a pointer to a location within that buffer without re-creating a new buffer? My goal is to analyze and change data within that buffer in chunks, without having to do a lot of buffer creation and data copying. In this case, ultimately, the C library is doing all the manipulation of the buffer, so I don't actually have to change values within the buffer using Python. I just need to give my C function access to data within the buffer.

    Read the article

  • ctypes buffer modification

    - by Chris
    Hi, I need to call a c library from my python code. The c library does a lot of image manipulation, so I am passing it image buffers allocated using create_string_buffer. The problem is that I also need to manipulate and change these buffers. What is the best way to reach in and twiddle individual values in my buffers? The buffers are all uint8 buffers. Thanks!

    Read the article

  • How to provide js-ctypes in a spidermonkey embedding?

    - by Triston J. Taylor
    Summary I have looked over the code the SpiderMonkey 'shell' application uses to create the ctypes JavaScript object, but I'm a less-than novice C programmer. Due to the varying levels of insanity emitted by modern build systems, I can't seem to track down the code or command that actually links a program with the desired functionality. method.madness This js-ctypes implementation by The Mozilla Devs is an awesome addition. Since its conception, scripting has been primarily used to exert control over more rigorous and robust applications. The advent of js-ctypes to the SpiderMonkey project, enables JavaScript to stand up and be counted as a full fledged object oriented rapid application development language flying high above 'the bar' set by various venerable application development languages such as Microsoft's VB6. Shall we begin? I built SpiderMonkey with this config: ./configure --enable-ctypes --with-system-nspr followed by successful execution of: make && make install The js shell works fine and a global ctypes javascript object was verified operational in that shell. Working with code taken from the first source listing at How to embed the JavaScript Engine -MDN, I made an attempt to instantiate the JavaScript ctypes object by inserting the following code at line 66: /* Populate the global object with the ctypes object. */ if (!JS_InitCTypesClass(cx, global)) return NULL; /* I compiled with: g++ $(./js-config --cflags --libs) hello.cpp -o hello It compiles with a few warnings: hello.cpp: In function ‘int main(int, const char**)’: hello.cpp:69:16: warning: converting to non-pointer type ‘int’ from NULL [-Wconversion-null] hello.cpp:80:20: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings] hello.cpp:89:17: warning: NULL used in arithmetic [-Wpointer-arith] But when you run the application: ./hello: symbol lookup error: ./hello: undefined symbol: JS_InitCTypesClass Moreover JS_InitCTypesClass is declared extern in 'dist/include/jsapi.h', but the function resides in 'ctypes/CTypes.cpp' which includes its own header 'CTypes.h' and is compiled at some point by some command during 'make' to yeild './CTypes.o'. As I stated earlier, I am less than a novice with the C code, and I really have no idea what to do here. Please give or give direction to a generic example of making the js-ctypes object functional in an embedding.

    Read the article

  • I need to speed up a function. Should I use cython, ctypes, or something else?

    - by Peter Stewart
    I'm having a lot of fun learning Python by writing a genetic programming type of application. I've had some great advice from Torsten Marek, Paul Hankin and Alex Martelli on this site. The program has 4 main functions: generate (randomly) an expression tree. evaluate the fitness of the tree crossbreed mutate As all of generate, crossbreed and mutate call 'evaluate the fitness'. it is the busiest function and is the primary bottleneck speedwise. As is the nature of genetic algorithms, it has to search an immense solution space so the faster the better. I want to speed up each of these functions. I'll start with the fitness evaluator. My question is what is the best way to do this. I've been looking into cython, ctypes and 'linking and embedding'. They are all new to me and quite beyond me at the moment but I look forward to learning one and eventually all of them. The 'fitness function' needs to compare the value of the expression tree to the value of the target expression. So it will consist of a postfix evaluator which will read the tree in a postfix order. I have all the code in python. I need advice on which I should learn and use now: cython, ctypes or linking and embedding. Thank you.

    Read the article

  • How to implement ctypes in IronPython

    - by Walter
    I need help. I have a code which is passing a script into a DLL and initialize the instrument. But, one of the code unable to use in IronPython beside python 2.7 and 3.3 I have attached the code as below enter code here import ctypes import time, sys DLLHANDLE=ctypes.cdll.LoadLibrary("C:\\INSTRDLL\\builds\\DCSOURCEDLL\\B2902A.dll") INPUTSCRIPT="SYSTEM{DCSOURCE1|INIT}" INPUTVOLTAGE=0.0 c_INPUTSCRIPT=ctypes.c_char_p(INPUTSCRIPT) c_INPUTVOLTAGE=ctypes.c_double(INPUTVOLTAGE) SOURCEHANDLE=DLLHANDLE.DCSOURCE(c_INPUTSCRIPT,c_INPUTVOLTAGE) time.sleep(1) Once "SOURCEHANDLE=DLLHANDLE.DCSOURCE(c_INPUTSCRIPT,c_INPUTVOLTAGE)" is triggered, Ironpython will crash automatically and no idea how to resolve it... or any workaround solution? Please advice..

    Read the article

  • How do I build a python string from a raw (binary) ctype buffer?

    - by fcrazy
    I'm playing with Python and ctypes and I can't figure out how to resolve this problem. I call to a C function which fills a raw binary data. My code looks like this: class Client(): def __init__(self): self.__BUFSIZE = 1024*1024 self.__buf = ctypes.create_string_buffer(self.__BUFSIZE) self.client = ctypes.cdll.LoadLibrary(r"I:\bin\client.dll") def do_something(self): len_written = self.client.fill_raw_buffer(self.__buf, self.__BUFSIZE) my_string = repr(self.__buf.value) print my_string The problem is that I'm receiving binary data (with 0x00) and it's truncated when I tried to build my_string. How can I build my_string if self._buf contains null bytes 0x00? Any idea is welcome. Thanks

    Read the article

  • Call functions in AutoIt DLL using Python ctypes

    - by Josh
    I want to call functions from an AutoIt dll, that I found at C:\Program Files (x86)\AutoIt3\AutoItX\AutoItX3.dll using Python. I know I could use win32com.client.Dispatch("AutoItX3.Control") but I can't install the application or register anything in the system. So far, this is where I am: from ctypes import * path = r"C:\Program Files (x86)\AutoIt3\AutoItX\AutoItX3.dll" autoit = windll.LoadLibrary(path) Here are the methods that works: autoit.AU3_WinMinimizeAll() # windows were successfully minimized. autoit.AU3_Sleep(1000) # sleeps 1 sec. Here is my problem, python is crashing when I call other methods like this one. I get python.exe has stopped working from windows... autoit.AU3_WinGetHandle('Untitled - Notepad', '') And some other methods are not crashing python but are just not working. This one doesn't close the window and return 0: autoit.AU3_WinClose('Untitled - Notepad', '') And this other one return 1 but the window is still minimized: autoit.AU3_WinActivate('Untitled - Notepad', '') I've tested the examples with with Dispatch("AutoItX3.Control") and everything is working like expected. It seems like methods that should return something other than a string are crashing python. But still, others like WinClose are not even working... Thank you in advance for your help! EDIT: These methods are now working when using unicode strings: autoit.AU3_WinClose(u'Untitled - Notepad', u'') autoit.AU3_WinActivate(u'Untitled - Notepad', u'') And I found the prototype for AU3_WinGetHandle: AU3_API void WINAPI AU3_WinGetHandle(const char szTitle, /[in,defaultvalue("")]*/const char *szText, char *szRetText, int nBufSize); Now I see that I should get the handle from szRetText but I am not sure how... I tried the following without success: from ctypes.wintypes import LPCWSTR, INT, POINTER AU3_WinGetHandle.argtypes = (LPCWSTR, LPCWSTR, POINTER(LPCWSTR), INT) s = c_wchar_p() print AU3_WinGetHandle(u'Untitled - Notepad', u'', byref(s), 100) # prints 1 print s # prints c_wchar_p(u'') Any idea how to retrive the handle from szRetText?

    Read the article

  • How to debug ctypes call of c++ dll?

    - by aF
    Hello, in my python project I call a c++ dll using ctypes library. That c++ dll consists on a wrapper dll that calls methods of a c# com interop dll. Sometimes I have a COM exception. I like to see what it corresponds exactlly but I don't know how to do it? How can I attach the c++ debugger to this situation? Thanks in advance

    Read the article

  • Python c_types .dll functions (pari library)

    - by silinter
    Alright, so a couple days ago I decided to try and write a primitive wrapper for the PARI library. Ever since then I've been playing with ctypes library in loading the dll and accessing the functions contained using code similar to the following: from ctypes import * libcyg=CDLL("<path/cygwin1.dll") #It needs cygwin to be loaded. Not sure why. pari=CDLL("<path>/libpari-gmp-2.4.dll") print pari.fibo #fibonacci function #prints something like "<_FuncPtr object at 0x00BA5828>" So the functions are there and they can potentially be accessed, but I always recieve an access violation no matter what I try. For example: pari.fibo(5) #access violation pari.fibo(c_int(5)) #access violation pari.fibo.argtypes=[c_long] #setting arguments manually pari.fibo.restype=long #set the return type pari.fibo(byref(c_int(5))) #access violation reading 0x04 consistently and any variation on that, including setting argtypes to receive pointers. The Pari .dll is written in C and the fibonacci function's syntax within the library is GEN fibo(long x) (docs @http://pari.math.u-bordeaux.fr/dochtml/html/Arithmetic_functions.html#fibonacci, I need more rep it seems). Could it be the return type that's causing these errors, as it is not a standard int or long but a GEN type, which is unique to the PARI library? Any help would be appreciated. If anyone is able to successfully load the library and use ANY function from within python, please tell; I've been at this for hours now.

    Read the article

  • How to do cleanup reliably in python?

    - by Cheery
    I have some ctypes bindings, and for each body.New I should call body.Free. The library I'm binding doesn't have allocation routines insulated out from the rest of the code (they can be called about anywhere there), and to use couple of useful features I need to make cyclic references. I think It'd solve if I'd find a reliable way to hook destructor to an object. (weakrefs would help if they'd give me the callback just before the data is dropped. So obviously this code megafails when I put in velocity_func: class Body(object): def __init__(self, mass, inertia): self._body = body.New(mass, inertia) def __del__(self): print '__del__ %r' % self if body: body.Free(self._body) ... def set_velocity_func(self, func): self._body.contents.velocity_func = ctypes_wrapping(func) I also tried to solve it through weakrefs, with those the things seem getting just worse, just only largely more unpredictable. Even if I don't put in the velocity_func, there will appear cycles at least then when I do this: class Toy(object): def __init__(self, body): self.body.owner = self ... def collision(a, b, contacts): whatever(a.body.owner) So how to make sure Structures will get garbage collected, even if they are allocated/freed by the shared library? There's repository if you are interested about more details: http://bitbucket.org/cheery/ctypes-chipmunk/

    Read the article

  • Regex For Finding Ctypes with Int32

    - by Stefan H
    (Hey all, I am looking for a little regex help... I am trying to find all CType(expression,Int32) s and replace them with CInt(expression) This, however, is proving quite difficult, considering there could be a nested Ctype(expression, Int32) within the regex match. Does anyone have any ideas for how to best go about doing this? Here is what I have now: Dim str As String = "CType((original.Width * CType((targetSize / CType(original.Height, Single)), Single)), Int32)" Dim exp As New Regex("CType\((.+), Int32\)") str = exp.Replace(str, "CInt($1)") But this will match the entire string and replace it. I was thinking of doing a recursive function to find the outer most match, and then work inwards, but that still presents a problem with things like CType(replaceChars(I), Int32)), Chr(CType(replacementChars(I), Int32) Any tips would be appreciated. Input returnString.Replace(Chr(CType(replaceChars(I), Int32)), Chr(CType(replacementChars(I), Int32))) Output: returnString.Replace(Chr(CInt(replaceChars(I))),Chr(CInt(replacementChars(I)))) Edit: Been working on it a little more and have a recursive function that I'm still working out the kinks in. Recursion + regex. it kinda hurts. Private Function FindReplaceCInts(ByVal strAs As String) As String System.Console.WriteLine(String.Format("Testing : {0}", strAs)) Dim exp As New Regex("CType\((.+), Int32\)") If exp.Match(strAs).Success Then For Each match As Match In exp.Matches(strAs) If exp.Match(match.Value.Substring(2)).Success Then Dim replaceT As String = match.Value.Substring(2) Dim Witht As String = FindReplaceCInts(match.Value.Substring(2)) System.Console.WriteLine(strAs.IndexOf(replaceT)) strAs.Replace(replaceT, Witht) End If Next strAs = exp.Replace(strAs, "CInt($1)") End If Return strAs End Function Cheers,

    Read the article

  • IO completion port key confusion

    - by Richard Tew
    I'm writing an IO completion port based server (source code here) using the Windows DLL API in Python using the ctypes module. But this is a pretty direct usage of the API and this question is directed at those who have a knowledge of IOCP, not Python. As I understand the documentation for CreateIoCompletionPort, you specify your "user defined" completion key when you call this function with a file handle (in my case a socket) you are associating with the created IOCP. When you get around to calling GetQueuedCompletionStatus, you get a completion key value along with a pointer to an overlapped object. The completion key should identify what overlapped object and request has completed. However, let's say I pass in 100 as the completion key in my CreateIoCompletionPort call with an overlapped object. When the same overlapped object has its IO completed and it arrives back through GetQueuedCompletionStatus, the completion key that accompanies it is much larger and bares no resemblance to the original value of 100. Am I misunderstanding how the completion key works, or must I be doing it wrong in the source code I linked above?

    Read the article

  • Importing ctype; embedding python in C++ application

    - by Drew
    I'm trying to embed python within a C++ based programming language (CCL: The compuatational control language, not that any of you have heard of it). Thus, I don't really have a "main" function to make calls from. I have made a test .cc program with a main, and when I compile it and run it, I am able to import my own python modules and system modules for use. When I embed my code in my CCL-based program and compile it (with g++), it seems I have most functionality, but I get the import error: ImportError: /usr/lib/python2.6/lib-dynload/_ctypes.so: undefined symbol: PyType_GenericNew Can someone explain this to me and how to go about solving it? It seems like I've linked the objects correctly. Thanks.

    Read the article

  • Know the row with max characters (C)

    - by l_core
    I have wrote a program in C, to find the row with the max number of characters. Here is the code #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> int main (int argc, char *argv[]) { char c; /* used to store the character with getc */ int c_tot = 0, c_rig = 0, c_max = 0; /* counters of characters*/ int r_tot = 0; /* counters of rows */ FILE *fptr; fptr = fopen(argv[1], "r"); if (fptr == NULL || argc != 2) { printf ("Error opening the file %s\n'", argv[1]); exit(EXIT_FAILURE); } while ( (c = getc(fptr)) != EOF) { if (c != ' ' && c != '\n') { c_tot++; c_rig++; } if (c == '\n') { r_tot++; if (c_rig > c_max) c_max = c_rig; c_rig = 0; } } printf ("Total rows: %d\n", r_tot); printf ("Total characters: %d\n", c_tot); printf ("Total characters in a row: %d\n", c_max); printf ("Average number of characters on a row: %d\n", (c_tot/r_tot)); printf ("The row with max characters is: %s\n", ??????) return 0; } I can easily find the row with the highest number of characters but how can i print that out? Thank You Folks

    Read the article

  • Mimicking basic fcntl or SetHandleInformation call in .Net

    - by Tristan
    Tornado enables win32 support by faking Python's fcntl function using SetHandleInformation, which is available via ctypes on Windows. After some other small fixes, this actually works using IronPython on Windows as well (sadly, IronPython is five times slower). I'd like to get Tornado working on any CLI platform, such using Mono on OSX or Linux. Is there a managed, cross-platform, .Net approach that can fake fcntl? Here's the win32 code from Tornado: SetHandleInformation = ctypes.windll.kernel32.SetHandleInformation SetHandleInformation.argtypes = (ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD, ctypes.wintypes.DWORD) SetHandleInformation.restype = ctypes.wintypes.BOOL HANDLE_FLAG_INHERIT = 0x00000001 F_GETFD = 1 F_SETFD = 2 F_GETFL = 3 F_SETFL = 4 FD_CLOEXEC = 1 os.O_NONBLOCK = 2048 FIONBIO = 126 def fcntl(fd, op, arg=0): if op == F_GETFD or op == F_GETFL: return 0 elif op == F_SETFD: # Check that the flag is CLOEXEC and translate if arg == FD_CLOEXEC: fd = int(fd) success = SetHandleInformation(fd, HANDLE_FLAG_INHERIT, arg) if not success: raise ctypes.GetLastError() else: raise ValueError("Unsupported arg") else: raise ValueError("Unsupported op")

    Read the article

  • Python libusb pyusb "mach-o, but wrong architecture"

    - by Jon
    I am having some trouble with the pyusb module. I have narrowed down the problem to a single line, and have created a small example script to replicate the error. #!/usr/bin/env python """ This module was created to isolate the problem in the pyusb package. Operating system: Mac OS 10.6.3 Python Version: 2.6.4 libusb 1.0.8 has been successfully installed using: sudo port install libusb I have also tried modifying /opt/local/etc/macports/macports.conf to force the i386 architecture instead of x86_64. """ from ctypes import * import ctypes.util libname = ctypes.util.find_library('usb-1.0') print 'libname: ', libname l = CDLL(libname, RTLD_GLOBAL) # RESULT: #libname: /usr/local/lib/libusb-1.0.dylib #Traceback (most recent call last): # File "./pyusb_problem.py", line 7, in <module> # l = CDLL(libname, RTLD_GLOBAL) # File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/ctypes/__init__.py", line 353, in __init__ # self._handle = _dlopen(self._name, mode) #OSError: dlopen(/usr/local/lib/libusb-1.0.dylib, 10): no suitable image found. Did find: # /usr/local/lib/libusb-1.0.dylib: mach-o, but wrong architecture # End of File This same script runs on Ubuntu 10.04 successfully. I have tried building the libusb module (directly from source AND through macports) for 32-bit (i386) instead of x86_64 (default for OS 10.6), but I receive the same error. Thank-you in advance for your help!

    Read the article

  • importing pywiiuse to test out

    - by Patrick Burton
    This is probably a simple problem. But I downloaded the pywiiuse library from here and I also downloaded the examples. However when I try to run one of the examples I end up with import issues. I'm not certain I have everything configured properly to run. One error I receive when trying to run example.py: Press 1&2 Traceback (most recent call last): File "example.py", line 73, in <module> wiimotes = wiiuse.init(nmotes) File "/home/thed0ctor/Descargas/wiiuse-0.12/wiiuse/__init__.py", line 309, in init dll = ctypes.cdll.LoadLibrary('libwiiuse.so') File "/usr/lib/python2.7/ctypes/__init__.py", line 431, in LoadLibrary return self._dlltype(name) File "/usr/lib/python2.7/ctypes/__init__.py", line 353, in __init__ self._handle = _dlopen(self._name, mode) OSError: libwiiuse.so: cannot open shared object file: No such file or directory I'm really just starting out with this library and don't really see any documentation on how to configure pywiiuse so any help is much appreciated.

    Read the article

  • How to set a __str__ method for all ctype Structure classes?

    - by Reuben Thomas
    [Since asking this question, I've found: http://www.cs.unc.edu/~gb/blog/2007/02/11/ctypes-tricks/ which gives a good answer.] I just wrote a __str__ method for a ctype-generated Structure class 'foo' thus: def foo_to_str(self): s = [] for i in foo._fields_: s.append('{}: {}'.format(i[0], foo.\_\_getattribute__(self, i[0]))) return '\n'.join(s) foo.\_\_str__ = foo_to_str But this is a fairly natural way to produce a __str__ method for any Structure class. How can I add this method directly to the Structure class, so that all Structure classes generated by ctypes get it? (I am using the h2xml and xml2py scripts to auto-generate ctypes code, and this offers no obvious way to change the names of the classes output, so simply subclassing Structure, Union &c. and adding my __str__ method there would involve post-processing the output of xml2py.)

    Read the article

  • Building an interleaved buffer for pyopengl and numpy

    - by Nick Sonneveld
    I'm trying to batch up a bunch of vertices and texture coords in an interleaved array before sending it to pyOpengl's glInterleavedArrays/glDrawArrays. The only problem is that I'm unable to find a suitably fast enough way to append data into a numpy array. Is there a better way to do this? I would have thought it would be quicker to preallocate the array and then fill it with data but instead, generating a python list and converting it to a numpy array is "faster". Although 15ms for 4096 quads seems slow. I have included some example code and their timings. #!/usr/bin/python import timeit import numpy import ctypes import random USE_RANDOM=True USE_STATIC_BUFFER=True STATIC_BUFFER = numpy.empty(4096*20, dtype=numpy.float32) def render(i): # pretend these are different each time if USE_RANDOM: tex_left, tex_right, tex_top, tex_bottom = random.random(), random.random(), random.random(), random.random() left, right, top, bottom = random.random(), random.random(), random.random(), random.random() else: tex_left, tex_right, tex_top, tex_bottom = 0.0, 1.0, 1.0, 0.0 left, right, top, bottom = -1.0, 1.0, 1.0, -1.0 ibuffer = ( tex_left, tex_bottom, left, bottom, 0.0, # Lower left corner tex_right, tex_bottom, right, bottom, 0.0, # Lower right corner tex_right, tex_top, right, top, 0.0, # Upper right corner tex_left, tex_top, left, top, 0.0, # upper left ) return ibuffer # create python list.. convert to numpy array at end def create_array_1(): ibuffer = [] for x in xrange(4096): data = render(x) ibuffer += data ibuffer = numpy.array(ibuffer, dtype=numpy.float32) return ibuffer # numpy.array, placing individually by index def create_array_2(): if USE_STATIC_BUFFER: ibuffer = STATIC_BUFFER else: ibuffer = numpy.empty(4096*20, dtype=numpy.float32) index = 0 for x in xrange(4096): data = render(x) for v in data: ibuffer[index] = v index += 1 return ibuffer # using slicing def create_array_3(): if USE_STATIC_BUFFER: ibuffer = STATIC_BUFFER else: ibuffer = numpy.empty(4096*20, dtype=numpy.float32) index = 0 for x in xrange(4096): data = render(x) ibuffer[index:index+20] = data index += 20 return ibuffer # using numpy.concat on a list of ibuffers def create_array_4(): ibuffer_concat = [] for x in xrange(4096): data = render(x) # converting makes a diff! data = numpy.array(data, dtype=numpy.float32) ibuffer_concat.append(data) return numpy.concatenate(ibuffer_concat) # using numpy array.put def create_array_5(): if USE_STATIC_BUFFER: ibuffer = STATIC_BUFFER else: ibuffer = numpy.empty(4096*20, dtype=numpy.float32) index = 0 for x in xrange(4096): data = render(x) ibuffer.put( xrange(index, index+20), data) index += 20 return ibuffer # using ctype array CTYPES_ARRAY = ctypes.c_float*(4096*20) def create_array_6(): ibuffer = [] for x in xrange(4096): data = render(x) ibuffer += data ibuffer = CTYPES_ARRAY(*ibuffer) return ibuffer def equals(a, b): for i,v in enumerate(a): if b[i] != v: return False return True if __name__ == "__main__": number = 100 # if random, don't try and compare arrays if not USE_RANDOM and not USE_STATIC_BUFFER: a = create_array_1() assert equals( a, create_array_2() ) assert equals( a, create_array_3() ) assert equals( a, create_array_4() ) assert equals( a, create_array_5() ) assert equals( a, create_array_6() ) t = timeit.Timer( "testing2.create_array_1()", "import testing2" ) print 'from list:', t.timeit(number)/number*1000.0, 'ms' t = timeit.Timer( "testing2.create_array_2()", "import testing2" ) print 'array: indexed:', t.timeit(number)/number*1000.0, 'ms' t = timeit.Timer( "testing2.create_array_3()", "import testing2" ) print 'array: slicing:', t.timeit(number)/number*1000.0, 'ms' t = timeit.Timer( "testing2.create_array_4()", "import testing2" ) print 'array: concat:', t.timeit(number)/number*1000.0, 'ms' t = timeit.Timer( "testing2.create_array_5()", "import testing2" ) print 'array: put:', t.timeit(number)/number*1000.0, 'ms' t = timeit.Timer( "testing2.create_array_6()", "import testing2" ) print 'ctypes float array:', t.timeit(number)/number*1000.0, 'ms' Timings using random numbers: $ python testing2.py from list: 15.0486779213 ms array: indexed: 24.8184704781 ms array: slicing: 50.2214789391 ms array: concat: 44.1691994667 ms array: put: 73.5879898071 ms ctypes float array: 20.6674289703 ms edit note: changed code to produce random numbers for each render to reduce object reuse and to simulate different vertices each time. edit note2: added static buffer and force all numpy.empty() to use dtype=float32 note 1/Apr/2010: still no progress and I don't really feel that any of the answers have solved the problem yet.

    Read the article

  • How can I create an ODBC connection to SAS?

    - by Chris B.
    I'm writing a program that needs to access SAS data. I've downloaded the ODBC drivers for SAS and installed them, but I need to be able to create ODBC connections on the fly, programmatically. The following code (in Python) seems like it should work: import ctypes ODBC_ADD_DSN = 1 def add_dsn(name, driver, **kw): nul, attrib = chr(0), [] kw['DSN'] = name for attr, val in kw.iteritems(): attrib.append('%s=%s' % (attr, val)) return ctypes.windll.ODBCCP32.SQLConfigDataSource(0, ODBC_ADD_DSN, driver, nul.join(attrib)) == 1 print add_dsn('SAS Test', 'SAS', description = 'Testing SAS') But it pops up the SAS ODBC configuration dialog, sets the datasource name, and waits for the user to enter the information and dismiss the dialog. How can I avoid that?

    Read the article

  • How can I dial GPRS/EDGE in Win CE

    - by brontes
    Hello all. I am developing application in python on Windows CE which needs connection to the internet (via GPRS/EDGE). When I turn on the device, the internet connection is not active. It becomes active if I open internet explorer. I would like to activate connection in my application. I'm trying to do this with RasDial function over ctypes library, but I can't get it to work. Is this the right way or I should do something else? Below is my current code. The ResDial function keeps returning error 87 – Invalid parameter. I don't know anymore what is wrong with it. I would really appreciate any kind of help. Thanks in advance. encoding: utf-8 import ppygui as gui from ctypes import * import os class MainFrame(gui.CeFrame): def init(self, parent = None): gui.CeFrame.init(self, title=u"Zgodovina dokumentov", menu="Menu") DWORD = c_ulong TCHAR = c_wchar ULONG_PTR = c_ulong class RASDIALPARAMS(Structure): _fields_ = [("dwSize", DWORD), ("szEntryName", TCHAR*21), ("szPhoneNumber", TCHAR*129), ("szCallbackNumber", TCHAR*49), ("szUserName", TCHAR*257), ("szPassword", TCHAR*257), ("szDomain", TCHAR*16), ] try: param = RASDIALPARAMS() param.dwSize = 1462 # also tried 1464 and sizeof(RASDIALPARAMS()). Makes no difference. param.szEntryName = u"My Connection" param.szPhoneNumber = u"0" param.szCallbackNumber = u"0" param.szUserName = u"0" param.szPassword = u"0" param.szDomain = u"0" iNasConn = c_ulong(0) ras = windll.coredll.RasDial(None, None, param, c_ulong(0xFFFFFFFF), c_voidp(self._w32_hWnd), byref(iNasConn)) print ras, repr(iNasConn) #this prints 87 c_ulong(0L) except Exception, e: print "Error" print e if name == 'main': app = gui.Application(MainFrame(None)) # create an application bound to our main frame instance app.run() #launch the app !

    Read the article

  • Collision library for bullet hell in Python

    - by darkfeline
    I am making a bullet hell game in Python and am looking for a suitable collision library, taking the following into consideration: The library should do 2D polygon collision. It should be very fast. As a bullet hell game, I expect to do collision checks between hundreds, likely thousands of objects every frame at a consistent 60fps. Good documentation Permissive license (like MIT, not GPL) I am also considering writing my own library in C/C++ and wrapping with python ctypes in the event that no such library exists, though I do not have experience with collision detection algorithms, so I am not sure if this would be more trouble than it's worth. Could someone provide some guidance on this matter?

    Read the article

< Previous Page | 1 2 3  | Next Page >