Search Results

Search found 15187 results on 608 pages for 'boost python'.

Page 90/608 | < Previous Page | 86 87 88 89 90 91 92 93 94 95 96 97  | Next Page >

  • How to I count key collisions when using boost::unordered_map?

    - by Nikhil
    I have a data structure with 15 unsigned longs, I have defined a hash function using hash_combine as follows: friend std::size_t hash_value(const TUPLE15& given) { std::size_t seed = 0; boost::hash_combine(seed, val1); boost::hash_combine(seed, val2); ... return seed; } I insert a large number of values into a boost::unordered_map but the performance is not good enough. Probably, I could do better with an alternative hashing function. To confirm this, I need to check how many collisions I am getting. How do I do this?

    Read the article

  • How do you manually insert options into boost.Program_options?

    - by windfinder
    I have an application that uses Boost.Program_options to store and manage its configuration options. We are currently moving away from configuration files and using database loaded configuration instead. I've written an API that reads configuration options from the database by hostname and instance name. (cool!) However, as far as I can see there is no way to manually insert these options into the boost Program_options. Has anyone used this before, any ideas? The docs from boost seem to indicate the only way to get stuff in that map is by the store function, which either reads from the command line or config file (not what I want). Basically looking for a way to manually insert the DB read values in to the map.

    Read the article

  • Cinnamon is broken after upgrade to 13.10

    - by user2306488
    I see reports of people with Unity broken after upgrading to 13.10. In my case Unity works fine but cinnamon is broken. It opens the startup applications but no window manager, no menus and the keyboad shortcuts won't work. As a consequence I can't even log out or shut down cleanly. The logs say: Oct 19 10:32:42 Aveline colord: Profile added: icc-1727cc5030c477b20ad75593e757248d Oct 19 10:32:43 Aveline gnome-session[9157]: WARNING: App 'cinnamon.desktop' exited with code 1 Oct 19 10:32:43 Aveline gnome-session[9157]: WARNING: App 'cinnamon.desktop' respawning too quickly Oct 19 10:32:43 Aveline gnome-session[9157]: CRITICAL: We failed, but the fail whale is dead. Sorry.... Oct 19 10:32:43 Aveline gnome-session[9157]: WARNING: App 'cinnamon.desktop' exited with code 1 Oct 19 10:32:46 Aveline whoopsie[1054]: online Oct 19 10:32:53 whoopsie[1054]: last message repeated 12 times Oct 19 10:32:53 Aveline kernel: [ 1982.637049] python[9626]: segfault at 1511 ip b6c9e850 sp bf8d0980 error 4 in libglib-2.0.so.0.3800.0[b6c5b000+102000] Oct 19 10:32:53 Aveline kernel: [ 1982.837527] python[9631]: segfault at 0 ip b6eb13fa sp b69ff848 error 6 in libdbus-1.so.3.7.4[b6e89000+49000] Oct 19 10:32:54 Aveline kernel: [ 1983.030271] python[9634]: segfault at a6f4098b ip b6e52389 sp bfcdad68 error 4 in libdbus-1.so.3.7.4[b6e34000+49000] Oct 19 10:32:54 Aveline kernel: [ 1983.253259] python[9639]: segfault at 4 ip b6e710f4 sp b69c1bfc error 6 in libdbus-1.so.3.7.4[b6e4b000+49000] Oct 19 10:32:54 Aveline kernel: [ 1983.501771] python[9642]: segfault at b4 ip b6e0f076 sp bf82524c error 4 in libdbus-1.so.3.7.4[b6dfd000+49000] Oct 19 10:32:54 Aveline kernel: [ 1983.721334] python[9647]: segfault at 4 ip b6eab0f4 sp b69fbbfc error 6 in libdbus-1.so.3.7.4[b6e85000+49000] Any idea?

    Read the article

  • Serializing network messages

    - by mtsvetkov
    I am writing a network wrapper around boost::asio and was wondering what is a good and simple way to serialize my messages. I have a message factory which can take care of dispatching the data to the correct builder, but I want to know if there are any established solutions for getting the binary data on the sender side and consequently passing the data for deserialization on the receiver end. Some options I've explored are: passing a pointer to a char[] to the serialize/deserialize functions (for serialize to write to, and deserialize to read from), but it's difficult to enforce buffer size this way; building on that, I decided to have the serialize function return a boost::asio::mutable_buffer, however ownership of the memory gets blurred between multiple classes, as the network wrapper needs to clean up the memory allocated by the message builder. I have also seen solutions involving streambuf's and stringstream's, but manipulating binary data in terms of its string representation is something I want to avoid. Is there some sort of binary stream I can use instead? What I am looking for is a solution (preferrably using boost libs) that lets the message builder dictate the amount of memory allocated during serialization and what that would look like in terms of passing the data around between the wrapper and message factory/message builders. PS. Messages contain almost exclusively built-in types and PODs and form a shallow but wide hierarchy for the sake of going through a factory. Note: a link to examples of using boost::serialization for something like this would be appreciated as I'm having difficulties figuring out the relation between it and buffers.

    Read the article

  • tkinter frame does not show on startup

    - by Jzz
    this is my first question on SO, so correct me please if I make a fool of myself. I have this fairly complicated python / Tkinter application (python 2.7). On startup, the __init__ loads several frames, and loads a database. When that is finished, I want to set the application to a default state (there are 2 program states, 'calculate' and 'config'). Setting the state of the application means that the appropriate frame is displayed (using grid). When the program is running, the user can select a program state in the menu. Problem is, the frame is not displayed on startup. I get an empty application (menu bar and status bar are displayed). When I select a program state in the menu, the frame displays as it should. Question: What am I doing wrong? Should I update idletasks? I tried, but no result. Anything else? Background: I use the following to switch program states: def set_program_state(self, state): '''sets the program state''' #try cleaning all the frames: try: self.config_frame.grid_forget() except: pass try: self.tidal_calculations_frame.grid_forget() except: pass try: self.tidal_grapth_frame.grid_forget() except: pass if state == "calculate": print "Switching to calculation mode" self.tidal_calculations_frame.grid() #frame is preloaded self.tidal_calculations_frame.fill_data(routes=self.routing_data.routes, deviations=self.misc_data.deviations, ship_types=self.misc_data.ship_types) self.tidal_grapth_frame.grid() self.program_state = "calculate" elif state == "config": print "Switching to config mode" self.config_frame = GUI_helper.config_screen_frame(self, self.user) #load frame first (contents depend on type of user) self.config_frame.grid() self.program_state = "config" I understand that this is kind of messy to read, so I simplified things for testing, using this: def set_program_state(self, state): '''sets the program state''' #try cleaning all the frames: try: self.testlabel_1.grid_forget() except: pass try: self.testlabel_2.grid_forget() except: pass if state == "calculate": print "switching to test1" self.testlabel_1 = tk.Label(self, text="calculate", borderwidth=1, relief=tk.RAISED) self.testlabel_1.grid(row=0, sticky=tk.W+tk.E) elif state == "config": print "switching to test1" self.testlabel_2 = tk.Label(self, text="config", borderwidth=1, relief=tk.RAISED) self.testlabel_2.grid(row=0, sticky=tk.W+tk.E) But the result is the same. The frame (or label in this test) is not displayed at startup, but when the user selects the state (calling the same function) the frame is displayed. UPDATE the sample code in the comments (thanks for that!) pointed me in another direction. Further testing revealed (what I think) the cause of the problem. Disabling the display of the status bar made the program work as expected. Turns out, I used pack to display the statusbar and grid to display the frames. And they are in the same container, so problems arise. I fixed that by using only pack inside the main container. But the same problem is still there. This is what I use for the statusbar: self.status = GUI_helper.StatusBar(self.parent) self.status.pack(side=tk.BOTTOM, fill=tk.X) And if I comment out the last line (pack), the config frame loads on startup, as per this line: self.set_program_state("config") But if I let the status bar pack inside the main window, the config frame does not show. Where it does show when the user asks for it (with the same command as above).

    Read the article

  • Dynamically loading modules in Python (+ multi processing question)

    - by morpheous
    I am writing a Python package which reads the list of modules (along with ancillary data) from a configuration file. I then want to iterate through each of the dynamically loaded modules and invoke a do_work() function in it which will spawn a new process, so that the code runs ASYNCHRONOUSLY in a separate process. At the moment, I am importing the list of all known modules at the beginning of my main script - this is a nasty hack I feel, and is not very flexible, as well as being a maintenance pain. This is the function that spawns the processes. I will like to modify it to dynamically load the module when it is encountered. The key in the dictionary is the name of the module containing the code: def do_work(work_info): for (worker, dataset) in work_info.items(): #import the module defined by variable worker here... # [Edit] NOT using threads anymore, want to spawn processes asynchronously here... #t = threading.Thread(target=worker.do_work, args=[dataset]) # I'll NOT dameonize since spawned children need to clean up on shutdown # Since the threads will be holding resources #t.daemon = True #t.start() Question 1 When I call the function in my script (as written above), I get the following error: AttributeError: 'str' object has no attribute 'do_work' Which makes sense, since the dictionary key is a string (name of the module to be imported). When I add the statement: import worker before spawning the thread, I get the error: ImportError: No module named worker This is strange, since the variable name rather than the value it holds are being used - when I print the variable, I get the value (as I expect) whats going on? Question 2 As I mentioned in the comments section, I realize that the do_work() function written in the spawned children needs to cleanup after itself. My understanding is to write a clean_up function that is called when do_work() has completed successfully, or an unhandled exception is caught - is there anything more I need to do to ensure resources don't leak or leave the OS in an unstable state? Question 3 If I comment out the t.daemon flag statement, will the code stil run ASYNCHRONOUSLY?. The work carried out by the spawned children are pretty intensive, and I don't want to have to be waiting for one child to finish before spawning another child. BTW, I am aware that threading in Python is in reality, a kind of time sharing/slicing - thats ok Lastly is there a better (more Pythonic) way of doing what I'm trying to do? [Edit] After reading a little more about Pythons GIL and the threading (ahem - hack) in Python, I think its best to use separate processes instead (at least IIUC, the script can take advantage of multiple processes if they are available), so I will be spawning new processes instead of threads. I have some sample code for spawning processes, but it is a bit trivial (using lambad functions). I would like to know how to expand it, so that it can deal with running functions in a loaded module (like I am doing above). This is a snippet of what I have: def do_mp_bench(): q = mp.Queue() # Not only thread safe, but "process safe" p1 = mp.Process(target=lambda: q.put(sum(range(10000000)))) p2 = mp.Process(target=lambda: q.put(sum(range(10000000)))) p1.start() p2.start() r1 = q.get() r2 = q.get() return r1 + r2 How may I modify this to process a dictionary of modules and run a do_work() function in each loaded module in a new process?

    Read the article

  • python socket related question.

    - by paul
    Hello,All im totally new to socket programming in python. i was read some tutorial and manual, but i didn't found what i want to make python related socket script in manual or tutorial. i want to make socket script which can send some info to server and also receive some info from server. For example, i want to send my login information to server, and want to receive result reply from server. but i have no idea..how to send my login information(id and password) to server. i was captured with wireshark, some process to send login info to server. and i was found port number is 5300 and server ip is 58.225.56.152 and i was send id is 'aaaaaaa' and password 'bbbbbbb' and i was received 'USER NOT FOUND' result from server. how can i make this kind of process with python socket ? if anyone help me some reference or some example or anything help much appreciate! 0000 00 50 56 f2 c8 cc 00 0c 29 a8 f8 c0 08 00 45 00 .PV.....).....E. 0010 00 e2 2a 19 40 00 80 06 d0 55 c0 a8 cb 85 3a e1 ..*[email protected]....:. 0020 38 98 05 f3 15 9a b9 86 62 7b 0d ab 0f ba 50 18 8.......b{....P. 0030 fa f0 26 14 00 00 50 54 3f 09 a2 91 7f 13 00 00 ..&...PT?....... 0040 00 1f 14 00 02 00 00 00 00 00 00 00 07 00 00 00 ................ 0050 61 61 61 61 61 61 61 50 54 3f 09 a2 91 7f 8b 00 aaaaaaaPT?...... 0060 00 00 1f 15 00 08 00 00 00 07 00 00 00 61 61 61 .............aaa 0070 61 61 61 61 07 00 00 00 62 62 62 62 62 62 62 01 aaaa....bbbbbbb. 0080 00 00 00 31 02 00 00 00 4b 52 0f 00 00 00 31 39 ...1....KR....19 0090 32 2e 31 36 38 2e 32 30 33 2e 31 33 33 30 00 00 2.168.203.1330.. 00a0 00 4d 69 63 72 6f 73 6f 66 74 20 57 69 6e 64 6f .Microsoft Windo 00b0 77 73 20 58 50 20 50 72 6f 66 65 73 73 69 6f 6e ws XP Profession 00c0 61 6c 20 53 65 72 76 69 63 65 20 50 61 63 6b 20 al Service Pack 00d0 32 14 00 00 00 31 30 30 31 33 30 30 35 33 31 35 2....10013005315 00e0 37 38 33 37 32 30 31 32 33 03 00 00 00 34 37 30 783720123....470 0000 00 0c 29 a8 f8 c0 00 50 56 f2 c8 cc 08 00 45 00 ..)....PV.....E. 0010 00 28 ae 37 00 00 80 06 8c f1 3a e1 38 98 c0 a8 .(.7......:.8... 0020 cb 85 15 9a 05 f3 0d ab 0f ba b9 86 63 35 50 10 ............c5P. 0030 fa f0 5f 8e 00 00 00 00 00 00 00 00 .._......... 0000 00 0c 29 a8 f8 c0 00 50 56 f2 c8 cc 08 00 45 00 ..)....PV.....E. 0010 00 4c ae 38 00 00 80 06 8c cc 3a e1 38 98 c0 a8 .L.8......:.8... 0020 cb 85 15 9a 05 f3 0d ab 0f ba b9 86 63 35 50 18 ............c5P. 0030 fa f0 3e 75 00 00 50 54 3f 09 a2 91 7f 16 00 00 ..>u..PT?....... 0040 00 1f 18 00 01 00 00 00 0e 00 00 00 55 73 65 72 ............User 0050 20 4e 6f 74 20 46 6f 75 6e 64 Not Found

    Read the article

  • Has anyone ever had OpenCV work with Python 2.7 on MacOS 10.6?

    - by ?????
    I've been trying on and off for the past 6 months to get OpenCV to work with Python on MacOS. Every time there's a new release, I try again and fail. I've tried both 64-bit and 32-bit, and both the xcode gcc and gcc installed via macports. I just spend the past two days on it, hopeful that the latest OpenCV release, that appears to include Python support directly would work. It doesn't. I've also tried and failed to use this: http://code.google.com/p/pyopencv/ I've been using OpenCV with C++ or Microsoft C++/CLI for the past few years, but I'd love to use it with Python on a Mac because that is my primary development environment. I'd love to hear from anyone who's actually been able to get the opencv python examples to run under Mac OS 10.6, either 32 or 64-bit. My last attempt was to follow the instructions on this page http://recursive-design.com/blog/2010/12/14/face-detection-with-osx-and-python/ with a clean, fresh install of 10.6 on a 64-bit capable Mac. My PYTHONPATH is set, and I can see the cv library in it. But an "import cv" from python fails. Previously, the closest I've ever gotten (again, staring on a clean, fresh 10.6 install) was this: Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import cv Fatal Python error: Interpreter not initialized (version mismatch?) Abort trap thrilllap-2:~ swirsky$ I've seen a lot of folks answering similar questions here, but have never seen an definitive answer for it.

    Read the article

  • socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access

    - by Sean Ochoa
    Hello all. I'm trying to create a custom TCP stack using Python 2.6.5 on Windows 7 to serve valid http page requests on port 80 locally. But, I've run into a snag with what seems like Windows 7 tightened up security. This code worked on Vista. Here's my sample code: import SocketServer class MyTCPHandler(SocketServer.BaseRequestHandler): def handle(self): headerText = """HTTP/1.0 200 OK Date: Fri, 31 Dec 1999 23:59:59 GMT Content-Type: text/html Content-Length: 1354""" bodyText = "<html><body>some page</body></html>" self.request.send(headerText + "\n" + bodyText) if __name__ == "__main__": HOST, PORT = "localhost", 80 server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler) server.serve_forever() C:\pythonpython TestServer.py Traceback (most recent call last): File "TestServer.py", line 19, in server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler) File "C:\Python26\lib\SocketServer.py", line 400, in init self.server_bind() File "C:\Python26\lib\SocketServer.py", line 411, in server_bind self.socket.bind(self.server_address) File "", line 1, in bind socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions How exactly do I get this to work on Windows 7?

    Read the article

  • cannot override sys.excepthook

    - by Mert Nuhoglu
    I try to customize behavior of sys.excepthook as described by the recipe. in ipython: :import pdb, sys, traceback :def info(type, value, tb): : traceback.print_exception(type, value, tb) : pdb.pm() :sys.excepthook = info :-- >>> x[10] = 5 ------------------------------------------------- Traceback (most recent call last): File "<ipython console>", line 1, in <module> NameError: name 'x' is not defined >>> pdb.pm() is not being called. It seems that sys.excepthook = info doesn't work in my python 2.5 installation. What should I look into? Any suggestion? Thank you

    Read the article

  • Implicitly invoking parent class initializer

    - by Matt Joiner
    class A(object): def __init__(self, a, b, c): #super(A, self).__init__() super(self.__class__, self).__init__() class B(A): def __init__(self, b, c): print super(B, self) print super(self.__class__, self) #super(B, self).__init__(1, b, c) super(self.__class__, self).__init__(1, b, c) class C(B): def __init__(self, c): #super(C, self).__init__(2, c) super(self.__class__, self).__init__(2, c) C(3) In the above code, the commented out __init__ calls appear to the be the commonly accepted "smart" way to do super class initialization. However in the event that the class hierarchy is likely to change, I have been using the uncommented form, until recently. It appears that in the call to the super constructor for B in the above hierarchy, that B.__init__ is called again, self.__class__ is actually C, not B as I had always assumed. Is there some way in Python-2.x that I can overcome this, and maintain proper MRO when calling super constructors without actually naming the current class?

    Read the article

  • sys.stdout not reassigning to sys.__stdout__

    - by Vince
    I'm pretty new to Python so I am still just learning the language. One of the things I came across was reassigning sys.stdout to change the default output of print. So I wrote this as a test: import sys sys.stdout = open('log.txt','a') print('hey') sys.stdout.close() sys.stdout = sys.__stdout__ print('hi') Now the string 'hi' is not written to the file but it does not show in the default output either. When I assign some other variable to sys.stdout in the beginning and change it back it works, but I'm just wondering why its not changing back the first time.

    Read the article

  • object won't die (still references to it that I can't find)

    - by user288558
    I'm using parallel-python and start a new job server in a function. after the functions ends it still exists even though I didn't return it out of the function (I used weakref to test this). I guess there's still some references to this object somewhere. My two theories: It starts threads and it logs to root logger. My questions: can I somehow findout in which namespace there is still a reference to this object. I have the weakref reference. Does anyone know how to detach a logger? What other debug suggestions do people have? here is my testcode: def pptester(): js=pp.Server(ppservers=nodes) js.set_ncpus(0) fh=file('tmp.tmp.tmp','w') tmp=[] for i in range(200): tmp.append(js.submit(ppworktest,(),(),('os','subprocess'))) js.print_stats() return weakref.ref(js) thanks in advance Wolfgang

    Read the article

  • fd.seek() IOError: [Errno 22] Invalid argument

    - by Julian Kessel
    My Python Interpreter (v2.6.5) raises the above error in the following codepart: fd = open("some_filename", "r") fd.seek(-2, os.SEEK_END) #same happens if you exchange the second arg. w/ 2 data=fd.read(2); last call is fd.seek() Traceback (most recent call last): File "bot.py", line 250, in <module> fd.seek(iterator, os.SEEK_END); IOError: [Errno 22] Invalid argument The strange thing with this is that the exception occurs just when executing my entire code, not if only the specific part with the file opening. At the runtime of this part of code, the opened file definitely exists, disk is not full, the variable "iterator" contains a correct value like in the first codeblock. What could be my mistake? Thanks in advance

    Read the article

  • Yield only as many are required from a generator

    - by Matt Joiner
    I wish to yield from a generator only as many items are required. In the following code a, b, c = itertools.count() I receive this exception: ValueError: too many values to unpack I've seen several related questions, however I have zero interest in the remaining items from the generator, I only wish to receive as many as I ask for, without providing that quantity in advance. It seems to me that Python determines the number of items you want, but then proceeds to try to read and store more than that number. How can I yield only as many items as I require, without passing in how many items I want?

    Read the article

  • Unlocking a mutex from a different thread (C++)

    - by dan
    I'm using the C++ boost::thread library, which in my case means I'm using pthreads. Officially, a mutex must be unlocked from the same thread which locks it, and I want the effect of being able to lock in one thread and then unlock in another. There are many ways to accomplish this. One possibility would be to write a new mutex class which allows this behavior. For example: class inter_thread_mutex{ bool locked; boost::mutex mx; boost::condition_variable cv; public: void lock(){ boost::unique_lock<boost::mutex> lck(mx); while(locked) cv.wait(lck); locked=true; } void unlock(){ { boost::lock_guard<boost::mutex> lck(mx); if(!locked) error(); locked=false; } cv.notify_one(); } // bool try_lock(); void error(); etc. } I should point out that the above code doesn't guarantee FIFO access, since if one thread calls lock() while another calls unlock(), this first thread may acquire the lock ahead of other threads which are waiting. (Come to think of it, the boost::thread documentation doesn't appear to make any explicit scheduling guarantees for either mutexes or condition variables). But let's just ignore that (and any other bugs) for now. My question is, if I decide to go this route, would I be able to use such a mutex as a model for the boost Lockable concept. For example, would anything go wrong if I use a boost::unique_lock< inter_thread_mutex for RAII-style access, and then pass this lock to boost::condition_variable_any.wait(), etc. On one hand I don't see why not. On the other hand, "I don't see why not" is usually a very bad way of determining whether something will work. The reason I ask is that if it turns out that I have to write wrapper classes for RAII locks and condition variables and whatever else, then I'd rather just find some other way to achieve the same effect.

    Read the article

  • Can I make pdb start debugging right away?

    - by hasen j
    I want to debug a python project The problem is, I don't know where to set a break point, what I want to do, is be able to call a method SomeClass( some_ctor_arguments ).some_method()` and have the debugger be fired right away How do I do that? I tried pdb.run( string_command ) but it doesn't seem to work right >>> import pdb >>> import <some-package> >>> pdb.run( .... ) > <string>(1)<module>() (Pdb) s NameError: "name '<some-package>' is not defined"

    Read the article

  • Automatically decorating every instance method in a class

    - by max
    I want to apply the same decorator to every method in a given class, other than those that start and end with __. It seems to me it should be doable using a class decorator. Are there any pitfalls to be aware of? Ideally, I'd also like to be able to: disable this mechanism for some methods by marking them with a special decorator enable this mechanism for subclasses as well enable this mechanism even for methods that are added to this class in runtime [Note: I'm using Python 3.2, so I'm fine if this relies on features added recently.] Here's my attempt: _methods_to_skip = {} def apply(decorator): def apply_decorator(cls): for method_name, method in get_all_instance_methods(cls): if (cls, method) in _methods_to_skip: continue if method_name[:2] == `__` and method_name[-2:] == `__`: continue cls.method_name = decorator(method) return apply_decorator def dont_decorate(method): _methods_to_skip.add((get_class_from_method(method), method)) return method Here are things I have problems with: how to implement get_all_instance_methods function not sure if my cls.method_name = decorator(method) line is correct how to do the same to any methods added to a class in runtime how to apply this to subclasses how to implement get_class_from_method

    Read the article

  • Why does decorating a class break the descriptor protocol, thus preventing staticmethod objects from behaving as expected?

    - by Robru
    I need a little bit of help understanding the subtleties of the descriptor protocol in Python, as it relates specifically to the behavior of staticmethod objects. I'll start with a trivial example, and then iteratively expand it, examining it's behavior at each step: class Stub: @staticmethod def do_things(): """Call this like Stub.do_things(), with no arguments or instance.""" print "Doing things!" At this point, this behaves as expected, but what's going on here is a bit subtle: When you call Stub.do_things(), you are not invoking do_things directly. Instead, Stub.do_things refers to a staticmethod instance, which has wrapped the function we want up inside it's own descriptor protocol such that you are actually invoking staticmethod.__get__, which first returns the function that we want, and then gets called afterwards. >>> Stub <class __main__.Stub at 0x...> >>> Stub.do_things <function do_things at 0x...> >>> Stub.__dict__['do_things'] <staticmethod object at 0x...> >>> Stub.do_things() Doing things! So far so good. Next, I need to wrap the class in a decorator that will be used to customize class instantiation -- the decorator will determine whether to allow new instantiations or provide cached instances: def deco(cls): def factory(*args, **kwargs): # pretend there is some logic here determining # whether to make a new instance or not return cls(*args, **kwargs) return factory @deco class Stub: @staticmethod def do_things(): """Call this like Stub.do_things(), with no arguments or instance.""" print "Doing things!" Now, naturally this part as-is would be expected to break staticmethods, because the class is now hidden behind it's decorator, ie, Stub not a class at all, but an instance of factory that is able to produce instances of Stub when you call it. Indeed: >>> Stub <function factory at 0x...> >>> Stub.do_things Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'function' object has no attribute 'do_things' >>> Stub() <__main__.Stub instance at 0x...> >>> Stub().do_things <function do_things at 0x...> >>> Stub().do_things() Doing things! So far I understand what's happening here. My goal is to restore the ability for staticmethods to function as you would expect them to, even though the class is wrapped. As luck would have it, the Python stdlib includes something called functools, which provides some tools just for this purpose, ie, making functions behave more like other functions that they wrap. So I change my decorator to look like this: def deco(cls): @functools.wraps(cls) def factory(*args, **kwargs): # pretend there is some logic here determining # whether to make a new instance or not return cls(*args, **kwargs) return factory Now, things start to get interesting: >>> Stub <function Stub at 0x...> >>> Stub.do_things <staticmethod object at 0x...> >>> Stub.do_things() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'staticmethod' object is not callable >>> Stub() <__main__.Stub instance at 0x...> >>> Stub().do_things <function do_things at 0x...> >>> Stub().do_things() Doing things! Wait.... what? functools copies the staticmethod over to the wrapping function, but it's not callable? Why not? What did I miss here? I was playing around with this for a bit and I actually came up with my own reimplementation of staticmethod that allows it to function in this situation, but I don't really understand why it was necessary or if this is even the best solution to this problem. Here's the complete example: class staticmethod(object): """Make @staticmethods play nice with decorated classes.""" def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): """Provide the expected behavior inside decorated classes.""" return self.func(*args, **kwargs) def __get__(self, obj, objtype=None): """Re-implement the standard behavior for undecorated classes.""" return self.func def deco(cls): @functools.wraps(cls) def factory(*args, **kwargs): # pretend there is some logic here determining # whether to make a new instance or not return cls(*args, **kwargs) return factory @deco class Stub: @staticmethod def do_things(): """Call this like Stub.do_things(), with no arguments or instance.""" print "Doing things!" Indeed it works exactly as expected: >>> Stub <function Stub at 0x...> >>> Stub.do_things <__main__.staticmethod object at 0x...> >>> Stub.do_things() Doing things! >>> Stub() <__main__.Stub instance at 0x...> >>> Stub().do_things <function do_things at 0x...> >>> Stub().do_things() Doing things! What approach would you take to make a staticmethod behave as expected inside a decorated class? Is this the best way? Why doesn't the builtin staticmethod implement __call__ on it's own in order for this to just work without any fuss? Thanks.

    Read the article

  • String formatting [str.format()] with a dictionary having a key which is a str() of a number

    - by decimus phostle
    Python neophyte here. I was wondering if someone could help with the KeyError I am getting when using a dictionary for string interpolation in str.format. dictionary = {'key1': 'val1', '1': 'val2'} string1 = 'Interpolating {0[key1]}'.format(dictionary) print string1 The above works fine and yields: Interpolating val1 However doing the following: dictionary = {'key1': 'val1', '1': 'val2'} string2 = 'Interpolating {0[1]}'.format(dictionary) print string2 results in: Traceback (most recent call last): File "test.py", line 3, in <module> string2 = 'Interpolating {0[1]}'.format(dictionary) KeyError: 1L So the problem seems to be in the interpretation of the numeric key as a list index, IMHO. Is there any way to work around this? (i.e. convey that this is instead a dictionary key) TIA and apologies if this question has been asked before(couldn't find anything relevant with my search-fu).

    Read the article

  • Print number in engineering format

    - by jmurrayufo
    I am trying to print a number into engineering format with python, but I cannot seem to get it to work. The syntax SEEMS simple enough, but it just doesn't work. >>> import decimal >>> x = decimal.Decimal(1000000) >>> print x 1000000 >>>> print x.to_eng_string() 1000000 I cannot figure out why this is. The two values are not equal (one is a string, the other is an int). Setting various contexts in decimal doesn't seem to help either. Any clues or ideas?

    Read the article

  • python Velocity control of the player, why doesn't this work?

    - by Dominic Grenier
    I have the following code inside a while True loop: if abs(playerx) < MAXSPEED: if moveLeft: playerx -= 1 if moveRight: playerx += 1 if abs(playery) < MAXSPEED: if moveDown: playery += 1 if moveUp: playery -= 1 if moveLeft == False and abs(playerx) > 0: playerx += 1 if moveRight == False and abs(playerx) > 0: playerx -= 1 if moveUp == False and abs(playery) > 0: playery += 1 if moveDown == False and abs(playery) > 0: playery -= 1 player.x += playerx player.y += playery if player.left < 0 or player.right > 1000: player.x -= playerx if player.top < 0 or player.bottom > 600: player.y -= playery The intended result is that while an arrow key is pressed, playerx or y increments by one at every loop until it reaches MAXSPEED and stays at MAXSPEED. And that when the player stops pressing that arrow key, his speed decreases. Until it reaches 0. To me, this code explicitly says that... But what actually happens is that playerx or y keeps incrementing regardless of MAXSPEED and continues moving even after the player stops pressing the arrow key. I keep rereading but I'm completely baffled by this weird behavior. Any insights? Thanks.

    Read the article

  • How to resolve "dpkg: error processing /var/cache/apt/archives/python-apport_2.0.1-0ubuntu9_all.deb"?

    - by raz7588
    Update Manager will not update although I have over 100 updates to do I get a error message like this: installArchives() failed: Extracting templates from packages: 29%% Extracting templates from packages: 58%% Extracting templates from packages: 88%% Extracting templates from packages: 100%% Preconfiguring packages ... Extracting templates from packages: 29%% Extracting templates from packages: 58%% Extracting templates from packages: 88%% Extracting templates from packages: 100%% Preconfiguring packages ... Extracting templates from packages: 29%% Extracting templates from packages: 58%% Extracting templates from packages: 88%% Extracting templates from packages: 100%% Preconfiguring packages ... Extracting templates from packages: 29%% Extracting templates from packages: 58%% Extracting templates from packages: 88%% Extracting templates from packages: 100%% Preconfiguring packages ... (Reading database ... (Reading database ... 5%% (Reading database ... 10%% (Reading database ... 15%% (Reading database ... 20%% (Reading database ... 25%% (Reading database ... 30%% (Reading database ... 35%% (Reading database ... 40%% (Reading database ... 45%% (Reading database ... 50%% (Reading database ... 55%% (Reading database ... 60%% (Reading database ... 65%% (Reading database ... 70%% (Reading database ... 75%% (Reading database ... 80%% (Reading database ... 85%% (Reading database ... 90%% (Reading database ... 95%% (Reading database ... 100%% (Reading database ... 189751 files and directories currently installed.) Preparing to replace python-problem-report 2.0.1-0ubuntu7 (using .../python-problem-report_2.0.1-0ubuntu9_all.deb) ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: warning: subprocess old pre-removal script returned error exit status 1 dpkg - trying script from the new package instead ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error processing /var/cache/apt/archives/python-problem-report_2.0.1-0ubuntu9_all.deb (--unpack): subprocess new pre-removal script returned error exit status 1 No apport report written because MaxReports is reached already Traceback (most recent call last): File "/usr/bin/pycompile", line 39, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error while cleaning up: subprocess installed post-installation script returned error exit status 1 Preparing to replace python-apport 2.0.1-0ubuntu7 (using .../python-apport_2.0.1-0ubuntu9_all.deb) ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: warning: subprocess old pre-removal script returned error exit status 1 dpkg - trying script from the new package instead ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error processing /var/cache/apt/archives/python-apport_2.0.1-0ubuntu9_all.deb (--unpack): subprocess new pre-removal script returned error exit status 1 No apport report written because MaxReports is reached already Traceback (most recent call last): File "/usr/bin/pycompile", line 39, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error while cleaning up: subprocess installed post-installation script returned error exit status 1 Preparing to replace apport 2.0.1-0ubuntu7 (using .../apport_2.0.1-0ubuntu9_all.deb) ... apport stop/waiting Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: warning: subprocess old pre-removal script returned error exit status 1 dpkg - trying script from the new package instead ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error processing /var/cache/apt/archives/apport_2.0.1-0ubuntu9_all.deb (--unpack): subprocess new pre-removal script returned error exit status 1 No apport report written because MaxReports is reached already apport start/running Traceback (most recent call last): File "/usr/bin/pycompile", line 39, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error while cleaning up: subprocess installed post-installation script returned error exit status 1 Preparing to replace gnome-orca 3.4.1-0ubuntu0.1 (using .../gnome-orca_3.4.2-0ubuntu0.1_all.deb) ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: warning: subprocess old pre-removal script returned error exit status 1 dpkg - trying script from the new package instead ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error processing /var/cache/apt/archives/gnome-orca_3.4.2-0ubuntu0.1_all.deb (--unpack): subprocess new pre-removal script returned error exit status 1 No apport report written because MaxReports is reached already Traceback (most recent call last): File "/usr/bin/pycompile", line 39, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error while cleaning up: subprocess installed post-installation script returned error exit status 1 Preparing to replace python-piston-mini-client 0.7.2-0ubuntu1 (using .../python-piston-mini-client_0.7.2+bzr57-0ubuntu1_all.deb) ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: warning: subprocess old pre-removal script returned error exit status 1 dpkg - trying script from the new package instead ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error processing /var/cache/apt/archives/python-piston-mini-client_0.7.2+bzr57-0ubuntu1_all.deb (--unpack): subprocess new pre-removal script returned error exit status 1 No apport report written because MaxReports is reached already Traceback (most recent call last): File "/usr/bin/pycompile", line 39, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error while cleaning up: subprocess installed post-installation script returned error exit status 1 Preparing to replace oneconf 0.2.8 (using .../oneconf_0.2.8.1_all.deb) ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: warning: subprocess old pre-removal script returned error exit status 1 dpkg - trying script from the new package instead ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error processing /var/cache/apt/archives/oneconf_0.2.8.1_all.deb (--unpack): subprocess new pre-removal script returned error exit status 1 No apport report written because MaxReports is reached already Traceback (most recent call last): File "/usr/bin/pycompile", line 39, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error while cleaning up: subprocess installed post-installation script returned error exit status 1 Preparing to replace software-center 5.2.2 (using .../software-center_5.2.2.2_all.deb) ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: warning: subprocess old pre-removal script returned error exit status 1 dpkg - trying script from the new package instead ... Traceback (most recent call last): File "/usr/bin/pyclean", line 33, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error processing /var/cache/apt/archives/software-center_5.2.2.2_all.deb (--unpack): subprocess new pre-removal script returned error exit status 1 No apport report written because MaxReports is reached already Traceback (most recent call last): File "/usr/bin/pycompile", line 39, in <module> from debpython.namespace import add_namespace_files ValueError: bad marshal data (unknown type code) dpkg: error while cleaning up: subprocess installed post-installation script returned error exit status 1 Preparing to replace libglade2-0 1:2.6.4-1ubuntu1 (using .../libglade2-0_1%%3a2.6.4-1ubuntu1.1_amd64.deb) ... Unpacking replacement libglade2-0 ... Preparing to replace libv4l-0 0.8.6-1ubuntu1 (using .../libv4l-0_0.8.6-1ubuntu2_amd64.deb) ... De-configuring libv4l-0:i386 ... Unpacking replacement libv4l-0 ... Preparing to replace libv4l-0:i386 0.8.6-1ubuntu1 (using .../libv4l-0_0.8.6-1ubuntu2_i386.deb) ... Unpacking replacement libv4l-0:i386 ... Preparing to replace libv4lconvert0:i386 0.8.6-1ubuntu1 (using .../libv4lconvert0_0.8.6-1ubuntu2_i386.deb) ... De-configuring libv4lconvert0 ... Unpacking replacement libv4lconvert0:i386 ... Preparing to replace libv4lconvert0 0.8.6-1ubuntu1 (using .../libv4lconvert0_0.8.6-1ubuntu2_amd64.deb) ... Unpacking replacement libv4lconvert0 ... Errors were encountered while processing: /var/cache/apt/archives/python-problem-report_2.0.1-0ubuntu9_all.deb /var/cache/apt/archives/python-apport_2.0.1-0ubuntu9_all.deb /var/cache/apt/archives/apport_2.0.1-0ubuntu9_all.deb /var/cache/apt/archives/gnome-orca_3.4.2-0ubuntu0.1_all.deb /var/cache/apt/archives/python-piston-mini-client_0.7.2+bzr57-0ubuntu1_all.deb /var/cache/apt/archives/oneconf_0.2.8.1_all.deb /var/cache/apt/archives/software-center_5.2.2.2_all.deb Error in function: SystemError: E:Sub-process /usr/bin/dpkg returned an error code (1) Setting up libglade2-0 (1:2.6.4-1ubuntu1.1) ... dpkg: error processing gnome-orca (--configure): Package is in a very bad inconsistent state - you should reinstall it before attempting configuration. dpkg: error processing python-problem-report (--configure): Package is in a very bad inconsistent state - you should reinstall it before attempting configuration. Setting up libv4lconvert0 (0.8.6-1ubuntu2) ... Setting up libv4lconvert0:i386 (0.8.6-1ubuntu2) ... dpkg: error processing python-piston-mini-client (--configure): Package is in a very bad inconsistent state - you should reinstall it before attempting configuration. Setting up libv4l-0 (0.8.6-1ubuntu2) ... Setting up libv4l-0:i386 (0.8.6-1ubuntu2) ... dpkg: dependency problems prevent configuration of python-apport: python-apport depends on python-problem-report (>= 0.94); however: Package python-problem-report is not configured yet. dpkg: error processing python-apport (--configure): dependency problems - leaving unconfigured dpkg: dependency problems prevent configuration of software-center: software-center depends on python-piston-mini-client (>= 0.1+bzr29); however: Package python-piston-mini-client is not configured yet. dpkg: error processing software-center (--configure): dependency problems - leaving unconfigured dpkg: dependency problems prevent configuration of oneconf: oneconf depends on python-piston-mini-client (>= 0.3+bzr32-0ubuntu1); however: Package python-piston-mini-client is not configured yet. dpkg: error processing oneconf (--configure): dependency problems - leaving unconfigured dpkg: dependency problems prevent configuration of apport: apport depends on python-apport (>= 2.0.1-0ubuntu7); however: Package python-apport is not configured yet. dpkg: error processing apport (--configure): dependency problems - leaving unconfigured Processing triggers for libc-bin ... ldconfig deferred processing now taking place This has been going on for two weeks now and I cannot get any updates. Any help would be great.

    Read the article

  • Is this an acceptable approach to undo/redo in Python?

    - by Codemonkey
    I'm making an application (wxPython) to process some data from Excel documents. I want the user to be able to undo and redo actions, even gigantic actions like processing the contents of 10 000 cells simultaneously. I Googled the topic, and all the solutions I could find involves a lot of black magic or is overly complicated. Here is how I imagine my simple undo/redo scheme. I write two classes - one called ActionStack and an abstract one called Action. Every "undoable" operation must be a subclass of Action and define the methods do and undo. The Action subclass is passed the instance of the "document", or data model, and is responsible for committing the operation and remembering how to undo the change. Now, every document is associated with an instance of the ActionStack. The ActionStack maintains a stack of actions (surprise!). Every time actions are undone and new actions are performed, all undone actions are removed for ever. The ActionStack will also automatically remove the oldest Action when the stack reaches the configurable maximum amount. I imagine the workflow would produce code looking something like this: class TableDocument(object): def __init__(self, table): self.table = table self.action_stack = ActionStack(history_limit=50) # ... def delete_cells(self, cells): self.action_stack.push( DeleteAction(self, cells) ) def add_column(self, index, name=''): self.action_stack.push( AddColumnAction(self, index, name) ) # ... def undo(self, count=1): self.action_stack.undo(count) def redo(self, count=1): self.action_stack.redo(count) Given that none of the methods I've found are this simple, I thought I'd get the experts' opinion before I go ahead with this plan. More specifically, what I'm wondering about is - are there any glaring holes in this plan that I'm not seeing?

    Read the article

< Previous Page | 86 87 88 89 90 91 92 93 94 95 96 97  | Next Page >