content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Get an IP adress of a client of a SOAP service I'm writing a SOAP service using python and soaplib. I need to get IP adresses of all clients of the service to store them to the log file. How can I do that? A: One way to do this is to implement a "hook" which is called at different stages of the wsgi executation. See the section "Hooks" in the soaplib readme file for details and the example hook.py in that distribution. For example, you could implement onMethodExec and then use the wsgi environ.get('REMOTE_ADDR') to obtain the client's IP address and log it.
Get an IP adress of a client of a SOAP service
I'm writing a SOAP service using python and soaplib. I need to get IP adresses of all clients of the service to store them to the log file. How can I do that?
[ "One way to do this is to implement a \"hook\" which is called at different stages of the wsgi executation. See the section \"Hooks\" in the soaplib readme file for details and the example hook.py in that distribution. \nFor example, you could implement onMethodExec and then use the wsgi environ.get('REMOTE_ADDR'...
[ 1 ]
[]
[]
[ "python", "soap" ]
stackoverflow_0003253036_python_soap.txt
Q: python 2.x or 3.x Since there is a python 3.x, why don't we use it? Why do we still use 2.x?What's the difference? A: Python 2.6 and 2.7 have been written to ease the transition to Python 3. It will take some more time to port the more complex packages (i.e. those with many dependencies, or libraries written in C). So if you are starting new projects, and all the libraries you need are there, it makes sense to start with 3.1. One of the more welcome changes is the handling of Unicode strings by default - it will prevent a lot of bugs. But if you were to port a complete ERP application, or anything big, from 2.6 to 3.x, it could be a bloodbath right now. The unicode changes for instance are the hardest to apply from 2.x -> 3.x, and the low level C APIs have changed a lot as well. A: Because 3.x isn't backwards compatible with 2.x and a lot of apps and libraries are written for the 2.x series. 3.x was their attempt at cleaning up all the crud that never should have been in Python in the first place.... and they had to make some breaking changes. Probably best to stick with 2.x for now, til 3.x gains a bit more popularity. A: The biggest differences are listed in the documentation of Python. Hth. :) A: If you're writing a new app, and don't rely on libraries that have no 3.x support yet, I suggest you go for 3.x. Let's create some critical mass :) Take a look at the python 3 documentation itself A: Because lots of libraries are not yet ported to 3.x I guess... And because lots of application still run on 2.x
python 2.x or 3.x
Since there is a python 3.x, why don't we use it? Why do we still use 2.x?What's the difference?
[ "Python 2.6 and 2.7 have been written to ease the transition to Python 3.\nIt will take some more time to port the more complex packages (i.e. those with many dependencies, or libraries written in C).\nSo if you are starting new projects, and all the libraries you need are there, it makes sense to start with 3.1. O...
[ 14, 8, 6, 5, 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0003253430_python_python_3.x.txt
Q: Need some advice regarding writing an reusable app for Django I need to implement a finite-state-machine in order to keep track of a few of my Django project models. I already have a similar app doing that but it's heavily coupled with the others apps models and not reusable in any way. So I decided to re-factor it. After a few hours, this is what I came up with: class StateMachine(models.Model): name = models.CharField(max_length=50, help_text="Must be an unique name") template = models.BooleanField(default=True) current_state = models.ForeignKey('State', blank=True, null=True, related_name='current_state') initial_state = models.ForeignKey('State', blank=True, null=True, related_name='initial_state') def get_valid_actions(self): return Action.objects.filter(machine=self, from_state=self.current_state) def copy(self): ... class State(models.Model): name = models.CharField(max_length=50) machine = models.ForeignKey(StateMachine) def enter_hook(self, machine=None, action=None, state=None): pass def exit_hook(self, machine=None, action=None, state=None): pass def _copy(self, machine): ... class Action(models.Model): name = models.CharField(max_length=50) machine = models.ForeignKey(StateMachine) from_state = models.ForeignKey(State, related_name='from_state') to_state = models.ForeignKey(State, blank=True, null=True, related_name='to_state') def is_valid(self): if self.machine.current_state == self.from_state: return True else: return False def act(self): if self.is_valid(): self.from_state.exit_hook(machine=self.machine, action=self, state=self.from_state) self.machine.current_state = self.to_state self.machine.save() self.to_state.enter_hook(machine=self.machine, action=self, state=self.to_state) else: raise ActionNotApplicable() return self.machine def _copy(self, machine): ... I am happy with the results. It does what a state machine is expected to do and nothing else. In my models I am using it like this: class SampleModel(models.Model): machine = models.ForeignKey(StateMachine, null=True) def setup_machine(self): self.machine = StateMachine.objects.get(template=True, name='bla bla bla').copy() self.save() I basically create a "template" machine using the admin interface and then I run copy method which copies the state machine model and sets the template to False. Now, here comes my questions :) Is using a ForeignKey in the SampleModel the best way to attach the StateMachine to it? I've read about Generic Relations in Django but I've never used it before. Using it would be beneficial in my scenario? I am trying to follow the "Do one thing and do it well" philosophy, but I've other business requirements to implement. For example, I need to send to send an e-mail to a specific group every time a state changes, and this group varies from state to state. The first solution I came up was to add an "email" field in the state model. But this would violate what this app proposes to do which is simply to keep track of a state machine. What would be the best way to solve this problem? I also include some hook functions in the model so that someone could attach custom behavior later, is this the best way to do it? (I think Django was already a signal system) Any other ideas/comments? I am new to this reusable apps thing :) Thanks! A: I implemented myself a finite-state machine in python ... The code of the machine module itself has no Django... However, this machine was used to manage a state attribute on a Django model. I think that the only field you really need to have is a state field. The rest should be only python declarations (unless you have a particular reason to save everything in your database). Here is this finite-state machine stuff, you can take ideas from it, or even take the whole code and refactor it. There is very good documentation, and I think it is pretty clean and simple : http://dl.dropbox.com/u/1869644/state_automaton.zip (and you can generate diagrams to dot format !!!) EDIT : I wanna be able to link a particular state to an user In this case (if you want to keep it generic) put the users field in a subclass of your state automaton. For example : class UserAlertStateAutomaton(FiniteStateAutomaton): """ An automaton that alerts users when the state changes """ users_to_alert = models.ManyToManyField(User) def change_state(self, new_state): """ overrides the parent method to alert users that state has changed """ super(UserAlertStateAutomaton, self).change_state(new_state) for user in self.users_to_alert: #do your thing def subscribe#... etc Which would still mean that you don't need to save anything else than the state in the base state automaton class. And by implementing a system of hooks (execute a method X when transition from state A to state B), you can pretty much do anything, and very simply : check the code I sent you !
Need some advice regarding writing an reusable app for Django
I need to implement a finite-state-machine in order to keep track of a few of my Django project models. I already have a similar app doing that but it's heavily coupled with the others apps models and not reusable in any way. So I decided to re-factor it. After a few hours, this is what I came up with: class StateMachine(models.Model): name = models.CharField(max_length=50, help_text="Must be an unique name") template = models.BooleanField(default=True) current_state = models.ForeignKey('State', blank=True, null=True, related_name='current_state') initial_state = models.ForeignKey('State', blank=True, null=True, related_name='initial_state') def get_valid_actions(self): return Action.objects.filter(machine=self, from_state=self.current_state) def copy(self): ... class State(models.Model): name = models.CharField(max_length=50) machine = models.ForeignKey(StateMachine) def enter_hook(self, machine=None, action=None, state=None): pass def exit_hook(self, machine=None, action=None, state=None): pass def _copy(self, machine): ... class Action(models.Model): name = models.CharField(max_length=50) machine = models.ForeignKey(StateMachine) from_state = models.ForeignKey(State, related_name='from_state') to_state = models.ForeignKey(State, blank=True, null=True, related_name='to_state') def is_valid(self): if self.machine.current_state == self.from_state: return True else: return False def act(self): if self.is_valid(): self.from_state.exit_hook(machine=self.machine, action=self, state=self.from_state) self.machine.current_state = self.to_state self.machine.save() self.to_state.enter_hook(machine=self.machine, action=self, state=self.to_state) else: raise ActionNotApplicable() return self.machine def _copy(self, machine): ... I am happy with the results. It does what a state machine is expected to do and nothing else. In my models I am using it like this: class SampleModel(models.Model): machine = models.ForeignKey(StateMachine, null=True) def setup_machine(self): self.machine = StateMachine.objects.get(template=True, name='bla bla bla').copy() self.save() I basically create a "template" machine using the admin interface and then I run copy method which copies the state machine model and sets the template to False. Now, here comes my questions :) Is using a ForeignKey in the SampleModel the best way to attach the StateMachine to it? I've read about Generic Relations in Django but I've never used it before. Using it would be beneficial in my scenario? I am trying to follow the "Do one thing and do it well" philosophy, but I've other business requirements to implement. For example, I need to send to send an e-mail to a specific group every time a state changes, and this group varies from state to state. The first solution I came up was to add an "email" field in the state model. But this would violate what this app proposes to do which is simply to keep track of a state machine. What would be the best way to solve this problem? I also include some hook functions in the model so that someone could attach custom behavior later, is this the best way to do it? (I think Django was already a signal system) Any other ideas/comments? I am new to this reusable apps thing :) Thanks!
[ "I implemented myself a finite-state machine in python ... The code of the machine module itself has no Django... However, this machine was used to manage a state attribute on a Django model.\nI think that the only field you really need to have is a state field. The rest should be only python declarations (unless y...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003253235_django_python.txt
Q: Pass list as argument to Python C module? I found this nice example of a Python C Module, where a single integer is passed along as the only argument. How can I instead pass a python list as argument? A: From http://code.activestate.com/lists/python-list/31841/: ... char * tok; /* delimiter tokens for strtok */ int cols; /* number of cols to parse, from the left */ int numLines; /* how many lines we passed for parsing */ char * line; /* pointer to the line as a string */ char * token; /* token parsed by strtok */ PyObject * listObj; /* the list of strings */ PyObject * strObj; /* one string in the list */ /* the O! parses for a Python object (listObj) checked to be of type PyList_Type */ if (! PyArg_ParseTuple( args, "O!is", &PyList_Type, &listObj, &cols, &tok )) return NULL; /* get the number of lines passed to us */ numLines = PyList_Size(listObj); /* should raise an error here. */ if (numLines < 0) return NULL; /* Not a list */ ... /* iterate over items of the list, grabbing strings, and parsing for numbers */ for (i=0; i<numLines; i++){ /* grab the string object from the next element of the list */ strObj = PyList_GetItem(listObj, i); /* Can't fail */ /* make it a string */ line = PyString_AsString( strObj ); /* now do the parsing */ See Parsing arguments and building values A: Use one of the O arguments and the sequence protocol.
Pass list as argument to Python C module?
I found this nice example of a Python C Module, where a single integer is passed along as the only argument. How can I instead pass a python list as argument?
[ "From http://code.activestate.com/lists/python-list/31841/:\n...\nchar * tok; /* delimiter tokens for strtok */\nint cols; /* number of cols to parse, from the left */\n\nint numLines; /* how many lines we passed for parsing */\nchar * line; /* pointer to the line as a string */\nchar...
[ 16, 0 ]
[]
[]
[ "arguments", "c", "integration", "list", "python" ]
stackoverflow_0003253563_arguments_c_integration_list_python.txt
Q: Django Test Client Like Tool? I've got to know and love the Django Test client. I'd really like to use it to test external sites and URLs outside of the current project. Is this possible? If not, is there something similar I could use? (ideally in Python) I don't need to do anything dramatic, just, say, grab a URL and check the status code, check that it took less than x seconds, and that it contains some text. Ideally I'd like it so that I could run/trigger these tests from some sort of hosted web app, and also have them run at certain intervals. I realise it wouldn't take too much to roll something myself, but I'd prefer to jump onboard something which already exists so wanted to check what the options were before I do so. Thanks loads. Rolo. A: No, it doesn't work like that. It's not a real web client, it's just a piece of internal Django code that catches the request and returns the relevant response. The best tool for the sort of testing you're talking about is something like Selenium.
Django Test Client Like Tool?
I've got to know and love the Django Test client. I'd really like to use it to test external sites and URLs outside of the current project. Is this possible? If not, is there something similar I could use? (ideally in Python) I don't need to do anything dramatic, just, say, grab a URL and check the status code, check that it took less than x seconds, and that it contains some text. Ideally I'd like it so that I could run/trigger these tests from some sort of hosted web app, and also have them run at certain intervals. I realise it wouldn't take too much to roll something myself, but I'd prefer to jump onboard something which already exists so wanted to check what the options were before I do so. Thanks loads. Rolo.
[ "No, it doesn't work like that. It's not a real web client, it's just a piece of internal Django code that catches the request and returns the relevant response.\nThe best tool for the sort of testing you're talking about is something like Selenium.\n" ]
[ 3 ]
[]
[]
[ "django", "python", "testing" ]
stackoverflow_0003253747_django_python_testing.txt
Q: Eclipse using multiple Python interpreters with execnet I'm using the execnet package to allow communication between Python scripts interpreted by different Python interpreters. The following code (test_execnet.py): import execnet for python_version in ('python', 'python3'): try: gw = execnet.makegateway("popen//python="+python_version) ch = gw.remote_exec('channel.send(1/3)') res = ch.receive() print(python_version, ': ', res, sep ="") except: print('problems with ', python_version) Runs perfectly in the command-line Terminal, showing the following output: $ python3 test_execnet.py python: 0 python3: 0.333333333333 However, if I try to run the same code from within the Eclipse IDE, I get the following error: 'import site' failed; use -v for traceback Traceback (most recent call last): File "<string>", line 1, in <module> File "<string>", line 4, in <module> File "<string>", line 2, in <module> File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/site-packages/execnet/gateway_base.py", line 8, in <module> import sys, os, weakref File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/os.py", line 380, in <module> from _abcoll import MutableMapping # Can't use collections (bootstrap) File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/_abcoll.py", line 54 class Hashable(metaclass=ABCMeta): ^ SyntaxError: invalid syntax problems with python problems with python3 NOTE: Eclipse Version: 3.6.0 PyDev Interpreter configured for the project: python3 "Preferences/Interpreter - Python"'s Python Interpreters: python (/usr/bin/python) python3 (/Library/Frameworks/Python.Framework/Versions/3.1/Resources/Python.app/Contents/MacOS/Python EDIT: I write a code to show the os.environ like this: for python_version in ('python', 'python3'): try: import os for item in os.environ: print(item, '= ', os.environ[item]) except: print('problems with ', python_version) I got the following outputs: eclipse_output.txt terminal_output.txt A FileMerge comparison of the files can be found at eclipse_output.txt vs. terminal_output.pdf. Any hints? Thanks A: seems like pydev does site-customizations and particularly modifies things for interactive/console usage (judging from a very quick skim of http://github.com/aptana/Pydev/blob/master/plugins/org.python.pydev/pysrc/pydev_sitecustomize/sitecustomize.py ). This is not useful or fitting for execnet-mediated processes. You could try to "del os.environ['PYTHONPATH']" before you invoke execnet.makegateway, or, to be more careful, just delete the sitecustomize part of it. hth, holger A: 'import site' failed; use -v for traceback I have seen that when python was unable to find its landmark. Which that indicates there is a PYTHONHOME problem. Check out http://docs.python.org/using/cmdline.html#envvar-PYTHONHOME maybe eclipse is screwing your environment up. Edit: Looked at your env dumps, looks like eclipse is definitely messing with PYTHONPATH, which will cause your child python processes to not work correctly. Basically what you have going on here is eclipse starts a python v2 instance with a PYTHONPATH pointing to the python v2 directories. Then you spawn a python v3 process which tries to load its landmark from the python v2 directories... You need to find a way to have eclipse not mess with the PYTHONPATH. I am not sure what eclipse is trying to do by doing that, but it is certainly no friend when you want to spawn new python processes.
Eclipse using multiple Python interpreters with execnet
I'm using the execnet package to allow communication between Python scripts interpreted by different Python interpreters. The following code (test_execnet.py): import execnet for python_version in ('python', 'python3'): try: gw = execnet.makegateway("popen//python="+python_version) ch = gw.remote_exec('channel.send(1/3)') res = ch.receive() print(python_version, ': ', res, sep ="") except: print('problems with ', python_version) Runs perfectly in the command-line Terminal, showing the following output: $ python3 test_execnet.py python: 0 python3: 0.333333333333 However, if I try to run the same code from within the Eclipse IDE, I get the following error: 'import site' failed; use -v for traceback Traceback (most recent call last): File "<string>", line 1, in <module> File "<string>", line 4, in <module> File "<string>", line 2, in <module> File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/site-packages/execnet/gateway_base.py", line 8, in <module> import sys, os, weakref File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/os.py", line 380, in <module> from _abcoll import MutableMapping # Can't use collections (bootstrap) File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/_abcoll.py", line 54 class Hashable(metaclass=ABCMeta): ^ SyntaxError: invalid syntax problems with python problems with python3 NOTE: Eclipse Version: 3.6.0 PyDev Interpreter configured for the project: python3 "Preferences/Interpreter - Python"'s Python Interpreters: python (/usr/bin/python) python3 (/Library/Frameworks/Python.Framework/Versions/3.1/Resources/Python.app/Contents/MacOS/Python EDIT: I write a code to show the os.environ like this: for python_version in ('python', 'python3'): try: import os for item in os.environ: print(item, '= ', os.environ[item]) except: print('problems with ', python_version) I got the following outputs: eclipse_output.txt terminal_output.txt A FileMerge comparison of the files can be found at eclipse_output.txt vs. terminal_output.pdf. Any hints? Thanks
[ "seems like pydev does site-customizations and particularly modifies things for interactive/console usage (judging from a very quick skim of http://github.com/aptana/Pydev/blob/master/plugins/org.python.pydev/pysrc/pydev_sitecustomize/sitecustomize.py ). This is not useful or fitting for execnet-mediated processes....
[ 3, 1 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0003248271_eclipse_pydev_python.txt
Q: Python copy : How to inherit the default copying behaviour? Ok ... It might be a stupid question ... but I'm not finding the answer right now ! I need to realize the copy of an object, for which I want all the attributes to be copied, except one or two for which I want to fully control the copy. Here is the standard copying behaviour for an object : >>> class test(object): ... def __init__(self, arg): ... self._a = arg ... >>> t = test(123999) >>> t._a 123999 >>> tc = copy.copy(t) >>> tc._a 123999 Which basically means that all the attributes are copied. What I would like to do is re-use this behaviour in the following way : >>> class test(object): ... def __init__(self, arga, argb): ... self._a = arga ... self._b = argb ... ... def __copy__(self): ... obj_copy = copy.copy(self) #NOT POSSIBLE OF COURSE => infinite recursion ... obj_copy._b = my_operation(obj_copy._b) ... return obj_copy I hope you got the point : I want to re-use the object copying behaviour, but hook-in my own operations. Is there a clean way to do this (without having to do for attr_name in dir(self): ...) ??? A: You could just do: def __copy__(self): clone = copy.deepcopy(self) clone._b = some_op(clone._b) return clone This will work because deepcopy avoids recursion. From the python docs: The deepcopy() function avoids these problems by: keeping a “memo” dictionary of objects already copied during the current copying pass; and letting user-defined classes override the copying operation or the set of components copied. A: If you don't have properties &c, all the state is in the __dict__, so...: ... def __copy__(self): ... obj_copy = object.__new__(type(self)) ... obj_copy.__dict__ = self.__dict__.copy() ... obj_copy._b = my_operation(obj_copy._b) ... return obj_copy A: I would like to do this in the following way - try it: import copy class test(object): def __init__(self, **args): self.args = args def __copy__(self): obj_copy = copy.deepcopy(self) return obj_copy
Python copy : How to inherit the default copying behaviour?
Ok ... It might be a stupid question ... but I'm not finding the answer right now ! I need to realize the copy of an object, for which I want all the attributes to be copied, except one or two for which I want to fully control the copy. Here is the standard copying behaviour for an object : >>> class test(object): ... def __init__(self, arg): ... self._a = arg ... >>> t = test(123999) >>> t._a 123999 >>> tc = copy.copy(t) >>> tc._a 123999 Which basically means that all the attributes are copied. What I would like to do is re-use this behaviour in the following way : >>> class test(object): ... def __init__(self, arga, argb): ... self._a = arga ... self._b = argb ... ... def __copy__(self): ... obj_copy = copy.copy(self) #NOT POSSIBLE OF COURSE => infinite recursion ... obj_copy._b = my_operation(obj_copy._b) ... return obj_copy I hope you got the point : I want to re-use the object copying behaviour, but hook-in my own operations. Is there a clean way to do this (without having to do for attr_name in dir(self): ...) ???
[ "You could just do:\ndef __copy__(self):\n clone = copy.deepcopy(self)\n clone._b = some_op(clone._b)\n return clone\n\nThis will work because deepcopy avoids recursion. From the python docs:\n\nThe deepcopy() function avoids these problems by:\n keeping a “memo” dictionary of objects already copied duri...
[ 5, 3, 2 ]
[]
[]
[ "copy", "python" ]
stackoverflow_0003253439_copy_python.txt
Q: How to get only text of a webpage with Python, just as Select-all & Copy in browser? I want to get "Main content" instead of < tag> Main content , where the latter is html code and could be retrieved using urllib.urlopen(url). Just as you open the url in browser, select all text and then copy&paste. Is there a possible way for this with Python? Thanks. A: Have a look at Beautiful Soup. Beautiful Soup is a Python HTML/XML parser designed for quick turnaround projects like screen-scraping. Three features make it powerful: Beautiful Soup won't choke if you give it bad markup. It yields a parse tree that makes approximately as much sense as your original document. This is usually good enough to collect the data you need and run away. Beautiful Soup provides a few simple methods and Pythonic idioms for navigating, searching, and modifying a parse tree: a toolkit for dissecting a document and extracting what you need. You don't have to create a custom parser for each application. Beautiful Soup automatically converts incoming documents to Unicode and outgoing documents to UTF-8. You don't have to think about encodings, unless the document doesn't specify an encoding and Beautiful Soup can't autodetect one. Then you just have to specify the original encoding.
How to get only text of a webpage with Python, just as Select-all & Copy in browser?
I want to get "Main content" instead of < tag> Main content , where the latter is html code and could be retrieved using urllib.urlopen(url). Just as you open the url in browser, select all text and then copy&paste. Is there a possible way for this with Python? Thanks.
[ "Have a look at Beautiful Soup.\n\nBeautiful Soup is a Python HTML/XML parser designed for quick turnaround projects like screen-scraping. Three features make it powerful:\n\nBeautiful Soup won't choke if you give it bad markup. It yields a parse tree that makes approximately as much sense as your original document...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0003254012_python.txt
Q: Having trouble with py.test remote I love py.test and am trying to get the remote test execution feature to work so I can run tests on a remote machine. There is very little doc and I am getting frustrated with it. Any help figuring out what I am doing wrong is appreciated. Here is my command line on the main server: c:\Python26\Scripts\py.test --dist=each --tx socket=192.168.1.11:8888 tests\test_guest_install.py If I read the doc right, this should push the script to the remote machine and run it. Here's the output on the other side: C:\Users\Dave\Desktop>c:\Python26\python.exe socketserver.py socket_readline_exec_server-1.2 Entering Accept loop ('0.0.0.0', 8888) socket_readline_exec_server-1.2 got new connection from 192.168.1.5 30856 reading line socket_readline_exec_server-1.2 compiled source, executing ============================= test session starts ============================= python: platform win32 -- Python 2.6.4 -- pytest-1.2.0 test object 1: C:\Users\Alan\Desktop\pyexecnetcache ============================== in 0.14 seconds =============================== socket_readline_exec_server-1.2 finished executing code leaving socketserver execloop Traceback (most recent call last): File "socketserver.py", line 90, in <module> startserver(serversock, loop=False) File "socketserver.py", line 81, in startserver serversock.shutdown(2) File "<string>", line 1, in shutdown socket.error: [Errno 10057] A request to send or receive data was disallowed be ause the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied A: Could you try to rerun with latest versions of pytest and pytest-xdist?
Having trouble with py.test remote
I love py.test and am trying to get the remote test execution feature to work so I can run tests on a remote machine. There is very little doc and I am getting frustrated with it. Any help figuring out what I am doing wrong is appreciated. Here is my command line on the main server: c:\Python26\Scripts\py.test --dist=each --tx socket=192.168.1.11:8888 tests\test_guest_install.py If I read the doc right, this should push the script to the remote machine and run it. Here's the output on the other side: C:\Users\Dave\Desktop>c:\Python26\python.exe socketserver.py socket_readline_exec_server-1.2 Entering Accept loop ('0.0.0.0', 8888) socket_readline_exec_server-1.2 got new connection from 192.168.1.5 30856 reading line socket_readline_exec_server-1.2 compiled source, executing ============================= test session starts ============================= python: platform win32 -- Python 2.6.4 -- pytest-1.2.0 test object 1: C:\Users\Alan\Desktop\pyexecnetcache ============================== in 0.14 seconds =============================== socket_readline_exec_server-1.2 finished executing code leaving socketserver execloop Traceback (most recent call last): File "socketserver.py", line 90, in <module> startserver(serversock, loop=False) File "socketserver.py", line 81, in startserver serversock.shutdown(2) File "<string>", line 1, in shutdown socket.error: [Errno 10057] A request to send or receive data was disallowed be ause the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
[ "Could you try to rerun with latest versions of pytest and pytest-xdist? \n" ]
[ 0 ]
[]
[]
[ "pytest", "python" ]
stackoverflow_0002174238_pytest_python.txt
Q: Python string to attribute How can I achieve such job: def get_foo(someobject, foostring): return someobject.foostring IE: if I do get_foo(obj, "name") it should be calling obj.name (see input as string but I call it as an attritube. Thanks A: Use the builtin function getattr. getattr(object, name[, default]) Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised. A: If someobject has an attribute named foostring then def get_foo(someobject, foostring): return getattr(someobject,foostring) or if you want to set an attribute to the supplied object then: def set_foo(someobject, foostring, value): return setattr(someobject,foostring, value) Try it A: You should use setattr and getattr: setattr(object,'property',value) getattr(object,'property',default)
Python string to attribute
How can I achieve such job: def get_foo(someobject, foostring): return someobject.foostring IE: if I do get_foo(obj, "name") it should be calling obj.name (see input as string but I call it as an attritube. Thanks
[ "Use the builtin function getattr.\n\ngetattr(object, name[, default])\nReturn the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If th...
[ 116, 50, 36 ]
[]
[]
[ "attributes", "python" ]
stackoverflow_0003253966_attributes_python.txt
Q: mod_python.publisher: nothing to publish HI, I get the following error on executing a script: [Thu Jul 15 17:32:02 2010] [error] [client 127.0.0.1] mod_python.publisher: nothing to publish., referer: http://localhost/test/mptest.py/ff What does this mean and how can I resolve this? A: here's some useful information mod_python publisher
mod_python.publisher: nothing to publish
HI, I get the following error on executing a script: [Thu Jul 15 17:32:02 2010] [error] [client 127.0.0.1] mod_python.publisher: nothing to publish., referer: http://localhost/test/mptest.py/ff What does this mean and how can I resolve this?
[ "here's some useful information\nmod_python publisher\n" ]
[ 0 ]
[]
[]
[ "mod_python", "python" ]
stackoverflow_0003254276_mod_python_python.txt
Q: Dumps and loads in django from django.utils.simplejson import dumps, loads # -*- coding: utf-8 -*- def index(request): return render_to_response('test2/index.html') def add_lang(request): logging.debug("Got request") a = request.POST logging.debug(a["lang"]) lang=dumps(a["lang"]) l = Language(code=lang) l.save() lang=loads(lang) logging.debug(loads(l.code)) return render_to_response('test2/test21.html', context_instance=RequestContext(request,{'test2': l.code})) My question is there any way to load the variable back to its original format in the template file.i.e, i want a function similar to loads in template.I do not want to do it in views since there will be a lot of code changes test21.html {{ test2 }} //The above prints"\u0905\u0902\u0917\u094d\u0930\u0947\u091c\u093c\u0940, \u0939\u093f\u0902\u0926" A: Not without writing a custom filter.
Dumps and loads in django
from django.utils.simplejson import dumps, loads # -*- coding: utf-8 -*- def index(request): return render_to_response('test2/index.html') def add_lang(request): logging.debug("Got request") a = request.POST logging.debug(a["lang"]) lang=dumps(a["lang"]) l = Language(code=lang) l.save() lang=loads(lang) logging.debug(loads(l.code)) return render_to_response('test2/test21.html', context_instance=RequestContext(request,{'test2': l.code})) My question is there any way to load the variable back to its original format in the template file.i.e, i want a function similar to loads in template.I do not want to do it in views since there will be a lot of code changes test21.html {{ test2 }} //The above prints"\u0905\u0902\u0917\u094d\u0930\u0947\u091c\u093c\u0940, \u0939\u093f\u0902\u0926"
[ "Not without writing a custom filter.\n" ]
[ 1 ]
[]
[]
[ "django", "django_templates", "django_views", "python" ]
stackoverflow_0003254381_django_django_templates_django_views_python.txt
Q: only() method in Python? I have these lines in Python: page = lxml.html.parse(URL).getroot() table = only(page.cssselect('table[width=510]')) What is the only method doing? I can't find it in the Python docs (though that might just be because it's very hard to search for!) thanks. A: There is no only built-in function, as you'll see if you type help(only) into your Python interpreter. It must be pulled into the namespace with a from <module> import <only|*> instruction in that module. When you find this, you could try importing the module in your Python interpreter and using the help function again to find out what it does. A: You can try to figure out which module only is defined in by examining the import statements in your file. Then look up only in the docs for that module. Or just put a print only.__module__ in your code and that might print out the module. A: AFAIK, it isn't standard. But I'd guess that it fetches the only element from its input, or raises an exception if the input doesn't have exactly one element. E.g.: >>> def only(input): ... [result] = input ... return result ... >>> only([12]) 12 >>> only([]) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in only ValueError: need more than 0 values to unpack >>> only([23, 34]) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in only ValueError: too many values to unpack >>> A: only is not a built-in function. Is it defined or imported anywhere in the .py file that you have? If not, look for from somemodule import *, and then look in each occurrence of somemodule.
only() method in Python?
I have these lines in Python: page = lxml.html.parse(URL).getroot() table = only(page.cssselect('table[width=510]')) What is the only method doing? I can't find it in the Python docs (though that might just be because it's very hard to search for!) thanks.
[ "There is no only built-in function, as you'll see if you type help(only) into your Python interpreter.\nIt must be pulled into the namespace with a from <module> import <only|*> instruction in that module. When you find this, you could try importing the module in your Python interpreter and using the help function...
[ 4, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003254363_python.txt
Q: i need to question my database about a word received from another aplication, my tables are related on a many to many relashionship i have 2 tables one market, another brand , so when a client search for a brand i need to return all the markets where he can find that brand. A: assuming your dd looks like this: market(id, name) brand(id, name) market_brand(fk_market_id, fk_brand_id) your query would look something like this: select m.name from brand b join market_brand mb on mb.fk_brand_id = b.id join market m on m.id = mb.fk_market_id where b.name = 'your_brand'
i need to question my database about a word received from another aplication, my tables are related on a many to many relashionship
i have 2 tables one market, another brand , so when a client search for a brand i need to return all the markets where he can find that brand.
[ "assuming your dd looks like this:\nmarket(id, name)\nbrand(id, name)\nmarket_brand(fk_market_id, fk_brand_id)\nyour query would look something like this:\nselect m.name\n from brand b\n join market_brand mb on mb.fk_brand_id = b.id\n join market m on m.id = mb.fk_market_id\n where b.name = 'your_brand'\n\n" ]
[ 0 ]
[]
[]
[ "mysql", "python", "sql" ]
stackoverflow_0003254581_mysql_python_sql.txt
Q: Generating passwords in Python 3.1.1 I am looking to generate passwords using strings typed by the user, the book I am reading recommends using sha over md5 because it is considered stronger. sha however has been deprecated and I am now using the hashlib module to encrypt me strings in a similar way to that shown here: http://docs.python.org/py3k/library/hashlib.html#module-hashlib. import os import hashlib from getpass import getpass print('Username: ' + os.environ['USER']) passwd = getpass('Password: ') h = hashlib.md5() h.update(passwd.encode()) passwd_encrypt = h.hexdigest() I am then comparing passwd_encrypt with a plain ascii file containing a list of usernames and encrypted passwords like so: THO 5f4dcc3b5aa765d61d8327deb882cf99 Is this a suitable technique for encryption of the password or is there a better way? I am also interested in whether storing the passwords in this way is suitable and what the alternatives may be. Thank you A: There is no "sha" algorithm. The sha1 algorithm is much stronger than md5, since md5 is completely broken. I believe there is an algorithm that takes microseconds to generate a collision. Sha1 has been considerably weakened by cryptanalysts, and the search is on for the next big thing, but it is still currently suitable for all but the most paranoid. With regard to their use in passwords, the purpose is to prevent discovery of the original password. So it doesn't really matter much that md5 collisions are trivial to generate, since a collision simply yields an alternate password that has the same md5 hash as the original password, it doesn't reveal the original password. Important note: Your version is missing an important component: the salt. This is a random string that is concatenated to the original password in order to generate the hash, and then concatenated to the hash itself for storage. The purpose is to ensure that users with the same password don't end up with the same stored hash. import random print('Username: ' + os.environ['USER']) passwd = getpass('Password: ') salt = ''.join(random.choice('BCDFGHJKLMNPQRSTVWXYZ') for range(4)) h = hashlib.md5() h.update(salt) h.update(passwd.encode()) passwd_encrypt = salt + h.hexdigest() You then verify the password by reusing the stored salt: passwd = getpass('Password: ') salt = passwd_encrypt[:4] h = hashlib.md5() h.update(salt) h.update(passwd.encode()) if passwd_encrypt != salt + h.hexdigest(): raise LoginFailed()
Generating passwords in Python 3.1.1
I am looking to generate passwords using strings typed by the user, the book I am reading recommends using sha over md5 because it is considered stronger. sha however has been deprecated and I am now using the hashlib module to encrypt me strings in a similar way to that shown here: http://docs.python.org/py3k/library/hashlib.html#module-hashlib. import os import hashlib from getpass import getpass print('Username: ' + os.environ['USER']) passwd = getpass('Password: ') h = hashlib.md5() h.update(passwd.encode()) passwd_encrypt = h.hexdigest() I am then comparing passwd_encrypt with a plain ascii file containing a list of usernames and encrypted passwords like so: THO 5f4dcc3b5aa765d61d8327deb882cf99 Is this a suitable technique for encryption of the password or is there a better way? I am also interested in whether storing the passwords in this way is suitable and what the alternatives may be. Thank you
[ "There is no \"sha\" algorithm. The sha1 algorithm is much stronger than md5, since md5 is completely broken. I believe there is an algorithm that takes microseconds to generate a collision.\nSha1 has been considerably weakened by cryptanalysts, and the search is on for the next big thing, but it is still currently...
[ 7 ]
[ "Comparing the hash of the password with a saved hash is a suitable method for authentication.\n" ]
[ -1 ]
[ "encryption", "passwords", "python", "python_3.x" ]
stackoverflow_0003254713_encryption_passwords_python_python_3.x.txt
Q: Python Framework for Desktop Database Application Is there a framework to develop Desktop Database applications (some screens with CRUD screens) for Python? I am looking for something similar to Windows Forms, with the ability to associate TextField, Combos and other UI metaphors with datasets connected to relational databases such as MySQL, SQLServer, Oracle or PostgreSQL. Thanks! A: Camelot A: PyQT should be able to do that, altough I never used it myself (See this article)
Python Framework for Desktop Database Application
Is there a framework to develop Desktop Database applications (some screens with CRUD screens) for Python? I am looking for something similar to Windows Forms, with the ability to associate TextField, Combos and other UI metaphors with datasets connected to relational databases such as MySQL, SQLServer, Oracle or PostgreSQL. Thanks!
[ "Camelot\n", "PyQT should be able to do that, altough I never used it myself (See this article)\n" ]
[ 5, 3 ]
[]
[]
[ "database", "desktop", "frameworks", "python" ]
stackoverflow_0003255665_database_desktop_frameworks_python.txt
Q: Implementing a SAML client in Python I'd like to integrate a web site written in Python (using Pylons) with an existing SAML based authentication service. From reading about SAML, I believe that the IdP (which already exists in this scenario) will send an XML document (via browser post) to the Service Provider (which I am implementing). The Service Provider will need to parse this XML and verify the identity of the user. Are there any existing Python libraries that implement this functionality? Thank you,
Implementing a SAML client in Python
I'd like to integrate a web site written in Python (using Pylons) with an existing SAML based authentication service. From reading about SAML, I believe that the IdP (which already exists in this scenario) will send an XML document (via browser post) to the Service Provider (which I am implementing). The Service Provider will need to parse this XML and verify the identity of the user. Are there any existing Python libraries that implement this functionality? Thank you,
[]
[]
[ "I know you are looking for a Python based solution but there are quite a few \"server\" based solutions that would potentially solve your problem as well and require few ongoing code maintenance issues. \nFor example, using the Apache or IIS Integration kits in conjunction with the PingFederate server from www.pin...
[ -1 ]
[ "authentication", "python", "saml", "single_sign_on" ]
stackoverflow_0003198104_authentication_python_saml_single_sign_on.txt
Q: Is there any reasonable SSDP or DIDL Lib for java/groovy/python? For a future project I am looking for a library to handle SSDP communication and messages in DIDL-Lite xml dialect. Is there any reasonable implementation of java, groovy or python? I don't like to use implementations of existing UPnP stacks like cybergarage or the frauenhofer UPnP stack because they are highly depending on these stacks. A: http://teleal.org/projects/cling Open Source DLNA/UPnP stack, libraries, and tools for Java and Android developers Cling is very modular, so you could only use its SSDP functionality. You can integrate it with your existing code at any level (data transport, protocol execution, etc). The Cling Support package contains a JAXB-based DIDL parser for UPnP A/V service implementors that can be used standalone.
Is there any reasonable SSDP or DIDL Lib for java/groovy/python?
For a future project I am looking for a library to handle SSDP communication and messages in DIDL-Lite xml dialect. Is there any reasonable implementation of java, groovy or python? I don't like to use implementations of existing UPnP stacks like cybergarage or the frauenhofer UPnP stack because they are highly depending on these stacks.
[ "http://teleal.org/projects/cling\nOpen Source DLNA/UPnP stack, libraries, and tools for Java and Android developers\nCling is very modular, so you could only use its SSDP functionality. You can integrate it with your existing code at any level (data transport, protocol execution, etc). \nThe Cling Support package ...
[ 3 ]
[]
[]
[ "groovy", "java", "python", "upnp" ]
stackoverflow_0000630296_groovy_java_python_upnp.txt
Q: wx.ProgressDialog disappears The progress dialog disappers rather then the cancel button changing to a close button when it is to be destroyed (and the PD_AUTO_HIDE flag is not set). progressDlg = wx.ProgressDialog("Organizing music files", "This may take some time..", maximum=9999, parent=self, style = wx.PD_CAN_ABORT |wx.PD_APP_MODAL |wx.PD_ELAPSED_TIME) ) progressDlg.SetSize((400, 200)) while self.working: wx.MilliSleep(250) progressDlg.Pulse(os.getcwd()) progressDlg.Destroy() A: Destroy() explicitly deletes the actual control. I'm pretty sure Destroy()ing a progressdialog behaves as every other control
wx.ProgressDialog disappears
The progress dialog disappers rather then the cancel button changing to a close button when it is to be destroyed (and the PD_AUTO_HIDE flag is not set). progressDlg = wx.ProgressDialog("Organizing music files", "This may take some time..", maximum=9999, parent=self, style = wx.PD_CAN_ABORT |wx.PD_APP_MODAL |wx.PD_ELAPSED_TIME) ) progressDlg.SetSize((400, 200)) while self.working: wx.MilliSleep(250) progressDlg.Pulse(os.getcwd()) progressDlg.Destroy()
[ "Destroy() explicitly deletes the actual control. I'm pretty sure Destroy()ing a progressdialog behaves as every other control\n" ]
[ 0 ]
[]
[]
[ "progressdialog", "python", "wxpython" ]
stackoverflow_0003251721_progressdialog_python_wxpython.txt
Q: Linear interpolation on a numpy array I have the following numpy array: # A B C Y my_arr = np.array([ [.20, .54, .26], # <0 [.22, .54, .24], # 1 [.19, .56, .25], # 2 [.19, .58, .23], # 3 [.17, .62, .21] ]) # 4+ if a user enters a y (example, 2.5) I should out put three values, one for A, B, and C: in my example A: .19, B: .57, C: .24 More Examples: Y A B C 0.2 .20 .54 .26 1.5 .215 .55 .245 4.0 .17 .62 .21 8.7 .17 .62 .21 The user will enter a multiple of y values as a numpy array. the result should be an array as well I've done bits and pieces of the code for example #boundaries: y[y < 0] = 0 y[y > 4] = 4 I'm also assuming that scipy.ndimage / map_coordinates will best fit my requirements rather than scipy.interpolate but I could be wrong A: from scipy import array, ndimage # A B C Y m = array([ [.20, .54, .26], # 0 [.22, .54, .24], # 1 [.19, .56, .25], # 2 [.19, .58, .23], # 3 [.17, .62, .21] ]) # 4 inputs = array([-1, 0, 0.2, 1, 1.5, 2, 2.5, 3, 4, 8.7]) inputs[inputs < 0] = 0 inputs[inputs > 4] = 4 for y in inputs: x = ndimage.map_coordinates(m, [y * numpy.ones(3), numpy.arange(3)], order=1) print y, x >>> 0.0 [ 0.2 0.54 0.26] 0.0 [ 0.2 0.54 0.26] 0.2 [ 0.204 0.54 0.256] 1.0 [ 0.22 0.54 0.24] 1.5 [ 0.205 0.55 0.245] 2.0 [ 0.19 0.56 0.25] 2.5 [ 0.19 0.57 0.24] 3.0 [ 0.19 0.58 0.23] 4.0 [ 0.17 0.62 0.21] 4.0 [ 0.17 0.62 0.21] A: There might be a better way using scipy.ndimage, but here is how you could do it with scipy.interpolate.interp1d: import numpy as np import scipy.interpolate as spi # A B C Y my_arr = np.array([ [.20, .54, .26], # 0 [.22, .54, .24], # 1 [.19, .56, .25], # 2 [.19, .58, .23], # 3 [.17, .62, .21] ]) print(my_arr) Y=np.arange(len(my_arr)) interp_funcs=[spi.interp1d(Y,my_arr[:,col]) for col in range(3)] y=np.array([2.5,0.2,1.5,4.0,8.7]) y[y < 0] = 0 y[y > 4] = 4 print(np.vstack(f(y) for f in interp_funcs)) # [[ 0.19 0.204 0.205 0.17 0.17 ] # [ 0.57 0.54 0.55 0.62 0.62 ] # [ 0.24 0.256 0.245 0.21 0.21 ]]
Linear interpolation on a numpy array
I have the following numpy array: # A B C Y my_arr = np.array([ [.20, .54, .26], # <0 [.22, .54, .24], # 1 [.19, .56, .25], # 2 [.19, .58, .23], # 3 [.17, .62, .21] ]) # 4+ if a user enters a y (example, 2.5) I should out put three values, one for A, B, and C: in my example A: .19, B: .57, C: .24 More Examples: Y A B C 0.2 .20 .54 .26 1.5 .215 .55 .245 4.0 .17 .62 .21 8.7 .17 .62 .21 The user will enter a multiple of y values as a numpy array. the result should be an array as well I've done bits and pieces of the code for example #boundaries: y[y < 0] = 0 y[y > 4] = 4 I'm also assuming that scipy.ndimage / map_coordinates will best fit my requirements rather than scipy.interpolate but I could be wrong
[ "from scipy import array, ndimage\n\n# A B C Y\nm = array([ [.20, .54, .26], # 0\n [.22, .54, .24], # 1\n [.19, .56, .25], # 2\n [.19, .58, .23], # 3\n [.17, .62, .21] ]) # 4\n\ninputs = array([-1, 0, 0.2, 1, 1.5, 2, 2.5, 3, 4,...
[ 6, 2 ]
[]
[]
[ "interpolation", "numpy", "python", "scipy" ]
stackoverflow_0003255816_interpolation_numpy_python_scipy.txt
Q: save gtk.DrawingArea to file I want to save gtk.DrawingArea() object contents to jpeg file using PIL. Particularly I want add to this script possibility to make photo. I found how to save image to jpeg. All I need - get pixbuf object from gtk.DrawingArea() object. How can I do this? A: If you're not married to the idea of using gstreamer, you can use OpenCV instead. This post gives a great example using pygame. However, you can get the pixbuf this way (and you don't even need PIL): def get_picture(self, event, data): drawable = self.movie_window.window colormap = drawable.get_colormap() pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, 0, 8, *drawable.get_size()) pixbuf = pixbuf.get_from_drawable(drawable, colormap, 0,0,0,0, *drawable.get_size()) pixbuf.save(r'somefile.png', 'png') pixbuf.save(r'somefile.jpeg', 'jpeg') and then just create a button and bind the command to get_picture. Of course, if I were writing this program I would actually grab the image to an Image in the first place and then draw it on the gtk.DrawingArea - that would allow you to do all sorts of fun things.
save gtk.DrawingArea to file
I want to save gtk.DrawingArea() object contents to jpeg file using PIL. Particularly I want add to this script possibility to make photo. I found how to save image to jpeg. All I need - get pixbuf object from gtk.DrawingArea() object. How can I do this?
[ "If you're not married to the idea of using gstreamer, you can use OpenCV instead. This post gives a great example using pygame.\nHowever, you can get the pixbuf this way (and you don't even need PIL):\ndef get_picture(self, event, data):\n drawable = self.movie_window.window\n colormap = drawable.get_colorma...
[ 2 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0003254499_gtk_pygtk_python.txt
Q: How to convert bytes in a string to integers? Python I want to get a list of ints representing the bytes in a string. A: One option for Python 2.6 and later is to use a bytearray: >>> b = bytearray('hello') >>> b[0] 104 >>> b[1] 101 >>> list(b) [104, 101, 108, 108, 111] For Python 3.x you'd need a bytes object rather than a string in any case and so could just do this: >>> b = b'hello' >>> list(b) [104, 101, 108, 108, 111] A: Do you mean the ascii values? nums = [ord(c) for c in mystring] or nums = [] for chr in mystring: nums.append(ord(chr)) A: Perhaps you mean a string of bytes, for example received over the net, representing a couple of integer values? In that case you can "unpack" the string into the integer values by using unpack() and specifying "i" for integer as the format string. See: http://docs.python.org/library/struct.html
How to convert bytes in a string to integers? Python
I want to get a list of ints representing the bytes in a string.
[ "One option for Python 2.6 and later is to use a bytearray:\n>>> b = bytearray('hello')\n>>> b[0]\n104\n>>> b[1]\n101\n>>> list(b)\n[104, 101, 108, 108, 111]\n\nFor Python 3.x you'd need a bytes object rather than a string in any case and so could just do this:\n>>> b = b'hello'\n>>> list(b)\n[104, 101, 108, 108, 1...
[ 14, 7, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003255987_python.txt
Q: What other Language synergizes well with Python? Need Advice Ok so I know the basics of programming languages, I've studied python and liked it a lot. I'm studying now the intermediate parts of python and I'm catching the concepts already. I'm working with a project and at the same time solving computer problems that practices algorithm use. I've learned that python has limitations and wants to compensate that limitations by learning another programming language. What programming language do you suggest that synergizes well with python? I want something who can give me their actual experience while working with python and the language that complements well with it. Answers like "try iron python or jython blah blah blah" won't help, if you can give me it's pros and cons, it's maturity it's problems then that's good enough for me... Thanks a lot EDIT - Sorry guys, I think I need to add some details in this. I'll be using python mainly for web programming or game development. So if you think this language A would help me in python for web programming then that's it. A: What is wrong with IronPython or Jython? You can learn how to write libraries in Java or .Net to alleviate some of Python's speed problems. Learning to write your own Python libraries will certainly help you better understand and overcome the limitations you mentioned. A: For me, the obvious choice to learn after Python is C. C is a lower level language, so you're dealing with more elemental computer concepts than objects, but it will give you the understanding necessary to write extensions to Python. That way, it will be easy to write your programs in Python, and then migrate parts to C for speed--either by writing an extension or by using a bridge language like Cython. A: If you run into performance problems (which might be an issue in game programming), C/C++ programs can be integrated well into Python scripts and vice versa: Extending and Embedding Python/C API But I haven't yet seen the need to do so myself. A: When you're quite comfortable with Python, Common Lisp and Scheme are good languages to learn about functional programming. I've been learning CLisp myself lately and there are a lot of "ahah!" moments that make it a lot of fun. IronPython and Jython are great tools to learn if you plan on entering the professional world - there is tons of development right now in C# and Java - they're pretty much the hot languages of the professional world. IronPython integrates with all of the .NET languages, while Jython of course integrates with Java. So your choice there should reflect your desire to work at a .NET company, or not. Both IronPython and Jython are well matured languages. Others have already mentioned C/C++ which are good choices if you're not familiar with them, and if ~30-40 years of programming life, and Top 3 rankings for July 2010 on the TIOBE index is not a strong enough reason to learn them... well you probably have other issues ;) If you're looking at newer languages that haven't really been tested hard-core, you have languages like Ruby (which seems to be the new sexy), and Go by Google. Perl is a bit like Ruby in that there is quite an overlap between Python and Ruby/Perl, and the areas they cover. If I were to pick another language, already knowing Python, I'd go with a compiled language - maybe lower level like C\C++. I guess it really can be determined by what you want to do. If you want to work for a .NET company (which may or may not imply you really love Microsoft products), IronPython and a .NET language (C#, VB) is the way to go. OTOH, if you want to work for a company like Google (which happens to employ a certain individual), they extensively use Java and Python, so it's probably better to learn Jython. I guess the question you need to ask yourself is, "Where do you I want to go today tomorrow?™" A: Haskell or Ocaml, or maybe a Lisp dialect such as Common Lisp or Scheme.
What other Language synergizes well with Python? Need Advice
Ok so I know the basics of programming languages, I've studied python and liked it a lot. I'm studying now the intermediate parts of python and I'm catching the concepts already. I'm working with a project and at the same time solving computer problems that practices algorithm use. I've learned that python has limitations and wants to compensate that limitations by learning another programming language. What programming language do you suggest that synergizes well with python? I want something who can give me their actual experience while working with python and the language that complements well with it. Answers like "try iron python or jython blah blah blah" won't help, if you can give me it's pros and cons, it's maturity it's problems then that's good enough for me... Thanks a lot EDIT - Sorry guys, I think I need to add some details in this. I'll be using python mainly for web programming or game development. So if you think this language A would help me in python for web programming then that's it.
[ "What is wrong with IronPython or Jython? You can learn how to write libraries in Java or .Net to alleviate some of Python's speed problems. Learning to write your own Python libraries will certainly help you better understand and overcome the limitations you mentioned.\n", "For me, the obvious choice to learn af...
[ 1, 1, 1, 1, 0 ]
[]
[]
[ "paradigms", "python" ]
stackoverflow_0003255925_paradigms_python.txt
Q: Django-Haystack + Whoosh - Are misspelling suggestions possible? I'm using Whoosh and Django-Haystack. I would like to make use of query suggestions for when users mistype words. e.g. Maybe you meant "unicorn" Is it necessary to use another search engine? Or can I successfully achieve this with Whoosh? A: Haystack lets you enable spelling suggestions, and that does work with Whoosh. A: I have no experience with Whoosh, but comparing edit distance and rolling your own wouldn't be too complex, if necessary.
Django-Haystack + Whoosh - Are misspelling suggestions possible?
I'm using Whoosh and Django-Haystack. I would like to make use of query suggestions for when users mistype words. e.g. Maybe you meant "unicorn" Is it necessary to use another search engine? Or can I successfully achieve this with Whoosh?
[ "Haystack lets you enable spelling suggestions, and that does work with Whoosh.\n", "I have no experience with Whoosh, but comparing edit distance and rolling your own wouldn't be too complex, if necessary.\n" ]
[ 4, 0 ]
[]
[]
[ "django", "django_haystack", "full_text_search", "python", "whoosh" ]
stackoverflow_0003256177_django_django_haystack_full_text_search_python_whoosh.txt
Q: Parse a cron entry in Python All. I am trying to find a python module that I can use to parse a cron entry and get the next time it will run. With perl I use the Schedule::Cron::Events module but I would like to convert to python. Thanks in advance. A: The documentation for python-crontab is in docstrings in the source code, as is usual for python. You can also explore the documentation via the python interpreter with the built-in help() function. The full source for python-crontab is less than 500 lines anyway and is very readable. Example from the source code: from crontab import CronTab tab = CronTab() cron = tab.new(command='/usr/bin/echo') cron.minute().during(5,50).every(5) cron.hour().every(4) cron2 = tab.new(command='/foo/bar',comment='SomeID') cron2.every_reboot() list = tab.find('bar') cron3 = list[0] cron3.clear() cron3.minute().every(1) print unicode(tab.render()) for cron4 in tab.find('echo'): print cron4 for cron5 in tab: print cron5 tab.remove_all('echo') t.write() A: I could be wrong but doesn't python crontab offer ways to read and write to crontab but nothing regarding parsing the crontab to determine the time until the next time a job will be run? A: Take a look at python-crontab.
Parse a cron entry in Python
All. I am trying to find a python module that I can use to parse a cron entry and get the next time it will run. With perl I use the Schedule::Cron::Events module but I would like to convert to python. Thanks in advance.
[ "The documentation for python-crontab is in docstrings in the source code, as is usual for python. You can also explore the documentation via the python interpreter with the built-in help() function. The full source for python-crontab is less than 500 lines anyway and is very readable.\nExample from the source code...
[ 8, 4, 2 ]
[]
[]
[ "cron", "module", "python" ]
stackoverflow_0001511854_cron_module_python.txt
Q: Python Deque appendleft with list I am currently creating my deque object using the following, self.CommandList = deque((['S', False, 60],['c'],['g16'],['i50'],['r30', True],['u320'],['o5000'],['b1'],['B4500'],['W1'],['l5154'],['!10'],['p2', True, 10],['e1'],['K20'],['U0'],['Y0'])) But I wish to add a similar list to the queue later but using appendleft, so it can jump ahead of the list. I assumed the following, but had no luck. NewList = (['S'],['c'],['!10'],['p4'],['o1200'],['i50'],['r30'],['b10'],['d1'],['A', True, 163]) self.CommandList.appendleft(NewList) Is this even possible with appendleft? A: I think you want .extendleft here. This will "extend the list" instead of just appending the list as one element. z = collections.deque([1,2,3,4]) # [1, 2, 3, 4] z.appendleft(['bad', 'news']) # [ ['bad', 'news'], 1, 2, 3, 4 ] z.extendleft(['good', 'news']) # [ 'good', 'news', ['bad', 'news'], 1, 2, 3, 4 ] If they are getting inserted in reverse, the quick fix is to just reverse the list: z.extendleft(reversed(['good', 'news']))
Python Deque appendleft with list
I am currently creating my deque object using the following, self.CommandList = deque((['S', False, 60],['c'],['g16'],['i50'],['r30', True],['u320'],['o5000'],['b1'],['B4500'],['W1'],['l5154'],['!10'],['p2', True, 10],['e1'],['K20'],['U0'],['Y0'])) But I wish to add a similar list to the queue later but using appendleft, so it can jump ahead of the list. I assumed the following, but had no luck. NewList = (['S'],['c'],['!10'],['p4'],['o1200'],['i50'],['r30'],['b10'],['d1'],['A', True, 163]) self.CommandList.appendleft(NewList) Is this even possible with appendleft?
[ "I think you want .extendleft here. This will \"extend the list\" instead of just appending the list as one element.\nz = collections.deque([1,2,3,4]) # [1, 2, 3, 4]\n\nz.appendleft(['bad', 'news']) # [ ['bad', 'news'], 1, 2, 3, 4 ]\nz.extendleft(['good', 'news']) # [ 'good', 'news', ['bad', 'news'], 1, 2, 3, ...
[ 17 ]
[]
[]
[ "deque", "list", "python" ]
stackoverflow_0003256377_deque_list_python.txt
Q: How to create a notification server which informs Delphi application when database changes? We need to be able to inform a Delphi application in case there are changes to some of our tables in MySQL. Delphi clients are in the Internet behind a firewall, and they have to be authenticated before connecting to the notification server we need to implement. The server can be programmed using for example Java, PHP or Python, and it has to support thousands of clients. Typically one change in the database needs to be informed only to a single client, and I don't believe performance will be a bottleneck. It just has to be possible to inform any of those thousands of clients when a change affecting the specific client occurs. I have been thinking of a solution where: MySQL trigger would inform to notification server Delphi client connects to a messaging queue and gets the notification using it My questions: What would be the best to way from the trigger to inform the external server of the change Which message queue solution to pick? A: Answer to the First Question: check this question and answers on Stack Overflow: When a new row in database is added, an external command line program must be invoked In theory, a simple user-defined function could be used to fire a 'row changed' message to a message broker / queue. But this involves external systems (at least a network subsystem) which can fail - and bad things can happen. A different solution which does not require dangerous modifications to the database system would be a multi-tiered design for the application. The server application which hosts the business logic then needs to generate 'database content changed' events, post them to a publish and subscribe message channel (aka 'topic') on the message broker so that every client will receive a copy of this message immediately or if the client reconnects (using 'durable subscriptions'). I wrote a related blog article about this topic here: Firebird Database Events and Message-oriented Middleware Answer to the Second Question: The creators of Second Life have evaluated a couple of message brokers and published their results - for some of the products, Delphi client libraries exist or can be implemented using standard protocols: Message Queue Evaluation Notes Since then, other products have been released, some of them can also be integrated with Delphi clients through non-Java protocols, for example: Open Message Queue (OpenMQ) 4.4, which is the default JMS provider broker in the Sun GlassFish v3 application Server JBoss HornetQ 2.1 which will be the default JMS provider in JBoss application server 6. HornetQ 2.0.GA obtained scores up to 307% higher than previously published SPECjms2007 benchmark results, on the same server hardware and operating system set-up. A very popular open source message broker which can be used from Delphi, Java, PHP, C# (and other) clients is Apache ActiveMQ 5.4.1 - free introduction chapter of "ActiveMQ in Action" by Bruce Snyder, Dejan Bosanac, and Rob Davies All brokers are designed for thousands of concurrent clients and tens of thousands of messages per second. They also typically support clustering and failover, though this is not part of the JMS specification. If speed is not so important, but you need High availability (even if your internal system is down), Amazon Simple Queue Service (Amazon SQS) is a cloud-based service which can be accessed using REST and Soap style interfaces. A: There is apache camel and spring intergration, both provides some ways to send messages across. A: Why not use the XMPP protocol (aka Jabbber) ?
How to create a notification server which informs Delphi application when database changes?
We need to be able to inform a Delphi application in case there are changes to some of our tables in MySQL. Delphi clients are in the Internet behind a firewall, and they have to be authenticated before connecting to the notification server we need to implement. The server can be programmed using for example Java, PHP or Python, and it has to support thousands of clients. Typically one change in the database needs to be informed only to a single client, and I don't believe performance will be a bottleneck. It just has to be possible to inform any of those thousands of clients when a change affecting the specific client occurs. I have been thinking of a solution where: MySQL trigger would inform to notification server Delphi client connects to a messaging queue and gets the notification using it My questions: What would be the best to way from the trigger to inform the external server of the change Which message queue solution to pick?
[ "Answer to the First Question:\ncheck this question and answers on Stack Overflow:\nWhen a new row in database is added, an external command line program must be invoked\nIn theory, a simple user-defined function could be used to fire a 'row changed' message to a message broker / queue. But this involves external s...
[ 5, 1, 0 ]
[]
[]
[ "delphi", "java", "mysql", "php", "python" ]
stackoverflow_0003255330_delphi_java_mysql_php_python.txt
Q: Catching http errors how can I catch the 404 and 403 errors for pages in python and urllib(2), for example? Are there any fast ways without big class-wrappers? Added info (stack trace): Traceback (most recent call last): File "test.py", line 3, in <module> page = urllib2.urlopen("http://localhost:4444") File "/usr/lib/python2.6/urllib2.py", line 126, in urlopen return _opener.open(url, data, timeout) File "/usr/lib/python2.6/urllib2.py", line 391, in open response = self._open(req, data) File "/usr/lib/python2.6/urllib2.py", line 409, in _open '_open', req) File "/usr/lib/python2.6/urllib2.py", line 369, in _call_chain result = func(*args) File "/usr/lib/python2.6/urllib2.py", line 1161, in http_open return self.do_open(httplib.HTTPConnection, req) File "/usr/lib/python2.6/urllib2.py", line 1136, in do_open raise URLError(err) urllib2.URLError: <urlopen error [Errno 111] Connection refused> A: import urllib2 try: page = urllib2.urlopen("some url") except urllib2.HTTPError, err: if err.code == 404: print "Page not found!" elif err.code == 403: print "Access denied!" else: print "Something happened! Error code", err.code except urllib2.URLError, err: print "Some other error happened:", err.reason In your case, the error happens already before the HTTP connection could be built - therefore you need to add another error handler that catches URLError. But this has nothing to do with 404 or 403 errors. A: req = urllib2.Request('url') >>> try: >>> urllib2.urlopen(req) >>> except urllib2.URLError, e: >>> print e.code >>> print e.read()
Catching http errors
how can I catch the 404 and 403 errors for pages in python and urllib(2), for example? Are there any fast ways without big class-wrappers? Added info (stack trace): Traceback (most recent call last): File "test.py", line 3, in <module> page = urllib2.urlopen("http://localhost:4444") File "/usr/lib/python2.6/urllib2.py", line 126, in urlopen return _opener.open(url, data, timeout) File "/usr/lib/python2.6/urllib2.py", line 391, in open response = self._open(req, data) File "/usr/lib/python2.6/urllib2.py", line 409, in _open '_open', req) File "/usr/lib/python2.6/urllib2.py", line 369, in _call_chain result = func(*args) File "/usr/lib/python2.6/urllib2.py", line 1161, in http_open return self.do_open(httplib.HTTPConnection, req) File "/usr/lib/python2.6/urllib2.py", line 1136, in do_open raise URLError(err) urllib2.URLError: <urlopen error [Errno 111] Connection refused>
[ "import urllib2 \ntry:\n page = urllib2.urlopen(\"some url\")\nexcept urllib2.HTTPError, err:\n if err.code == 404:\n print \"Page not found!\"\n elif err.code == 403:\n print \"Access denied!\"\n else:\n print \"Something happened! Error code\", err.code\nexcept urllib2.URLError, err:\n ...
[ 23, 5 ]
[]
[]
[ "python", "urllib" ]
stackoverflow_0003256576_python_urllib.txt
Q: How do I redirect different domain names requests to the same ip in django I have one ip for two domain name, e.g. "www.example.com" and "example.info", and I want each of them to be handled as a different domain (e.g. www.example.com/photos and example.info/photos will be ahndled each by its corresponding function). Is there an elegant way to do this in django? A: You would do this by setting up different WSGI for each domain using a setting SITE_ID corresponding to the site id from the django.contrib.site app.
How do I redirect different domain names requests to the same ip in django
I have one ip for two domain name, e.g. "www.example.com" and "example.info", and I want each of them to be handled as a different domain (e.g. www.example.com/photos and example.info/photos will be ahndled each by its corresponding function). Is there an elegant way to do this in django?
[ "You would do this by setting up different WSGI for each domain using a setting SITE_ID corresponding to the site id from the django.contrib.site app.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003256731_django_python.txt
Q: Call back in Python Could some explain how call back methods work, and if possible, give me an example in Python? So as far as I understand them, they are methods which are provided by the user of an API, to the API, so that the user doesn't have to wait till that particular API function completes. So does the user program continue executing, and once the callback method is called by the API, return to point in the program where the callback method was provided? How does a callback method essentially affect the 'flow' of a program? Sorry if I'm being vague here. A: Callbacks are just user-supplied hooks. They allow you to specify what function to call in case of certain events. re.sub has a callback, but it sounds like you are dealing with a GUI, so I'll give a GUI example: Here is a very simple example of a callback: from Tkinter import * master = Tk() def my_callback(): print('Running my_callback') b = Button(master, text="OK", command=my_callback) b.pack() mainloop() When you press the OK button, the program prints "Running my_callback". If you play around with this code: from Tkinter import * import time master = Tk() def my_callback(): print('Starting my_callback') time.sleep(5) print('Ending my_callback') def my_callback2(): print('Starting my_callback2') time.sleep(5) print('Ending my_callback2') b = Button(master, text="OK", command=my_callback) b.pack() b = Button(master, text="OK2", command=my_callback2) b.pack() mainloop() you'll see that pressing either button blocks the GUI from responding until the callback finishes. So the "user does have to wait till that particular API function completes".
Call back in Python
Could some explain how call back methods work, and if possible, give me an example in Python? So as far as I understand them, they are methods which are provided by the user of an API, to the API, so that the user doesn't have to wait till that particular API function completes. So does the user program continue executing, and once the callback method is called by the API, return to point in the program where the callback method was provided? How does a callback method essentially affect the 'flow' of a program? Sorry if I'm being vague here.
[ "Callbacks are just user-supplied hooks. They allow you to specify what function to call in case of certain events. re.sub has a callback, but it sounds like you are dealing with a GUI, so I'll give a GUI example:\nHere is a very simple example of a callback:\nfrom Tkinter import *\n\nmaster = Tk()\n\ndef my_callba...
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0003257093_python.txt
Q: Tweepy API: how to get a user's id from a status SearchResult object? I'm trying to write a script to follow people on twitter. The tweepy API seems pretty good, but I'm running into some unintuitive behavior related to the mapping from user's ids to their screen names. In [1]: import tweepy In [2]: api = tweepy.API() # get an arbitrary tweet In [3]: tweet = api.search("anything")[0] In [5]: tweet.text Out[5]: 'Currently mourning the [potential] loss of around 500 pictures I took while in Oklahoma. Anyone know anything about Canon Rebels?' # who tweeted it? In [6]: tweet.from_user Out[6]: 'helloregan' # get the tweeters id In [7]: tweet.from_user_id Out[7]: 101962792 # i'm paranoid. just want to make sure its right. In [8]: helloregan = api.get_user(user_id=tweet.from_user_id) # yep, same id. In [9]: helloregan.id Out[9]: 101962792 # lets check to see if its the same screen name? no. different person. In [10]: helloregan.screen_name Out[10]: 'kikiiputh' What gives? A: Figured out the issue isn't a tweepy one: http://code.google.com/p/twitter-api/issues/detail?id=214 Updated for reference for any other tweepy users who run into the same issue.
Tweepy API: how to get a user's id from a status SearchResult object?
I'm trying to write a script to follow people on twitter. The tweepy API seems pretty good, but I'm running into some unintuitive behavior related to the mapping from user's ids to their screen names. In [1]: import tweepy In [2]: api = tweepy.API() # get an arbitrary tweet In [3]: tweet = api.search("anything")[0] In [5]: tweet.text Out[5]: 'Currently mourning the [potential] loss of around 500 pictures I took while in Oklahoma. Anyone know anything about Canon Rebels?' # who tweeted it? In [6]: tweet.from_user Out[6]: 'helloregan' # get the tweeters id In [7]: tweet.from_user_id Out[7]: 101962792 # i'm paranoid. just want to make sure its right. In [8]: helloregan = api.get_user(user_id=tweet.from_user_id) # yep, same id. In [9]: helloregan.id Out[9]: 101962792 # lets check to see if its the same screen name? no. different person. In [10]: helloregan.screen_name Out[10]: 'kikiiputh' What gives?
[ "Figured out the issue isn't a tweepy one:\nhttp://code.google.com/p/twitter-api/issues/detail?id=214\nUpdated for reference for any other tweepy users who run into the same issue.\n" ]
[ 7 ]
[]
[]
[ "python", "tweepy", "twitter" ]
stackoverflow_0003256981_python_tweepy_twitter.txt
Q: Copying files with Python under Windows I'm trying to copy files inside a Python script using the following code: inf,outf = open(ifn,"r"), open(ofn,"w") outf.write(inf.read()) inf.close() outf.close() This works perfectly unedr OSX (and other UNIX flavors I suspect) but fails under Windows. Basically, the read() call returns far less bytes than the actual file size (which are around 10KB in length) hence causing the write truncate the output file. The description of the read() method says that "If the size argument is negative or omitted, read all data until EOF is reached" so I expect the above code to work under any environment, having Python shielding my code from OSs quirks. So, what's the point? Now, I resorted to shutil.copyfile, which suits my need, and it works. I'm using Python 2.6.5 Thank you all. A: shutil is a better way to copy files anyway, but you need to open binary files in binary mode on Windows. It matters there. open(fname, 'rb')
Copying files with Python under Windows
I'm trying to copy files inside a Python script using the following code: inf,outf = open(ifn,"r"), open(ofn,"w") outf.write(inf.read()) inf.close() outf.close() This works perfectly unedr OSX (and other UNIX flavors I suspect) but fails under Windows. Basically, the read() call returns far less bytes than the actual file size (which are around 10KB in length) hence causing the write truncate the output file. The description of the read() method says that "If the size argument is negative or omitted, read all data until EOF is reached" so I expect the above code to work under any environment, having Python shielding my code from OSs quirks. So, what's the point? Now, I resorted to shutil.copyfile, which suits my need, and it works. I'm using Python 2.6.5 Thank you all.
[ "shutil is a better way to copy files anyway, but you need to open binary files in binary mode on Windows. It matters there. open(fname, 'rb')\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0003257471_python.txt
Q: defining variable from string I'm trying to define variable inside function. vars() shows variable is created, but gives me NameError: exception. What am I doing wrong? def a(str1): vars() [str1] = 1 print vars() print b a('b') output: {'str1': 'b', 'b': 1} exception: NameError: global name 'b' is not defined A: You're invoking undefined behaviour. From the documentation of vars(): Note The returned dictionary should not be modified: the effects on the corresponding symbol table are undefined. Other answers give possible solutions. A: Your code works for me. Perhaps you should try an alternative approach: exec(str1 + '=1') This will execute b=1 A: If you don't understand why a construct doesn't work, neither will the next person who has to read your code. If you mean b = 1 you should say that. In this case vars() gives you access to the function local dictionary so your code is equivalent to def a(): b = 1 where b is local to a and evaporates when it goes out of scope upon exit from a. premature optimization is the root of many people's attempt to second-guess Python from itertools import izip import timeit import msw.wordlist def zip_list(p): """construct a dictionary of length 100 from a list of strings""" return dict(zip(p[:100], p[100:])) def izip_list(p): """as zip_list but avoids creating a new list to feed to dict()""" return dict(izip(p[:100], p[100:])) def pass_list(p): """take 100 elements of a list and do nothing""" for i in p[:100]: pass def exec_pass_list(p): """exec() a no-op 100 times""" for i in xrange(100): exec('pass') # returns a list of 64'000 unique lowercase dictionary words for tests words = msw.wordlist.Wordlist() words.shuffle() words = words[:200] print 'words', words[:5], '...' for func in ['zip_list', 'izip_list', 'pass_list', 'exec_pass_list']: t = timeit.Timer('%s(words)' % func, 'from __main__ import words, %s' % func) print func, t.repeat(number=10**5) which yields: words ['concatenated', 'predicament', 'shtick', 'imagine', 'stationing'] ... zip_list [1.8603439331054688, 1.8597819805145264, 1.8571949005126953] izip_list [1.5500969886779785, 1.5501470565795898, 1.5536530017852783] pass_list [0.26778006553649902, 0.26837801933288574, 0.26767921447753906] exec_pass_list [74.459679126739502, 75.221366882324219, 77.538936853408813] I didn't bother trying implement whatever the OP was trying to do because being 50 times slower to not construct a dictionary sort makes further testing kinda stupid.
defining variable from string
I'm trying to define variable inside function. vars() shows variable is created, but gives me NameError: exception. What am I doing wrong? def a(str1): vars() [str1] = 1 print vars() print b a('b') output: {'str1': 'b', 'b': 1} exception: NameError: global name 'b' is not defined
[ "You're invoking undefined behaviour. From the documentation of vars():\n\nNote The returned dictionary should not be modified: the effects on the corresponding symbol table are undefined.\n\nOther answers give possible solutions.\n", "Your code works for me. Perhaps you should try an alternative approach:\nexec(...
[ 4, 2, 1 ]
[]
[]
[ "python", "scope" ]
stackoverflow_0003257672_python_scope.txt
Q: How do I do threading in python? I am trying to learn how to use threads with python. this is the code I have been studying: import time from threading import Thread def myfunc(i): print "sleeping 5 sec from thread %d" % i time.sleep(5) print "finished sleeping from thread %d" % i for i in range(10): t = Thread(target=myfunc, args=(i,)) t.start() the program runs fine in command prompt but when I try to run it in idle I get errors like this: Traceback (most recent call last): File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345, in __call__ return self.func(*args) File "C:\Python24\lib\idlelib\ScriptBinding.py", line 165, in run_module_event interp.runcode(code) File "C:\Python24\lib\idlelib\PyShell.py", line 726, in runcode self.tkconsole.endexecuting() File "C:\Python24\lib\idlelib\PyShell.py", line 901, in endexecuting self.showprompt() File "C:\Python24\lib\idlelib\PyShell.py", line 1163, in showprompt self.resetoutput() File "C:\Python24\lib\idlelib\PyShell.py", line 1178, in resetoutput self.text.insert("end-1c", "\n") File "C:\Python24\lib\idlelib\Percolator.py", line 25, in insert self.top.insert(index, chars, tags) File "C:\Python24\lib\idlelib\PyShell.py", line 315, in insert UndoDelegator.insert(self, index, chars, tags) File "C:\Python24\lib\idlelib\UndoDelegator.py", line 81, in insert self.addcmd(InsertCommand(index, chars, tags)) File "C:\Python24\lib\idlelib\UndoDelegator.py", line 116, in addcmd cmd.do(self.delegate) File "C:\Python24\lib\idlelib\UndoDelegator.py", line 216, in do if text.compare(self.index1, ">", "end-1c"): File "C:\Python24\lib\lib-tk\Tkinter.py", line 2784, in compare return self.tk.getboolean(self.tk.call( TclError: expected boolean value but got "" Is python threading just not stable or am I doing something grossly wrong? The example came from : http://www.saltycrane.com/blog/2008/09/simplistic-python-thread-example/ A: It sounds like a bug in IDLE, not a problem with Python. The error is coming from Tkinter, which is a Python GUI toolkit, and which IDLE probably uses. I would report it to whoever maintains IDLE. A: Not everything runs properly under IDLE. This is because IDLE is a Python program in itself and has its own attributes and state that can sometimes get messed up by your own code. You can tell this is a problem with IDLE because you can see idlelib in the call stack. Also, you're not using TCL/TK at all in your application, but IDLE is, and the call stack shows that too. I would advise switching to a more 'inert' text editor for working with Python code!
How do I do threading in python?
I am trying to learn how to use threads with python. this is the code I have been studying: import time from threading import Thread def myfunc(i): print "sleeping 5 sec from thread %d" % i time.sleep(5) print "finished sleeping from thread %d" % i for i in range(10): t = Thread(target=myfunc, args=(i,)) t.start() the program runs fine in command prompt but when I try to run it in idle I get errors like this: Traceback (most recent call last): File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345, in __call__ return self.func(*args) File "C:\Python24\lib\idlelib\ScriptBinding.py", line 165, in run_module_event interp.runcode(code) File "C:\Python24\lib\idlelib\PyShell.py", line 726, in runcode self.tkconsole.endexecuting() File "C:\Python24\lib\idlelib\PyShell.py", line 901, in endexecuting self.showprompt() File "C:\Python24\lib\idlelib\PyShell.py", line 1163, in showprompt self.resetoutput() File "C:\Python24\lib\idlelib\PyShell.py", line 1178, in resetoutput self.text.insert("end-1c", "\n") File "C:\Python24\lib\idlelib\Percolator.py", line 25, in insert self.top.insert(index, chars, tags) File "C:\Python24\lib\idlelib\PyShell.py", line 315, in insert UndoDelegator.insert(self, index, chars, tags) File "C:\Python24\lib\idlelib\UndoDelegator.py", line 81, in insert self.addcmd(InsertCommand(index, chars, tags)) File "C:\Python24\lib\idlelib\UndoDelegator.py", line 116, in addcmd cmd.do(self.delegate) File "C:\Python24\lib\idlelib\UndoDelegator.py", line 216, in do if text.compare(self.index1, ">", "end-1c"): File "C:\Python24\lib\lib-tk\Tkinter.py", line 2784, in compare return self.tk.getboolean(self.tk.call( TclError: expected boolean value but got "" Is python threading just not stable or am I doing something grossly wrong? The example came from : http://www.saltycrane.com/blog/2008/09/simplistic-python-thread-example/
[ "It sounds like a bug in IDLE, not a problem with Python. The error is coming from Tkinter, which is a Python GUI toolkit, and which IDLE probably uses. I would report it to whoever maintains IDLE.\n", "Not everything runs properly under IDLE. This is because IDLE is a Python program in itself and has its own att...
[ 1, 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003257834_multithreading_python.txt
Q: Single player 'pong' game I am just starting out learning pygame and livewires, and I'm trying to make a single-player pong game, where you just hit the ball, and it bounces around until it passes your paddle (located on the left side of the screen and controlled by the mouse), which makes you lose. I have the basic code, but the ball doesn't stay on the screen, it just flickers and doesn't remain constant. Also, the paddle does not move with the mouse. I'm sure I'm missing something simple, but I just can't figure it out. Help please! Here's what I have: from livewires import games import random games.init(screen_width=640, screen_height=480, fps=50) class Paddle(games.Sprite): image=games.load_image("paddle.bmp") def __init__(self, x=10): super(Paddle, self).__init__(image=Paddle.image, y=games.mouse.y, left=10) self.score=games.Text(value=0, size=25, top=5, right=games.screen.width - 10) games.screen.add(self.score) def update(self): self.y=games.mouse.y if self.top<0: self.top=0 if self.bottom>games.screen.height: self.bottom=games.screen.height self.check_collide() def check_collide(self): for ball in self.overlapping_sprites: self.score.value+=1 ball.handle_collide() class Ball(games.Sprite): image=games.load_image("ball.bmp") speed=5 def __init__(self, x=90, y=90): super(Ball, self).__init__(image=Ball.image, x=x, y=y, dx=Ball.speed, dy=Ball.speed) def update(self): if self.right>games.screen.width: self.dx=-self.dx if self.bottom>games.screen.height or self.top<0: self.dy=-self.dy if self.left<0: self.end_game() self.destroy() def handle_collide(self): self.dx=-self.dx def end_game(self): end_message=games.Message(value="Game Over", size=90, x=games.screen.width/2, y=games.screen.height/2, lifetime=250, after_death=games.screen.quit) games.screen.add(end_message) def main(): background_image=games.load_image("background.bmp", transparent=False) games.screen.background=background_image paddle_image=games.load_image("paddle.bmp") the_paddle=games.Sprite(image=paddle_image, x=10, y=games.mouse.y) games.screen.add(the_paddle) ball_image=games.load_image("ball.bmp") the_ball=games.Sprite(image=ball_image, x=630, y=200, dx=2, dy=2) games.screen.add(the_ball) games.mouse.is_visible=False games.screen.event_grab=True games.screen.mainloop() main() A: I can't help you because you did not post the complete code here. At least, I do not see where you're updating the positions of the sprites (self.x += self.dx somewhere?) and updating the draw to screen. You're also not utilising your classes in the main() function. That said, I'm seeing def __init__(self, x=10): and inside the constructor you never used the x variable. That worries me, too. Consider using the Paddle and Ball class as a Sprite, like the following: if __name__ == '__main__': background_image = games.load_image("background.bmp", transparent=False) games.screen.background = background_image the_paddle = Puddle() games.screen.add(the_paddle) the_ball = Ball() games.screen.add(the_ball) games.mouse.is_visible = False games.screen.event_grab = True games.screen.mainloop() Note I've taken the liberty to make your code read more Pythonic. I have never used livewires, however, so my code may not function. But it should point you to the right direction. Good luck! A: Why are you using livewires? You can use only pygame for a pong game. import pygame pygame.init() screen = pygame.display.set_mode((640, 480)) # window size pygame.display.set_caption("Simple pong") # window title # this is a rect that contains the ball # at the beginning it is set in the center of the screen ball_rect = pygame.Rect((312, 232), (16, 16)) # speed of the ball (x, y) ball_speed = [4, 4] # this contains your paddle # vertically centered on the left side paddle_rect = pygame.Rect((8, 200), (8, 80)) # 1 point if you hit the ball # -5 point if you miss the ball score = 0 # load the font for displaying the score font = pygame.font.Font(None, 30) # mainloop while True: # event handler for event in pygame.event.get(): # quit event => close the game if event.type == pygame.QUIT: exit(0) # control the paddle with the mouse elif event.type == pygame.MOUSEMOTION: paddle_rect.centery = event.pos[1] # correct paddle position if it's going out of window if paddle_rect.top < 0: paddle_rect.top = 0 elif paddle_rect.bottom >= 480: paddle_rect.bottom = 480 # this test if up or down keys are pressed # if yes move the paddle if pygame.key.get_pressed()[pygame.K_UP] and paddle_rect.top > 0: paddle_rect.top -= 5 elif pygame.key.get_pressed()[pygame.K_DOWN] and paddle_rect.bottom < 480: paddle_rect.top += 5 # update ball position # this move the ball ball_rect.left += ball_speed[0] ball_rect.top += ball_speed[1] # these two if block control if the ball is going out on the screen # if it's going it reverse speed to simulate a bounce if ball_rect.top <= 0 or ball_rect.bottom >= 480: ball_speed[1] = -ball_speed[1] if ball_rect.right >= 640: ball_speed[0] = -ball_speed[0] # this control if the ball touched the left side elif ball_rect.left <= 0: score -= 5 # reset the ball to the center ball_rect = pygame.Rect((312, 232), (16, 16)) # test if the ball is hit by the paddle # if yes reverse speed and add a point if paddle_rect.colliderect(ball_rect): ball_speed[0] = -ball_speed[0] score += 1 # clear screen screen.fill((255, 255, 255)) # draw the ball, the paddle and the score pygame.draw.rect(screen, (0, 0, 0), paddle_rect) # paddle pygame.draw.circle(screen, (0, 0, 0), ball_rect.center, ball_rect.width/2) # ball score_text = font.render(str(score), True, (0, 0, 0)) screen.blit(score_text, (320-font.size(str(score))[0]/2, 5)) # score # update screen and wait 20 milliseconds pygame.display.flip() pygame.time.delay(20)
Single player 'pong' game
I am just starting out learning pygame and livewires, and I'm trying to make a single-player pong game, where you just hit the ball, and it bounces around until it passes your paddle (located on the left side of the screen and controlled by the mouse), which makes you lose. I have the basic code, but the ball doesn't stay on the screen, it just flickers and doesn't remain constant. Also, the paddle does not move with the mouse. I'm sure I'm missing something simple, but I just can't figure it out. Help please! Here's what I have: from livewires import games import random games.init(screen_width=640, screen_height=480, fps=50) class Paddle(games.Sprite): image=games.load_image("paddle.bmp") def __init__(self, x=10): super(Paddle, self).__init__(image=Paddle.image, y=games.mouse.y, left=10) self.score=games.Text(value=0, size=25, top=5, right=games.screen.width - 10) games.screen.add(self.score) def update(self): self.y=games.mouse.y if self.top<0: self.top=0 if self.bottom>games.screen.height: self.bottom=games.screen.height self.check_collide() def check_collide(self): for ball in self.overlapping_sprites: self.score.value+=1 ball.handle_collide() class Ball(games.Sprite): image=games.load_image("ball.bmp") speed=5 def __init__(self, x=90, y=90): super(Ball, self).__init__(image=Ball.image, x=x, y=y, dx=Ball.speed, dy=Ball.speed) def update(self): if self.right>games.screen.width: self.dx=-self.dx if self.bottom>games.screen.height or self.top<0: self.dy=-self.dy if self.left<0: self.end_game() self.destroy() def handle_collide(self): self.dx=-self.dx def end_game(self): end_message=games.Message(value="Game Over", size=90, x=games.screen.width/2, y=games.screen.height/2, lifetime=250, after_death=games.screen.quit) games.screen.add(end_message) def main(): background_image=games.load_image("background.bmp", transparent=False) games.screen.background=background_image paddle_image=games.load_image("paddle.bmp") the_paddle=games.Sprite(image=paddle_image, x=10, y=games.mouse.y) games.screen.add(the_paddle) ball_image=games.load_image("ball.bmp") the_ball=games.Sprite(image=ball_image, x=630, y=200, dx=2, dy=2) games.screen.add(the_ball) games.mouse.is_visible=False games.screen.event_grab=True games.screen.mainloop() main()
[ "I can't help you because you did not post the complete code here. At least, I do not see where you're updating the positions of the sprites (self.x += self.dx somewhere?) and updating the draw to screen. You're also not utilising your classes in the main() function.\nThat said, I'm seeing\n def __init__(self, x=10...
[ 1, 1 ]
[]
[]
[ "livewires", "pygame", "python" ]
stackoverflow_0002674288_livewires_pygame_python.txt
Q: Dynamically add base class? Let's say I have a base class defined as follows: class Form(object): class Meta: model = None method = 'POST' Now a developer comes a long and defines his subclass like: class SubForm(Form): class Meta: model = 'User' Now suddenly the method attribute is lost. How can I "get it back" without forcing the user to inherit his meta class from mine? Can I dynamically add a base class to Form.Meta in the initializer, or in a metaclass's __new__ func? A: As long as they won't override your __init__, or it will be called (ie by super), you can monkey-patch the Meta inner class: class Form(object): class Meta: model = None method = "POST" def __init__(self, *args, **kwargs): if self.__class__ != Form: self.Meta.__bases__ += (Form.Meta,) # other __init__ code here. class SubForm(Form): class Meta: model = 'User' A: Do you really need Meta to be defined that way? If you only need to access it as form.Meta.method, why wouldn't you just use a dotdict? class dotdict(dict): def __getattr__(self, attr): return self.get(attr, None) __setattr__= dict.__setitem__ __delattr__= dict.__delitem__ Then you can do this: class Form(object): def __init__(self): self.Meta = dotdict() self.Meta.model = None self.Meta.method = 'POST' class SubForm(Form): def __init__(self): Form.__init__(self) self.Meta.model = 'User' A: You can check for method attribute in the __init__ method of a parent object and update it if needed. Of course this will work only if the programmer you are protecting your code from will call it in his constructor. class Form(object): def __init__(self): if not getattr(self.Meta,'method',False): self.Meta.method='POST' class Meta: model = None method = 'POST' class SubForm(Form): class Meta: model = 'User' A: Maybe you could use a metaclass like this: class _Meta: model = None method = "Post" class MetaForm(type): def __init__(cls, name, bases, dct): super(MetaForm, cls).__init__(name, bases, dct) if hasattr(cls, 'Meta'): meta = getattr(cls, 'Meta') for k,v in _Meta.__dict__.items(): check = meta.__dict__.get(k) if not check: meta.__dict__[k] = v else: setattr(cls, "Meta", _Meta) class Form(object): __metaclass__ = MetaForm class SubForm(Form): class Meta: model = 'User' class Sub2Form(Form): pass sub_form = SubForm() sub2_form = Sub2Form() print sub_form.Meta.method # prints "Post" print sub2_form.Meta.model # prints None The code is really simple and maybe you need to suit it to your needs. A: Maybe I could omit the default Meta class inside Form and use a default dict instead? meta_defaults = {'model':None, 'method':'POST'} meta_vars = meta_defaults meta_vars.update(Form.Meta.__dict__)
Dynamically add base class?
Let's say I have a base class defined as follows: class Form(object): class Meta: model = None method = 'POST' Now a developer comes a long and defines his subclass like: class SubForm(Form): class Meta: model = 'User' Now suddenly the method attribute is lost. How can I "get it back" without forcing the user to inherit his meta class from mine? Can I dynamically add a base class to Form.Meta in the initializer, or in a metaclass's __new__ func?
[ "As long as they won't override your __init__, or it will be called (ie by super), you can monkey-patch the Meta inner class:\nclass Form(object):\n class Meta:\n model = None\n method = \"POST\"\n\n def __init__(self, *args, **kwargs):\n if self.__class__ != Form:\n self.Meta....
[ 9, 4, 1, 1, 0 ]
[]
[]
[ "inheritance", "python", "python_2.6", "syntax" ]
stackoverflow_0003169502_inheritance_python_python_2.6_syntax.txt
Q: Executing Python program on web Can I use os.system() or subprocess.call() to execute a Python program on a webserver? I mean can I write these functions in a .py script and run it from a web browser and expect the program to be executed? Thanks a lot. EDIT: Sorry for all the confusion, I am giving you more background to my problem. The reason I am trying to do is this. I have a Python program that accepts an XML file and returns me TTF file. I run that program in terminal like this: ttx somefile.xml After which it does all the work and generates a ttf file. Now when I deploy this script as a module on web server. I use a to allow user to browse and select the XML file. Then I read the file data to temporary file and then pass the file to the module script to be executed like this: ttx.main([temp_filename]) Is this right way to do it? Because at this point, I don't get any error in the log or in browser. I get blank screen. When this didn't work, I was going to try os.system or subprocess.call A: You do not use os.system or subprocess.call to execute something as a cgi process. Maybe you should read the Python cgi tutorial here: http://www.cs.virginia.edu/~lab2q/ If you want your cgi process to communicate with another process on your local machine, you might want to look at "REST frameworks" for Python. A: Yes, I do it all the time. Import as you would do normally, stick your .py in your cgi-bin folder and make sure the server is capable of handling python. A: Another option would be to simply create an application on Google's App Engine. That gives you oodles of resources and APIs for Python execution. http://code.google.com/appengine A: So long as your server is configured to run CGI scripts (Apache's documentation for that is here, for example), yes, you can execute a python script from a webserver. Simply make sure the script is in the appropriate cgi-bin/ directory and that the file has executable permission on the server. With regards to your comments: You can, if you really want, explicitly allow other folders on the server to run executable code. I don't know what server you're using, but on Apache this is done by setting Option +ExecCGI for the folder you want. Again, see the docs I linked to. You need to give an absolute path with respect to the server. As an example, a site I develop has the layout: /public_html/cgi-bin/ When I want to access .cgi or .py files, the url for the site is something like http://chess.narnia.homeunix.com/cgi-bin/index.cgi. You can also set up re-directs to certain files if you want. One way to pass parameters through your browser is to append them to the URL like an HTTP POST method. Here's a good example of doing that. Is that what you were looking for with your question, or did you want to actually invoke the python script with os.system()? A: I've done it quite a bit in classic ASP on IIS 5 and above. I would have the ASP engine execute python code (instead of, e.g., vbscript (hearkening back to the old days, here)). Behind those asp pages would be python modules written in straight python that could be imported and could execute pretty much arbitrary code. As others have mentioned, the effective user needs to have execute permission on the thing you're trying to execute.
Executing Python program on web
Can I use os.system() or subprocess.call() to execute a Python program on a webserver? I mean can I write these functions in a .py script and run it from a web browser and expect the program to be executed? Thanks a lot. EDIT: Sorry for all the confusion, I am giving you more background to my problem. The reason I am trying to do is this. I have a Python program that accepts an XML file and returns me TTF file. I run that program in terminal like this: ttx somefile.xml After which it does all the work and generates a ttf file. Now when I deploy this script as a module on web server. I use a to allow user to browse and select the XML file. Then I read the file data to temporary file and then pass the file to the module script to be executed like this: ttx.main([temp_filename]) Is this right way to do it? Because at this point, I don't get any error in the log or in browser. I get blank screen. When this didn't work, I was going to try os.system or subprocess.call
[ "You do not use os.system or subprocess.call to execute something as a cgi process.\nMaybe you should read the Python cgi tutorial here:\nhttp://www.cs.virginia.edu/~lab2q/\nIf you want your cgi process to communicate with another process on your local machine, you might want to look at \"REST frameworks\" for Pyth...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003257900_python.txt
Q: How much leeway do I have to leave myself to learn a new language? I'm a relatively new hire, and I'm starting on a small, fairly simple project. The language that this project will be implemented in is still to be determined. The question basically boils down to - Java or Python? Here's the dilemma: My manager would prefer it to be done in Python. I don't object to that, but I have no experience in Python. I'd really love to learn Python and think I could manage it fairly quickly (especially as it's a small project). BUT the project is due at the end of March and must be ready by then. So they'd rather have it in Java and on time than in Python and late, and they don't want to pressure me to do it in Python if I think I can't make it on time. Sorry about the background - but my question basically is, how long does it take, on average, to adapt to a new language? I know this is subjective and personalized, and depends on how fast the particular programmer is... but talking about an average programmer, or even a somewhat fast one that picks up things quickly, what percentage of an increase does programming in a non-native language (but with similar concepts) cause? As in, if this project would take me about 2 weeks in Java or a .NET language, how much longer can it take me in Python? Can I assume that having double the amount of time (i.e. a new, unfamiliar language causes a 50% increase in programming time) is adequate? And included in this question - from what I've heard, it seems to be pretty easy/intuitive to switch over from Java to Python. Is this true...? Thanks everyone for all the answers! I didn't realize there are so many sides to this question... I will try to choose an answer soon - each response made me look at it a different way and it's hard to choose one answer. A: I think it depends on the area of the project. While GUI is not hard in Python, any kind of GUI-framework will have a somewhat steep learning curve. If it is a webapp, I'd say go for Python. The added time for learning is quickly gained back by easy of use of the many Python webframeworks. The big risk is that you will code Python just like you code Java. Many of the things true in Java are not true in Python and vice versa. It will probably make your Python code slow and verbose. If you decide to try Python, read up on common pitfalls coming from Java, for example: http://dirtsimple.org/2004/12/python-is-not-java.html A: You have roughly 5 weeks to complete the project. If you're confident the Java version would take 2 weeks, that leaves 3 weeks to flail around with the Python version until you have to give up. I say go for it. Python is relatively easy to pick up. I think three weeks of work is enough to time to know whether you can finish by the deadline. IMHO, this is a great excuse for you to learn a new language. Keep updating your manager regularly with your progress. I think the right decision will become apparent as time goes on. A: My boss's rule of thumb is any time there's a learning curve, it can triple the time to write the application. So, if Java would take you two weeks, then Python may take about 6. A: It always take longer than you think. Try writing a small program doing just a bit of what you need. If you are to write a program with a GUI then make small program showing a frame with Hello World and an Ok-button and see how hard that is. A: Python is like baby java, you'll pick it up in a breeze. A: Well I would say how fast you pick up Python also depends on what other languages you know(or comfortable) apart from Java. If the only language you know is Java then I don't think the switch from Java to Python would be intuitive or smooth. To start with Java is statically typed and Python is dynamically typed, and it takes some time to get used to OO programming with Python even if you are skilled in using OO techniques using Java. So I would say honor the timeline and finish the project in time (or earlier :) using Java since this is what your work demands. Keep learning Python and automate some of the routine activities you do using Python so that you get a reasonable level of confidence to work on new project using Python. A: If you Google for "Pythonic", you'll find a lot of discussion about how to do things in ways that fit well in Python, will be easy to understand by other Python users, and so on. It always takes a while to progress from code that simply works in a language to using that language well -- and in the case of Python, that learning curve is a bit longer than normal. In the end, I'd say the answer depends on your age and personality (and your perception of the "personality" of your employer). Relatively speaking, Java is the conservative approach -- it reduces risks and probably gives the best chance of finishing the job on time and within budget. Using a language you don't know increases the risk of not delivering what's needed. Chances are that you'll end up writing it (at least) twice, once in a form that's pretty similar to what you would have done in Java, and then again in a form that's more Pythonic. That may well mean some late nights, especially if you get down to a week to go (or something on that order) and realize you need (or badly want) to rewrite almost everything you've done so far. It mostly comes down to a question of whether you're comfortable with assuming that risk. A: I'd say if you want to avoid possible headaches, do it in Java and learn Python at home, by trying to re-create a similar application to the one you do at work, if you want something which feels real. It's likely that if you arent familiar with Python you arent going to take advantage of its capabilities anyway. Once I took a look at the first Python application I made, and it looked like I wrote an Object Pascal application in Python syntax A: Generally, if I'm not familiar with a language, I allow at least a month to get somewhat comfortable with it. Two or three months if it's outside my "comfort zone" of C-like languages. Having said that, I think Java and Python are similar enough that you might trim that a bit. Also, based on your own history, how good are your estimates when you're familiar with a language? If you think it will take two weeks to do it in Java, how well can you rely on that estimate? Personally, I'm sometimes way under, even when I think I'm being pessimistic, but maybe you're better at estimating than me. A part of me is tempted to say "Go for Python". That's at least partly because I'm a Python fan. However, as a new hire, you probably ought to make a good impression, and I think you'll do that better by delivering on time (or early) than by learning Python. However, if there are parts that can be cleanly separated out and done in Python, maybe you could do some parts in Java and other parts in Python. A: Are you just programming or are you designing/architecting? If you are coding according to a design that an experienced Python resource has layed-out then I'd give myself 3-4 times as long since you've described this as a small, fairly simple project. If you are designing/architecting this yourself then you're taking on a big risk by trying to learn a new language at the same time. There's too much chance that you could design something at the onset that is core to your design, only to figure-out later that it doesn't work and you need to rewrite alot of stuff because of it. That being said I would present the risks and such to your manager (showing your obvious enthusiasm for learning Python) and let him make the call. A: Charlie, being a new hire and all, you shouldn't really decide on which technology to code the project. This is a management decision. In fact, even though team skill can be used to determine the technology of choice for one or other project, there are many other, more important, things to take into account. Which technology serves your purposes well? Assuming it can really be done in python and java: Is time-to-market really important? If you need to expand your team (i.e., extend the project), will you be able to hire more Python programmers? Are they more or less expensive than Java programmers? Are there other projects in Python at your enterprise (or your clients enterprise)? A homogeneous environment is easier to administrate. Learn the differences between Java and Python and see which one applies better to the problem. For example, Python probably performs worse than Java... But Python programs can be programmed and tested way more quickly. And, of course, yes you can take into account that there's a learning curve. As another answer put it, Python is very simple, and so is Java and almost every common language out there. What kills you is learning API's, SDK's, debugging tools, environment differences, etc. Another thing, that I draw from experience: never believe that a project is done when its done. Everything changes, so when you deliver the product, either your manager or your client (whoever will use it) will ask you to change something, and once you're done with that change, there will be more. Software are living things... they only stop changing when they are dead. A: My personal preference is to learn new languages on personal projects, and use tools I already understand on professional projects. So if it was me, I'd do the project in Java, and do a few little Python projects at home. But of course, you learn a lot more a lot faster when you are using a new language "for real" forty hours a week, so if you have adequate support from management and co-workers, then take advantage of the opportunity.
How much leeway do I have to leave myself to learn a new language?
I'm a relatively new hire, and I'm starting on a small, fairly simple project. The language that this project will be implemented in is still to be determined. The question basically boils down to - Java or Python? Here's the dilemma: My manager would prefer it to be done in Python. I don't object to that, but I have no experience in Python. I'd really love to learn Python and think I could manage it fairly quickly (especially as it's a small project). BUT the project is due at the end of March and must be ready by then. So they'd rather have it in Java and on time than in Python and late, and they don't want to pressure me to do it in Python if I think I can't make it on time. Sorry about the background - but my question basically is, how long does it take, on average, to adapt to a new language? I know this is subjective and personalized, and depends on how fast the particular programmer is... but talking about an average programmer, or even a somewhat fast one that picks up things quickly, what percentage of an increase does programming in a non-native language (but with similar concepts) cause? As in, if this project would take me about 2 weeks in Java or a .NET language, how much longer can it take me in Python? Can I assume that having double the amount of time (i.e. a new, unfamiliar language causes a 50% increase in programming time) is adequate? And included in this question - from what I've heard, it seems to be pretty easy/intuitive to switch over from Java to Python. Is this true...? Thanks everyone for all the answers! I didn't realize there are so many sides to this question... I will try to choose an answer soon - each response made me look at it a different way and it's hard to choose one answer.
[ "I think it depends on the area of the project. While GUI is not hard in Python, any kind of GUI-framework will have a somewhat steep learning curve.\nIf it is a webapp, I'd say go for Python. The added time for learning is quickly gained back by easy of use of the many Python webframeworks.\nThe big risk is that y...
[ 8, 7, 5, 4, 3, 2, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "java", "python" ]
stackoverflow_0002328230_java_python.txt
Q: Overcoming os.system() limitation in Python 2.3 I am having a problem converting one of my company's scripts from csh to Python. The csh script calls an aliased command, but when I call that same aliased command via os.system(), it does not work. So, if foo is the aliased command: CSH Script (this works, executes foo): foo <argument> Python (this does not work, error claims foo is an unknown command): os.system("foo <argument>") I figure there must be some kind of context switch happening when I execute the python script, which causes Python to not have access to the aliases created in the shell. After reading the documentation, it seems that os.system is being deprecated in favor of subprocess, and that subprocess has a shell parameter that might be able to help me out...problem is that I'm stuck using Python 2.3, and subprocess isn't available until version 2.4. I had the idea to replicate the alias in python. So, for example, say foo was aliased to cp. CSH: alias foo cp foo file1 file2 Python: os.system("alias foo cp") os.system("foo file1 file2") No dice...errors here as well: sh: line 0: alias: foo: not found sh: line 0: alias: cp: not found sh: foo: command not found My last ditch effort is to take the few lines of code that use foo and put them into their own CSH script that Python would call. But if there's a way to make this work without resorting to that, I'd love to know about it. Thanks in advance! A: What made you think os.system would use csh? It uses standard C function system, that on Unix system will call just basic /bin/sh. This will not be csh, but most probably bash, or some simpler version of it. BTW: note that what you do with shell environment in os.system will not affect subsequent calls to os.system, because each is run in different subshell. In other words, changes made to the environment are lost. And your call to alias fails, because /bin/sh uses different syntax for aliases than csh. You could workaround this by running not foo, but something along the lines: os.system("/bin/csh -i -c 'foo arg1 arg2'") Note the option -i which is supposed to force csh to read startup scripts. A: If you are willing to have the "foo" alias in Python, then perform the aliasing yourself before calling os.system: cmd = "foo file1 file2" foo_alias = "cp" cmd = re.sub("^foo ", foo_alias + " ", cmd) os.system(cmd) If the foo alias is more elaborate (with argument substitution, etc), this could be more difficult.
Overcoming os.system() limitation in Python 2.3
I am having a problem converting one of my company's scripts from csh to Python. The csh script calls an aliased command, but when I call that same aliased command via os.system(), it does not work. So, if foo is the aliased command: CSH Script (this works, executes foo): foo <argument> Python (this does not work, error claims foo is an unknown command): os.system("foo <argument>") I figure there must be some kind of context switch happening when I execute the python script, which causes Python to not have access to the aliases created in the shell. After reading the documentation, it seems that os.system is being deprecated in favor of subprocess, and that subprocess has a shell parameter that might be able to help me out...problem is that I'm stuck using Python 2.3, and subprocess isn't available until version 2.4. I had the idea to replicate the alias in python. So, for example, say foo was aliased to cp. CSH: alias foo cp foo file1 file2 Python: os.system("alias foo cp") os.system("foo file1 file2") No dice...errors here as well: sh: line 0: alias: foo: not found sh: line 0: alias: cp: not found sh: foo: command not found My last ditch effort is to take the few lines of code that use foo and put them into their own CSH script that Python would call. But if there's a way to make this work without resorting to that, I'd love to know about it. Thanks in advance!
[ "What made you think os.system would use csh? It uses standard C function system, that on Unix system will call just basic /bin/sh. This will not be csh, but most probably bash, or some simpler version of it.\nBTW: note that what you do with shell environment in os.system will not affect subsequent calls to os.syst...
[ 8, 0 ]
[]
[]
[ "alias", "csh", "os.system", "python", "subprocess" ]
stackoverflow_0003258229_alias_csh_os.system_python_subprocess.txt
Q: Is there a folder layout structure for Django websites? I am trying to get an overview of a Django website application structure. The way I have done this in the past with other frameworks (Symfony, RoR etc) is to look at the application folder structure, work out which bits go where, and then work my way on from there onwards. I have been searching online for similar info about Django website folder structure - but have been unable to find one. Is there a recommended folder structure for Django apps? - and if yes, where I can obtain the document that details this? A: Take a look at the tutorial on djangoproject.com - the directory structure is pretty clearly stated. A: Yes see Folder structure for a Django project also see Writing your first Django app, part 1 - Creating a project startproject script by default generates mysite/ __init__.py manage.py settings.py urls.py A: I think the philosophy was letting you have control over that. You can take a look at djangoproject's structure for inspiration: http://code.djangoproject.com/browser/djangoproject.com/django_website
Is there a folder layout structure for Django websites?
I am trying to get an overview of a Django website application structure. The way I have done this in the past with other frameworks (Symfony, RoR etc) is to look at the application folder structure, work out which bits go where, and then work my way on from there onwards. I have been searching online for similar info about Django website folder structure - but have been unable to find one. Is there a recommended folder structure for Django apps? - and if yes, where I can obtain the document that details this?
[ "Take a look at the tutorial on djangoproject.com - the directory structure is pretty clearly stated.\n", "Yes see \nFolder structure for a Django project\nalso see\nWriting your first Django app, part 1 - Creating a project\nstartproject script by default generates\nmysite/\n __init__.py\n manage.py\n s...
[ 2, 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003258332_django_python.txt
Q: pyinotify: Handling IN_MODIFY triggers I am trying to watch a directory, and is looking for file modifications. Thinking of using pyinotify. Problem is that while using IN_MODIFY event to check for a file change, it triggers quite a number of events if I am copying even a small file of say 12 MB to the directory over a network. I dont want to handle so many triggers. I want to only trigger a single event, after the file is copied. How do I achieve that? Any Pyinotify gurus can help A: Try changing IN_MODIFY to IN_CLOSE_WRITE. An IN_CLOSE_WRITE event occurs when a writable file is closed. That should happen only once, unless the program that is copying the file chooses to close the file multiple times. The above change is probably all you need, but if not, this basic code can be a very useful tool for seeing what events occur when. With it, you should be able to determine what event to use. # Example: loops monitoring events forever. # import pyinotify # Instanciate a new WatchManager (will be used to store watches). wm = pyinotify.WatchManager() # Associate this WatchManager with a Notifier (will be used to report and # process events). notifier = pyinotify.Notifier(wm) # Add a new watch on /tmp for ALL_EVENTS. wm.add_watch('/tmp', pyinotify.ALL_EVENTS) # Loop forever and handle events. notifier.loop()
pyinotify: Handling IN_MODIFY triggers
I am trying to watch a directory, and is looking for file modifications. Thinking of using pyinotify. Problem is that while using IN_MODIFY event to check for a file change, it triggers quite a number of events if I am copying even a small file of say 12 MB to the directory over a network. I dont want to handle so many triggers. I want to only trigger a single event, after the file is copied. How do I achieve that? Any Pyinotify gurus can help
[ "Try changing IN_MODIFY to IN_CLOSE_WRITE.\nAn IN_CLOSE_WRITE event occurs when a writable file is closed. That should happen only once, unless the program that is copying the file chooses to close the file multiple times.\nThe above change is probably all you need, but if not, this basic code\ncan be a very useful...
[ 3 ]
[]
[]
[ "file", "inotify", "pyinotify", "python" ]
stackoverflow_0003258066_file_inotify_pyinotify_python.txt
Q: How do I do threading in python? using code from this site: http://www.saltycrane.com/blog/2008/09/simplistic-python-thread-example/ The code is import time from threading import Thread def myfunc(i): print "sleeping 5 sec from thread %d" % i time.sleep(5) print "finished sleeping from thread %d" % i for i in range(10): t = Thread(target=myfunc, args=(i,)) t.start() and I get this output: sleeping 5 sec from thread 0 sleeping 5 sec from thread 1 sleeping 5 sec from thread 2 sleeping 5 sec from thread 3 sleeping 5 sec from thread 4 sleeping 5 sec from thread 5 sleeping 5 sec from thread 6 sleeping 5 sec from thread 7 sleeping 5 sec from thread 8 sleeping 5 sec from thread 9 finished sleeping from thread 0 finished sleeping from thread 2 finished sleeping from thread 4 finished sleeping from thread 1finished sleeping from thread 6finished sleeping from thread 8 finished sleeping from thread 5finished sleeping from thread 7finished sleeping from thread 9 finished sleeping from thread 3 what going on here? I am ok with the threads not printing in order because this is possible, but why are they not printing on newlines at the end? I am using python 2.6 under windows xp A: You've just discovered why programming with threads is hard :) What's happening is that all your threads are getting woken up at almost the same time. One thread starts printing out "finished sleeping from thread 1" and before it gets a chance to print that last "\n", another thread comes and prints "finished sleeping from thread 6", and on and on. Those newlines aren't being skipped, they're just moved around and bunched up elsewhere. That's probably why a line has been skipped before "finished...3". My guess is that there are many trailing blank lines that got removed due to formatting. Use threading.Lock to put synchronization around your print statements so that multiple prints can't happen at the same time. A: print implemented by multiple opcodes, specifically the newline is a seperate one. Python will context switch between opcodes: >>> def f(o): ... print o ... ... >>> from dis import dis >>> dis(f) 2 0 LOAD_FAST 0 (o) 3 PRINT_ITEM 4 PRINT_NEWLINE 5 LOAD_CONST 0 (None) 8 RETURN_VALUE A: I think they when a thread didn't print a new line it's because the control was passed to another thread before the first thread printed the new line. A: Because print isn't atomic a thread's print can be interrupted by another thread at any time. If thread1 is half done printing and thread2 interrupts it and starts printing, the output will be interleaved with thread1 and thread2's output. A: Indeed it's not thread safe to print. In your example you might want to use the logging module. Or you could create a thread safe print.
How do I do threading in python?
using code from this site: http://www.saltycrane.com/blog/2008/09/simplistic-python-thread-example/ The code is import time from threading import Thread def myfunc(i): print "sleeping 5 sec from thread %d" % i time.sleep(5) print "finished sleeping from thread %d" % i for i in range(10): t = Thread(target=myfunc, args=(i,)) t.start() and I get this output: sleeping 5 sec from thread 0 sleeping 5 sec from thread 1 sleeping 5 sec from thread 2 sleeping 5 sec from thread 3 sleeping 5 sec from thread 4 sleeping 5 sec from thread 5 sleeping 5 sec from thread 6 sleeping 5 sec from thread 7 sleeping 5 sec from thread 8 sleeping 5 sec from thread 9 finished sleeping from thread 0 finished sleeping from thread 2 finished sleeping from thread 4 finished sleeping from thread 1finished sleeping from thread 6finished sleeping from thread 8 finished sleeping from thread 5finished sleeping from thread 7finished sleeping from thread 9 finished sleeping from thread 3 what going on here? I am ok with the threads not printing in order because this is possible, but why are they not printing on newlines at the end? I am using python 2.6 under windows xp
[ "You've just discovered why programming with threads is hard :)\nWhat's happening is that all your threads are getting woken up at almost the same time. One thread starts printing out \"finished sleeping from thread 1\" and before it gets a chance to print that last \"\\n\", another thread comes and prints \"finis...
[ 6, 5, 2, 0, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003258603_multithreading_python.txt
Q: Access native windows icons for custom wxDialogs I want to subclass wx.Dialog to get a little more functionality than is provided by the wx.MessageDialog class but I would still like to be able to use the native windows icons (ie the ones used in the wx.MessageDialog that can be set by the flags such as wx.ICON_ERROR etc.. ) Is there anyway to access these? Update: Thanks to steven for pointing out that this can easily be accomplished with wx.ArtProvider e.g. wx.ArtProvider.GetBitmap(wx.ART_ERROR, wx.ART_CMN_DIALOG) A: This should do the trick: wx.ArtProvider.GetBitmap(wx.ART_ERROR, wx.ART_CMN_DIALOG) A: Not sure how you'd do in in wx, but here's a Microsoft article on how to do it with the native API: http://msdn.microsoft.com/en-us/magazine/cc188763.aspx
Access native windows icons for custom wxDialogs
I want to subclass wx.Dialog to get a little more functionality than is provided by the wx.MessageDialog class but I would still like to be able to use the native windows icons (ie the ones used in the wx.MessageDialog that can be set by the flags such as wx.ICON_ERROR etc.. ) Is there anyway to access these? Update: Thanks to steven for pointing out that this can easily be accomplished with wx.ArtProvider e.g. wx.ArtProvider.GetBitmap(wx.ART_ERROR, wx.ART_CMN_DIALOG)
[ "This should do the trick:\nwx.ArtProvider.GetBitmap(wx.ART_ERROR, wx.ART_CMN_DIALOG)\n\n", "Not sure how you'd do in in wx, but here's a Microsoft article on how to do it with the native API:\nhttp://msdn.microsoft.com/en-us/magazine/cc188763.aspx\n" ]
[ 2, 0 ]
[]
[]
[ "customdialog", "dialog", "python", "user_interface", "wxpython" ]
stackoverflow_0003257464_customdialog_dialog_python_user_interface_wxpython.txt
Q: Writing bindings and wrappers I keep seeing people writing wrappers for, say a module written in X language to use it in Y language. I wanted to know the basics of writing such wrappers. Where does one start from? My question here is more specific for libgnokii, how do I begin to write python bindings for it. A: You can start with reading this: extending python with c or c++ And then when you decide that it's too much hassle, you can check out swig or possibly Boost.Python. ctypes may also be useful. I've done manual wrapping of c++ classes and I've used swig. swig was much easier to use, but in the end I wanted to do stuff that wasn't easily done (or I was just too lazy to figure out how). So i ended up doing manual wrapping. It's a bit of work but if you know a bit of C, it's very doable. A: You can start by looking here for information on extending Python with C. You'll probably want to think about how to translate libgnokii's API into something Pythonic while you're at it. If you don't want to do a lot of work, you can just write a thin wrapper that translates all the gnokii API calls into Python functions.
Writing bindings and wrappers
I keep seeing people writing wrappers for, say a module written in X language to use it in Y language. I wanted to know the basics of writing such wrappers. Where does one start from? My question here is more specific for libgnokii, how do I begin to write python bindings for it.
[ "You can start with reading this: extending python with c or c++ And then when you decide that it's too much hassle, you can check out swig or possibly Boost.Python.\nctypes may also be useful.\nI've done manual wrapping of c++ classes and I've used swig. swig was much easier to use, but in the end I wanted to do s...
[ 7, 2 ]
[]
[]
[ "binding", "python" ]
stackoverflow_0003259033_binding_python.txt
Q: Perl's BEGIN{} block in Python I have Python code that uses the "with" keyword (new in 2.6) and I want to check if the interpreter version is at least 2.6, so I use this code: import sys if sys.version < '2.6': raise Exception( "python 2.6 required" ) However, the 2.4 interpreter chokes on the with keyword (later in the script) because it doesn't recognize the syntax, and it does this before it evaluates my check. Is there something in Python analogous to Perl's BEGIN{} block? A: Take a look here: How can I check for Python version in a program that uses new language features? A: Perhaps someone has a better answer, but my first thought would be to have a separate script to perform the check, then import the "real" script once the check has passed. Python won't check the syntax until the import happens. import sys if sys.version < '2.6': raise Exception( "python 2.6 required" ) import myscript # runs myscript
Perl's BEGIN{} block in Python
I have Python code that uses the "with" keyword (new in 2.6) and I want to check if the interpreter version is at least 2.6, so I use this code: import sys if sys.version < '2.6': raise Exception( "python 2.6 required" ) However, the 2.4 interpreter chokes on the with keyword (later in the script) because it doesn't recognize the syntax, and it does this before it evaluates my check. Is there something in Python analogous to Perl's BEGIN{} block?
[ "Take a look here:\nHow can I check for Python version in a program that uses new language features?\n", "Perhaps someone has a better answer, but my first thought would be to have a separate script to perform the check, then import the \"real\" script once the check has passed. Python won't check the syntax unti...
[ 4, 3 ]
[]
[]
[ "perl", "python", "version" ]
stackoverflow_0003259060_perl_python_version.txt
Q: sorting a list of tuples I have a list of tuples of the form (a,b,c,d) and I want to copy only those tuples with unique values of 'a' to a new list. I'm very new to python. Current idea that isn't working: for (x) in list: a,b,c,d=(x) if list.count(a)==1: newlist.append(x) A: If you don't want to add any of the tuples that have duplicate a values (as opposed to adding the first occurrence of a given a, but none of the later ones): seen = {} for x in your_list: a,b,c,d = x seen.setdefault(a, []).append(x) newlist = [] for a,x_vals in seen.iteritems(): if len(x_vals) == 1: newlist.append(x_vals[0]) A: values = {} for t in tups: a,b,c,d = t if a not in values: values[a] = (1, t) else: count, tup = values[a] values[a] = (count+1, t) unique_tups = map(lambda v: v[1], filter(lambda k: k[0] == 1, values.values())) I am using a dictionary to store a values and the tuples that have that a value. The value at that key is a tuple of (count, tuple) where count is the number of times that a has been seen. At the end, I filter the values dictionary for only those a values where the count is 1, i.e. they are unique. Then I map that list to return only those tuples, since the count value will be 1. Now, unique_tups is a list of all those tuples with unique a's. Updated after receiving feedback from commenters, thanks! A: You could use a set to keep track of the duplicates: seen_a = set() for x in list: a, b, c, d = x if a not in seen_a: newlist.append(x) seen_a.add(x) A: you could indeed sort the list and then iterate over it: xs = [(1,2,3,4), (5, 2, 3, 4), (2, 3, 3, 3), (1, 5, 2, 3)] newList = [] xs.sort() lastX = None for x in xs: if lastX: if lastX[0] == x[0]: lastX = None else: newList.append(lastX) lastX = x if lastX: newList.append(lastX)
sorting a list of tuples
I have a list of tuples of the form (a,b,c,d) and I want to copy only those tuples with unique values of 'a' to a new list. I'm very new to python. Current idea that isn't working: for (x) in list: a,b,c,d=(x) if list.count(a)==1: newlist.append(x)
[ "If you don't want to add any of the tuples that have duplicate a values (as opposed to adding the first occurrence of a given a, but none of the later ones):\nseen = {}\nfor x in your_list:\n a,b,c,d = x\n seen.setdefault(a, []).append(x)\n\nnewlist = []\nfor a,x_vals in seen.iteritems():\n if len(x_vals)...
[ 3, 2, 2, 0 ]
[]
[]
[ "list", "python", "sorting", "tuples" ]
stackoverflow_0003259159_list_python_sorting_tuples.txt
Q: Django + mod_python + apache: admin panel and urls don't work Whole this day I was trying to configure django on production server. I use mod_python. When I open http: //beta.example.com I see my site but http: //beta.example.com/admin and http: //beta.example.com/441/abc/ doesn't work: Page not found (404) Request Method: GET Request URL: http://beta.example.com/admin {'path': u'admin'} You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Page not found (404) Request Method: GET Request URL: http://beta.example.com/441/abc/ {'path': u'441/abc/'} You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. My urls: from settings import MEDIA_ROOT from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # static files url(r'^static/javascripts/(?P<path>.*)$', 'django.views.static.serve', {'document_root': MEDIA_ROOT + '/javascripts'}, name='javascripts'), url(r'^static/images/(?P<path>.*)$', 'django.views.static.serve', {'document_root': MEDIA_ROOT + '/images'}, name='images'), url(r'^static/stylesheets/(?P<path>.*)$', 'django.views.static.serve', {'document_root': MEDIA_ROOT + '/stylesheets'}, name='stylesheets'), url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': MEDIA_ROOT}, name='static'), (r'^admin/', include(admin.site.urls)), url(r'^/?$', 'content.views.index', name='root-url'), url(r'^(?P<id>[0-9]{2,5})/(?P<slug>[a-z\-]+)/?$', 'content.views.show', name='show-url'), ) Apache: DocumentRoot "/var/www/django/beta.example.com/site" <Location "/"> allow from all SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE site.settings PythonOption django.root / PythonDebug On PythonPath "['/var/www/django/beta.example.com', '/var/www/django/beta.example.com/site'] + sys.path" </Location> <Location "/static" > SetHandler none </Location> I have no idea what's wrong. A: Not sure if that will solve your problem but in my site.conf for django I had to comment the line: PythonOption django.root / to make it work. A: You really don't want to be using mod_python for deployment. I highly suggest moving to mod_wsgi for Django depoyment. A: I'm just throwing this out there, but you have to enable the django admin middleware in your settings file. It's there but commented out right out of the box. If you've done that I don't have any idea what your problem is.
Django + mod_python + apache: admin panel and urls don't work
Whole this day I was trying to configure django on production server. I use mod_python. When I open http: //beta.example.com I see my site but http: //beta.example.com/admin and http: //beta.example.com/441/abc/ doesn't work: Page not found (404) Request Method: GET Request URL: http://beta.example.com/admin {'path': u'admin'} You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Page not found (404) Request Method: GET Request URL: http://beta.example.com/441/abc/ {'path': u'441/abc/'} You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. My urls: from settings import MEDIA_ROOT from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # static files url(r'^static/javascripts/(?P<path>.*)$', 'django.views.static.serve', {'document_root': MEDIA_ROOT + '/javascripts'}, name='javascripts'), url(r'^static/images/(?P<path>.*)$', 'django.views.static.serve', {'document_root': MEDIA_ROOT + '/images'}, name='images'), url(r'^static/stylesheets/(?P<path>.*)$', 'django.views.static.serve', {'document_root': MEDIA_ROOT + '/stylesheets'}, name='stylesheets'), url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': MEDIA_ROOT}, name='static'), (r'^admin/', include(admin.site.urls)), url(r'^/?$', 'content.views.index', name='root-url'), url(r'^(?P<id>[0-9]{2,5})/(?P<slug>[a-z\-]+)/?$', 'content.views.show', name='show-url'), ) Apache: DocumentRoot "/var/www/django/beta.example.com/site" <Location "/"> allow from all SetHandler python-program PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE site.settings PythonOption django.root / PythonDebug On PythonPath "['/var/www/django/beta.example.com', '/var/www/django/beta.example.com/site'] + sys.path" </Location> <Location "/static" > SetHandler none </Location> I have no idea what's wrong.
[ "Not sure if that will solve your problem but in my site.conf for django I had to comment the line:\nPythonOption django.root /\nto make it work.\n", "You really don't want to be using mod_python for deployment. I highly suggest moving to mod_wsgi for Django depoyment. \n", "I'm just throwing this out there, bu...
[ 2, 2, 0 ]
[]
[]
[ "django", "mod_python", "python" ]
stackoverflow_0003258511_django_mod_python_python.txt
Q: Get IP Adress from a connected Windows Network Share with Python How can i manage to get the IP or path like \11.1.1.100\projects of a connected network share with a drive letter. I only have the drive letter and want to get the IP of the Share with python. Many Thanks... Sashmo A: I don't know the python equivalent, but WNetGetConnection will give you the UNC path mapped to the drive letter: wchar_t szName[256]; DWORD chName = 256; DWORD dwResult = WNetGetConnectionW(L"Z:", szName, &chName); I'm sure there is a python module that wraps this functionality. From the UNC path you can get the server name, and from that you can lookup its IP address.
Get IP Adress from a connected Windows Network Share with Python
How can i manage to get the IP or path like \11.1.1.100\projects of a connected network share with a drive letter. I only have the drive letter and want to get the IP of the Share with python. Many Thanks... Sashmo
[ "I don't know the python equivalent, but WNetGetConnection will give you the UNC path mapped to the drive letter:\nwchar_t szName[256];\nDWORD chName = 256;\nDWORD dwResult = WNetGetConnectionW(L\"Z:\", szName, &chName);\n\nI'm sure there is a python module that wraps this functionality. From the UNC path you can ...
[ 2 ]
[]
[]
[ "networking", "python", "windows" ]
stackoverflow_0003257975_networking_python_windows.txt
Q: Changing the size of a wx.ProgressDialog The size of the ProgresDialog is too narrow to hold the text that I need to display... I tryed to change the size of the dialog by calling the SetSize method on the dialog after it is created. This fixed the size of the dialog but on creation of the dialog the gauge size is initially smaller and then jumps in size to fit the dialog box size, which obviously looks nasty, is there any way to fix this or do I just have to create a custom dialog.. A: As I understand it, the ProgressDialog wraps the native platform dialog, so there may not be much you can do to fix it. To get the most flexibility, you'll have to use wx.Dialog and maybe a wx.Gauge. Mike Driscoll Blog: http://blog.pythonlibrary.org
Changing the size of a wx.ProgressDialog
The size of the ProgresDialog is too narrow to hold the text that I need to display... I tryed to change the size of the dialog by calling the SetSize method on the dialog after it is created. This fixed the size of the dialog but on creation of the dialog the gauge size is initially smaller and then jumps in size to fit the dialog box size, which obviously looks nasty, is there any way to fix this or do I just have to create a custom dialog..
[ "As I understand it, the ProgressDialog wraps the native platform dialog, so there may not be much you can do to fix it. To get the most flexibility, you'll have to use wx.Dialog and maybe a wx.Gauge.\n\nMike Driscoll\nBlog: http://blog.pythonlibrary.org\n" ]
[ 1 ]
[]
[]
[ "progressdialog", "python", "wxpython" ]
stackoverflow_0003251927_progressdialog_python_wxpython.txt
Q: interactive console for my mainloop app I have an little script which logs users that login to my Pidgin/MSN account #!/usr/bin/env python def log_names(buddy): name = str(purple.PurpleBuddyGetName(buddy)) account = purple.PurpleAccountGetUsername(purple.PurpleBuddyGetAccount(buddy)) if account == u'dummy_account@hotmail.com': try: log[name] += 1 except KeyError: log[name] = 1 log.sync() import dbus, gobject, shelve from dbus.mainloop.glib import DBusGMainLoop dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) bus = dbus.SessionBus() log = shelve.open('pidgin.log') obj = bus.get_object('im.pidgin.purple.PurpleService', '/im/pidgin/purple/PurpleObject') purple = dbus.Interface(obj, 'im.pidgin.purple.PurpleInterface') bus.add_signal_receiver(log_names, dbus_interface='im.pidgin.purple.PurpleInterface', signal_name='BuddySignedOn') loop = gobject.MainLoop() loop.run() I wanna add a simple interactive console to this which allows me to query the data from the log object, but I'm stuck at how I would implement it Do I use threads of some kind or am I able to use some sort of call back within gobject.MainLoop()? A: You should look in the direction of general GObject/GLib programming (this is where gobject.MainLoop() is coming from). You could use threads, you could use event callbacks, whatever. For example, this is a simple 'console' using event callbacks. Add this just before the loop.run(): import glib, sys, os, fcntl class IODriver(object): def __init__(self, line_callback): self.buffer = '' self.line_callback = line_callback flags = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL) flags |= os.O_NONBLOCK fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, flags) glib.io_add_watch(sys.stdin, glib.IO_IN, self.io_callback) def io_callback(self, fd, condition): chunk = fd.read() for char in chunk: self.buffer += char if char == '\n': self.line_callback(self.buffer) self.buffer = '' return True def line_entered(line): print "You have typed:", line.strip() d = IODriver(line_entered) If you are building a PyGTK application, you don't have to call the mainloop specially for the dbus, because it will use the main application's mainloop. There also other mainloops for other libraries available, for example dbus.mainloop.qt for PyQt4.
interactive console for my mainloop app
I have an little script which logs users that login to my Pidgin/MSN account #!/usr/bin/env python def log_names(buddy): name = str(purple.PurpleBuddyGetName(buddy)) account = purple.PurpleAccountGetUsername(purple.PurpleBuddyGetAccount(buddy)) if account == u'dummy_account@hotmail.com': try: log[name] += 1 except KeyError: log[name] = 1 log.sync() import dbus, gobject, shelve from dbus.mainloop.glib import DBusGMainLoop dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) bus = dbus.SessionBus() log = shelve.open('pidgin.log') obj = bus.get_object('im.pidgin.purple.PurpleService', '/im/pidgin/purple/PurpleObject') purple = dbus.Interface(obj, 'im.pidgin.purple.PurpleInterface') bus.add_signal_receiver(log_names, dbus_interface='im.pidgin.purple.PurpleInterface', signal_name='BuddySignedOn') loop = gobject.MainLoop() loop.run() I wanna add a simple interactive console to this which allows me to query the data from the log object, but I'm stuck at how I would implement it Do I use threads of some kind or am I able to use some sort of call back within gobject.MainLoop()?
[ "You should look in the direction of general GObject/GLib programming (this is where gobject.MainLoop() is coming from). You could use threads, you could use event callbacks, whatever. For example, this is a simple 'console' using event callbacks. Add this just before the loop.run():\nimport glib, sys, os, fcntl\n\...
[ 3 ]
[]
[]
[ "dbus", "interactive", "python" ]
stackoverflow_0003148264_dbus_interactive_python.txt
Q: Can a PyQt program consume a DBus interface that exposes custom C++ types (marhsalled via Qt's MetaType system)? If so, how? I have a Qt/C++ application that exposes some custom C++ classes via DBus methods (by registering them as MetaTypes, and using annotations in the xml), and I want my PyQt program to consume these methods. The problem I see is that the exposed types are C++ classes, not python, so how can I make python aware of these classes? A: There is no such thing as 'C++ classes' in D-Bus, it is language-agnostic. All methods, functions, etc. have type signatures expressible in basic D-Bus types (see the spec). Just call those classes, and it should work.
Can a PyQt program consume a DBus interface that exposes custom C++ types (marhsalled via Qt's MetaType system)? If so, how?
I have a Qt/C++ application that exposes some custom C++ classes via DBus methods (by registering them as MetaTypes, and using annotations in the xml), and I want my PyQt program to consume these methods. The problem I see is that the exposed types are C++ classes, not python, so how can I make python aware of these classes?
[ "There is no such thing as 'C++ classes' in D-Bus, it is language-agnostic. All methods, functions, etc. have type signatures expressible in basic D-Bus types (see the spec). Just call those classes, and it should work.\n" ]
[ 0 ]
[]
[]
[ "c++", "dbus", "pyqt", "python", "qt" ]
stackoverflow_0003181156_c++_dbus_pyqt_python_qt.txt
Q: Numpy interconversion between multidimensional and linear indexing I'm looking for a fast way to interconvert between linear and multidimensional indexing in Numpy. To make my usage concrete, I have a large collection of N particles, each assigned 5 float values (dimensions) giving an Nx5 array. I then bin each dimension using numpy.digitize with an appropriate choice of bin boundaries to assign each particle a bin in the 5 dimensional space. N = 10 ndims = 5 p = numpy.random.normal(size=(N,ndims)) for idim in xrange(ndims): bbnds[idim] = numpy.array([-float('inf')]+[-2.,-1.,0.,1.,2.]+[float('inf')]) binassign = ndims*[None] for idim in xrange(ndims): binassign[idim] = numpy.digitize(p[:,idim],bbnds[idim]) - 1 binassign then contains rows that correspond to the multidimensional index. If I then want to convert the multidimensional index to a linear index, I think I would want to do something like: linind = numpy.arange(6**5).reshape(6,6,6,6,6) This would give a look-up for each multidimensional index to map it to a linear index. You could then go back using: mindx = numpy.unravel_index(x,linind.shape) Where I'm having difficulties is figuring out how to take binassign (the Nx5 array) containing the multidimensional index in each row, and coverting that to an 1d linear index, by using it to slice the linear indexing array linind. If anyone has a one (or several) line indexing trick to go back and forth between the multidimensional index and the linear index in a way that vectorizes the operation for all N particles, I would appreciate your insight. A: You can simply calculate the index of each bin: box_indices = numpy.dot(ndims**numpy.arange(ndims), binassign) The scalar product simply does 1*x0 + 5*x1 + 5*5*x2 +… This is done very efficiently through NumPy's dot(). A: Although I very much like EOL's answer, I wanted to generalize it a bit for non-uniform numbers of bins along each direction, and also to highlight the differences between C and F styles of ordering. Here is an example solution: ndims = 5 N = 10 # Define bin boundaries binbnds = ndims*[None] nbins = [] for idim in xrange(ndims): binbnds[idim] = numpy.linspace(-10.0,10.0,numpy.random.randint(2,15)) binbnds[idim][0] = -float('inf') binbnds[idim][-1] = float('inf') nbins.append(binbnds[idim].shape[0]-1) nstates = numpy.cumprod(nbins)[-1] # Define variable values for N particles in ndims dimensions p = numpy.random.normal(size=(N,ndims)) # Assign to bins along each dimension binassign = ndims*[None] for idim in xrange(ndims): binassign[idim] = numpy.digitize(p[:,idim],binbnds[idim]) - 1 binassign = numpy.array(binassign) # multidimensional array with elements mapping from multidim to linear index # Two different arrays for C vs F ordering linind_C = numpy.arange(nstates).reshape(nbins,order='C') linind_F = numpy.arange(nstates).reshape(nbins,order='F') and now make the conversion # Fast conversion to linear index b_F = numpy.cumprod([1] + nbins)[:-1] b_C = numpy.cumprod([1] + nbins[::-1])[:-1][::-1] box_index_F = numpy.dot(b_F,binassign) box_index_C = numpy.dot(b_C,binassign) and to check for correctness: # Check print 'Checking correct mapping for each particle F order' for k in xrange(N): ii = box_index_F[k] jj = linind_F[tuple(binassign[:,k])] print 'particle %d %s (%d %d)' % (k,ii == jj,ii,jj) print 'Checking correct mapping for each particle C order' for k in xrange(N): ii = box_index_C[k] jj = linind_C[tuple(binassign[:,k])] print 'particle %d %s (%d %d)' % (k,ii == jj,ii,jj) And for completeness, if you want to go back from the 1d index to the multidimensional index in a fast, vectorized-style way: print 'Convert C-style from linear to multi' x = box_index_C.reshape(-1,1) bassign_rev_C = x / b_C % nbins print 'Convert F-style from linear to multi' x = box_index_F.reshape(-1,1) bassign_rev_F = x / b_F % nbins and again to check: print 'Check C-order' for k in xrange(N): ii = tuple(binassign[:,k]) jj = tuple(bassign_rev_C[k,:]) print ii==jj,ii,jj print 'Check F-order' for k in xrange(N): ii = tuple(binassign[:,k]) jj = tuple(bassign_rev_F[k,:]) print ii==jj,ii,jj
Numpy interconversion between multidimensional and linear indexing
I'm looking for a fast way to interconvert between linear and multidimensional indexing in Numpy. To make my usage concrete, I have a large collection of N particles, each assigned 5 float values (dimensions) giving an Nx5 array. I then bin each dimension using numpy.digitize with an appropriate choice of bin boundaries to assign each particle a bin in the 5 dimensional space. N = 10 ndims = 5 p = numpy.random.normal(size=(N,ndims)) for idim in xrange(ndims): bbnds[idim] = numpy.array([-float('inf')]+[-2.,-1.,0.,1.,2.]+[float('inf')]) binassign = ndims*[None] for idim in xrange(ndims): binassign[idim] = numpy.digitize(p[:,idim],bbnds[idim]) - 1 binassign then contains rows that correspond to the multidimensional index. If I then want to convert the multidimensional index to a linear index, I think I would want to do something like: linind = numpy.arange(6**5).reshape(6,6,6,6,6) This would give a look-up for each multidimensional index to map it to a linear index. You could then go back using: mindx = numpy.unravel_index(x,linind.shape) Where I'm having difficulties is figuring out how to take binassign (the Nx5 array) containing the multidimensional index in each row, and coverting that to an 1d linear index, by using it to slice the linear indexing array linind. If anyone has a one (or several) line indexing trick to go back and forth between the multidimensional index and the linear index in a way that vectorizes the operation for all N particles, I would appreciate your insight.
[ "You can simply calculate the index of each bin:\nbox_indices = numpy.dot(ndims**numpy.arange(ndims), binassign)\n\nThe scalar product simply does 1*x0 + 5*x1 + 5*5*x2 +… This is done very efficiently through NumPy's dot().\n", "Although I very much like EOL's answer, I wanted to generalize it a bit for non-unif...
[ 4, 3 ]
[]
[]
[ "indexing", "numpy", "python" ]
stackoverflow_0003257619_indexing_numpy_python.txt
Q: Application is not working under raw system I've an python GUI application, I use pyQt4. I build binary with bbfreeze (before I was using py2exe but it didn't work with email module well). On system where I build this app, everything works properly, but when I install it on raw windows (without all those vc_redist and set of python libraries) binary does not work. Where should I start to find a solution, since I have no messages/exceptions/crashes, it simply ends immediately after i run it from command line. I predict that if I'd install some of tools from "build system" I would run it. Is this the only way? I mean, if I would find the missing lib (if it's a lib problem), would adding this library to bbfreeze script would solve this problem? cheers P. A: Get Dependency Walker, and run depends.exe on your executable. It will examine the full tree of DLL dependencies, and mark with a red error the ones that are missing. It will likely be a MSCVRTxx.dll.
Application is not working under raw system
I've an python GUI application, I use pyQt4. I build binary with bbfreeze (before I was using py2exe but it didn't work with email module well). On system where I build this app, everything works properly, but when I install it on raw windows (without all those vc_redist and set of python libraries) binary does not work. Where should I start to find a solution, since I have no messages/exceptions/crashes, it simply ends immediately after i run it from command line. I predict that if I'd install some of tools from "build system" I would run it. Is this the only way? I mean, if I would find the missing lib (if it's a lib problem), would adding this library to bbfreeze script would solve this problem? cheers P.
[ "Get Dependency Walker, and run depends.exe on your executable. It will examine the full tree of DLL dependencies, and mark with a red error the ones that are missing.\nIt will likely be a MSCVRTxx.dll.\n" ]
[ 1 ]
[]
[]
[ "py2exe", "pyqt", "python", "windows" ]
stackoverflow_0003259993_py2exe_pyqt_python_windows.txt
Q: Running a python script from ArcMap running a python script from within ESRI's ArcMap and it calls another python script (or at least attempts to call it) using the subprocess module. However, the system window that it executes in (DOS window) comes up only very briefly and enough for me to see there is an error but goes away too quickly for me to actually read it and see what the error is! Does anyone know of a way to "pause" the DOS window or possibly pipe the output of it to a file or something using python? Here is my code that calls the script that pops up the DOS window and has the error in it: py_path2="C:\Python25\python.exe" py_script2="C:\DataDownload\PythonScripts\DownloadAdministrative.py" subprocess.call([py_path2, py_script2]) Much appreciated! Cheers A: Try doing a raw_input() command at the end of your script (it's input() in Python 3). This will pause the script and wait for keyboard input. If the script raises an exception, you will need to catch it and then issue the command. Also, there are ways to read the stdout and stderr streams of your command, try looking at subprocess.Popen arguments at http://docs.python.org/library/subprocess.html. A: subprocess.call accepts the same arguments as Popen. See http://docs.python.org/library/subprocess.html You are especially interested in argument stderr, I think. Perhaps something like that would help: err = fopen('logfile', 'w') subprocess.call([py_path2, py_script2], stderr=err) err.close() You could do more if you used Popen directly, without wrapping it around in call.
Running a python script from ArcMap
running a python script from within ESRI's ArcMap and it calls another python script (or at least attempts to call it) using the subprocess module. However, the system window that it executes in (DOS window) comes up only very briefly and enough for me to see there is an error but goes away too quickly for me to actually read it and see what the error is! Does anyone know of a way to "pause" the DOS window or possibly pipe the output of it to a file or something using python? Here is my code that calls the script that pops up the DOS window and has the error in it: py_path2="C:\Python25\python.exe" py_script2="C:\DataDownload\PythonScripts\DownloadAdministrative.py" subprocess.call([py_path2, py_script2]) Much appreciated! Cheers
[ "Try doing a raw_input() command at the end of your script (it's input() in Python 3). \nThis will pause the script and wait for keyboard input. If the script raises an exception, you will need to catch it and then issue the command.\nAlso, there are ways to read the stdout and stderr streams of your command, try l...
[ 0, 0 ]
[]
[]
[ "esri", "python" ]
stackoverflow_0003259999_esri_python.txt
Q: Create multiple buttons with consecutive integers in name I have the following python code and I was wondering if it's possible to create those buttons in a for loop instead? I was thinking of modifying the local namespace but I'm not sure if that's a good idea. I really want the buttons to be named so that it's named consecutively. self.todo1 = wx.TextCtrl(self, -1, "") self.timer_label1 = wx.StaticText(self, -1, "00:00") self.set_timer1 = wx.Button(self, -1, "Set Timer") self.todo2 = wx.TextCtrl(self, -1, "") self.timer_label2 = wx.StaticText(self, -1, "00:00") self.set_timer2 = wx.Button(self, -1, "Set Timer") self.todo3 = wx.TextCtrl(self, -1, "") self.timer_label3 = wx.StaticText(self, -1, "00:00") self.set_timer3 = wx.Button(self, -1, "Set Timer") self.todo4 = wx.TextCtrl(self, -1, "") self.timer_label4 = wx.StaticText(self, -1, "00:00") self.set_timer4 = wx.Button(self, -1, "Set Timer") self.todo5 = wx.TextCtrl(self, -1, "") self.timer_label5 = wx.StaticText(self, -1, "00:00") self.set_timer5 = wx.Button(self, -1, "Set Timer") A: I think the built-in setattr method is probably your best friend here. Something like this should work: for i in range(1,6): setattr(self,'todo%d' % i,wx.TextCtrl(self, -1, "")) setattr(self,'timer_label%d' % i, wx.StaticText(self,-1,"00:00")) setattr(self,'set_timer%d' % i, wx.Button(self,-1,"Set Timer")) Just remember that doing: object.x = y Is the same as doing: setattr(object,'x',y) Hope that helps! A: use a dict: self.set_timer = {} self.timer_label = {} self.text_timer = {} for i in range(1,5): self.text_timer[i] = wx.TextCtrl(self, -1, "") self.timer_label[i] = wx.StaticText(self, -1, "00:00") self.set_timer[i] = wx.Button(self, -1, "Set Timer") A: I recommend against doing this. Instead, an easy and expandable approach is to make a class for each timer object. Looking at the implied functionality in your question, you're going to want to display the time correctly, reset it, take input from the text ctrl, etc, and you're code will be easier to maintain if you encapsulate all of this in a class rather than through many named variables that are distinguished by the integers in their names. Here's an example. class TimerCtrl(object): def __init__(self, parent, label_number): self.todo = wx.TextCtrl(parent, -1, "") self.timer_label = wx.StaticText(parent, -1, "00:00") self.button = wx.Button(parent, -1, "Set Timer %i" % label_number) self.label_number = label_number # and then in your other class, which I assume is some type of wx.Window self.timer_controls = [] for i in range(5): self.timer_controls.append( TimerCtrl(self, i+1) ) Note that I'm not making any attempt at clever indexing of the TimerCtrl instances but instead I'm just collecting them all -- clever indexing breaks easier and usually isn't worth the hassle. Instead find a way to let the objects do the work for you. Also, you may want to have TimerCtrl inherit from a wx.Panel, or some such thing. A: Personally, I'd do something like this: ---------------------------------------------------------------------- def btnBuilder(): """""" btnNum = 1 for btn in range(5): btn = wx.Button(panel, "Set Timer", name="set_timer%s" % btnNum) btn.Bind(wx.EVT_BUTTON, self.onButton) btnNum += 1 ---------------------------------------------------------------------- def onButton(self, event): """""" btn = event.GetEventObject() btnName = btn.GetName() if btnName == "set_timer1": # do something If you need to, you can add a button number argument and even a sizer to the first function to put the buttons into. I do this sort of thing when I have a bunch of buttons that will all do something similar. Mike Driscoll Blog: http://blog.pythonlibrary.org
Create multiple buttons with consecutive integers in name
I have the following python code and I was wondering if it's possible to create those buttons in a for loop instead? I was thinking of modifying the local namespace but I'm not sure if that's a good idea. I really want the buttons to be named so that it's named consecutively. self.todo1 = wx.TextCtrl(self, -1, "") self.timer_label1 = wx.StaticText(self, -1, "00:00") self.set_timer1 = wx.Button(self, -1, "Set Timer") self.todo2 = wx.TextCtrl(self, -1, "") self.timer_label2 = wx.StaticText(self, -1, "00:00") self.set_timer2 = wx.Button(self, -1, "Set Timer") self.todo3 = wx.TextCtrl(self, -1, "") self.timer_label3 = wx.StaticText(self, -1, "00:00") self.set_timer3 = wx.Button(self, -1, "Set Timer") self.todo4 = wx.TextCtrl(self, -1, "") self.timer_label4 = wx.StaticText(self, -1, "00:00") self.set_timer4 = wx.Button(self, -1, "Set Timer") self.todo5 = wx.TextCtrl(self, -1, "") self.timer_label5 = wx.StaticText(self, -1, "00:00") self.set_timer5 = wx.Button(self, -1, "Set Timer")
[ "I think the built-in setattr method is probably your best friend here. Something like this should work:\nfor i in range(1,6):\n setattr(self,'todo%d' % i,wx.TextCtrl(self, -1, \"\"))\n setattr(self,'timer_label%d' % i, wx.StaticText(self,-1,\"00:00\"))\n setattr(self,'set_timer%d' % i, wx.Button(self,-1,\"S...
[ 3, 2, 0, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003231358_python_wxpython.txt
Q: Run a C# application from python script I've just about finished coding a decently sized disease transmission model in C#. However, I'm fairly new to .NET and am unsure how to proceed. Currently I just double-click on the .exe file and the model imports config setting from text files, does its thing, and outputs the results into a text file. What I would like to do next is write a Python script to do the following: Run the simulation N times (N > 1000) After each run rename the output file and store (i.e. ./output.txt -> ./acc/outputN.txt) Aggregate, parse, and analyze the outputs Output the result in some clean format (possibly excel) The majority of my programming experience to date has been in C/C++ on linux. I'm fairly confident about the last two items; however, I have no idea how to proceed for the first two. Here are some specific questions I'd like advice on: What is the easiest/best way to run my C# .exe from a python script? Does anyone have advice on the best way to do filesystem operations in Python on a Windows system? Thanks! A: As of Python 2.6+ you should be using the subprocess module: (Docs) import subprocess for v in range(1000): cmdLine = r"c:\path\to\my\app.exe" subprocess.Popen(subprocess) subprocess.Popen(r"move output.txt ./acc/output-%d.txt" % (v)) A: The answer to your problems can be found in 'os' in the python standard library. Documentation for doing various operations, such as handling files and starting processes, can be found here. Process management (Running your C# program) can be found here and file operations are here. EDIT: Actually, instead of the above process link, you should use the subprocess module.
Run a C# application from python script
I've just about finished coding a decently sized disease transmission model in C#. However, I'm fairly new to .NET and am unsure how to proceed. Currently I just double-click on the .exe file and the model imports config setting from text files, does its thing, and outputs the results into a text file. What I would like to do next is write a Python script to do the following: Run the simulation N times (N > 1000) After each run rename the output file and store (i.e. ./output.txt -> ./acc/outputN.txt) Aggregate, parse, and analyze the outputs Output the result in some clean format (possibly excel) The majority of my programming experience to date has been in C/C++ on linux. I'm fairly confident about the last two items; however, I have no idea how to proceed for the first two. Here are some specific questions I'd like advice on: What is the easiest/best way to run my C# .exe from a python script? Does anyone have advice on the best way to do filesystem operations in Python on a Windows system? Thanks!
[ "As of Python 2.6+ you should be using the subprocess module: (Docs)\nimport subprocess\n\nfor v in range(1000):\n cmdLine = r\"c:\\path\\to\\my\\app.exe\"\n subprocess.Popen(subprocess)\n subprocess.Popen(r\"move output.txt ./acc/output-%d.txt\" % (v))\n\n", "The answer to your problems can be found in ...
[ 12, 3 ]
[]
[]
[ "filesystems", "python", "simulation", "subprocess" ]
stackoverflow_0003260015_filesystems_python_simulation_subprocess.txt
Q: How to check variable against 2 possible values? I have a variable s which contains a one letter string s = 'a' Depending on the value of that variable, I want to return different things. So far I am doing something along the lines of this: if s == 'a' or s == 'b': return 1 elif s == 'c' or s == 'd': return 2 else: return 3 Is there a better way to write this? A more Pythonic way? Or is this the most efficient? Previously, I incorrectly had something like this: if s == 'a' or 'b': ... Obviously that doesn't work and was pretty dumb of me. I know of conditional assignment and have tried this: return 1 if s == 'a' or s == 'b' ... I guess my question is specifically to is there a way you can compare a variable to two values without having to type something == something or something == something A: if s in ('a', 'b'): return 1 elif s in ('c', 'd'): return 2 else: return 3 A: d = {'a':1, 'b':1, 'c':2, 'd':2} return d.get(s, 3) A: If you only return fixed values, a dictionary is probably the best approach. A: if s in 'ab': return 1 elif s in 'cd': return 2 else: return 3 A: Maybe little more self documenting using if else: d = {'a':1, 'b':1, 'c':2, 'd':2} ## good choice is to replace case with dict when possible return d[s] if s in d else 3 Also it is possible to implement the popular first answer with if else: return (1 if s in ('a', 'b') else (2 if s in ('c','d') else 3)) A: return 1 if (x in 'ab') else 2 if (x in 'cd') else 3
How to check variable against 2 possible values?
I have a variable s which contains a one letter string s = 'a' Depending on the value of that variable, I want to return different things. So far I am doing something along the lines of this: if s == 'a' or s == 'b': return 1 elif s == 'c' or s == 'd': return 2 else: return 3 Is there a better way to write this? A more Pythonic way? Or is this the most efficient? Previously, I incorrectly had something like this: if s == 'a' or 'b': ... Obviously that doesn't work and was pretty dumb of me. I know of conditional assignment and have tried this: return 1 if s == 'a' or s == 'b' ... I guess my question is specifically to is there a way you can compare a variable to two values without having to type something == something or something == something
[ "if s in ('a', 'b'):\n return 1\nelif s in ('c', 'd'):\n return 2\nelse:\n return 3\n\n", " d = {'a':1, 'b':1, 'c':2, 'd':2}\n return d.get(s, 3)\n\n", "If you only return fixed values, a dictionary is probably the best approach.\n", "if s in 'ab':\n return 1\nelif s in 'cd':\n return 2\nelse:\...
[ 51, 15, 1, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003260057_python.txt
Q: socket.getaddrinfo fails on one machine; works on another apparently-identical one. Why? I've got a laptop and a desktop, both running Ubuntu 10.04, both running the stock Python 2.6.5 that comes with Ubuntu. On the laptop, the following program #!/usr/bin/env python import socket print(socket.getaddrinfo("localhost", 8025, 0, socket.SOCK_STREAM)) works -- i.e., it prints out some stuff without getting an error. The stuff, in fact, is: [(10, 1, 6, '', ('::1', 8025, 0, 0)), (2, 1, 6, '', ('127.0.0.1', 8025))] (That's one bunch of IPv6 data, and one bunch of IPv4 data.) However, on the other box, the same program does this: Traceback (most recent call last): File "socktest.py", line 5, in <module> print(socket.getaddrinfo("localhost", 8025, 0, socket.SOCK_STREAM)) socket.gaierror: [Errno -2] Name or service not known Why? The laptop is x86 (i.e., 32-bit) whereas the desktop is x86_64, but I'd be surprised if that mattered. The laptop also has two network interfaces (wireless and wired), whereas the desktop just has wired; again I doubt that's relevant. All three interfaces were bound to IPv6 addresses, according to "ifconfig". I diffed /etc/network on the two boxes, and saw no difference, except that the laptop has this clause # The primary network interface auto eth0 iface eth0 inet dhcp ... which, again, strikes me as irrelevant. :: If you want some context: my Python program is trying to send email, and it's the email software that is ultimately calling getaddrinfo. A: Check /etc/hosts on the box where it does not work. Is there an entry for localhost? Also compare /etc/nsswitch.conf and see if there is anything suspicious, like missing 'hosts' line
socket.getaddrinfo fails on one machine; works on another apparently-identical one. Why?
I've got a laptop and a desktop, both running Ubuntu 10.04, both running the stock Python 2.6.5 that comes with Ubuntu. On the laptop, the following program #!/usr/bin/env python import socket print(socket.getaddrinfo("localhost", 8025, 0, socket.SOCK_STREAM)) works -- i.e., it prints out some stuff without getting an error. The stuff, in fact, is: [(10, 1, 6, '', ('::1', 8025, 0, 0)), (2, 1, 6, '', ('127.0.0.1', 8025))] (That's one bunch of IPv6 data, and one bunch of IPv4 data.) However, on the other box, the same program does this: Traceback (most recent call last): File "socktest.py", line 5, in <module> print(socket.getaddrinfo("localhost", 8025, 0, socket.SOCK_STREAM)) socket.gaierror: [Errno -2] Name or service not known Why? The laptop is x86 (i.e., 32-bit) whereas the desktop is x86_64, but I'd be surprised if that mattered. The laptop also has two network interfaces (wireless and wired), whereas the desktop just has wired; again I doubt that's relevant. All three interfaces were bound to IPv6 addresses, according to "ifconfig". I diffed /etc/network on the two boxes, and saw no difference, except that the laptop has this clause # The primary network interface auto eth0 iface eth0 inet dhcp ... which, again, strikes me as irrelevant. :: If you want some context: my Python program is trying to send email, and it's the email software that is ultimately calling getaddrinfo.
[ "Check /etc/hosts on the box where it does not work. Is there an entry for localhost?\nAlso compare /etc/nsswitch.conf and see if there is anything suspicious, like missing 'hosts' line\n" ]
[ 1 ]
[]
[]
[ "networking", "python", "sockets" ]
stackoverflow_0003260469_networking_python_sockets.txt
Q: I'd like to know what's going on this Python program. I've included the code Here's the code: http://paste.pocoo.org/show/238093/ My main questions right now are: Is Line 37 mainly the gist of this program? And does it simply calculate this once and then print the result? Ex: self.start + key*self.step with start=1, key=4, step=2 [prints 9] where does the variable 'value' actually come into play here? Line 39. Not worried about the "Exceptions" part of the program. I pretty much understand what it's doing. Lastly, and you really don't have to answer this one as it's probably better as another question "down the road" but I really do not see how __getitem__, __setitem__...etc...you still have to write in your own code to "make it do stuff". :) I'm just not getting what's so "special" about these special methods. A: Yes, more or less. This is the exception. If someone assigns a value to a particular index, the sequence remembers that and will return that value instead of calculating it. Note that the code here does not actually use this function. Random comment instead: the last 3 lines of the getitem function could be much more concisely implemented as return self.changed.get(key, self.start + key*self.step) -- dict.get lets you provide a default to return if a key is missing. They're "special" only in that they let you override what happens when someone does yourthing[foo] or yourthing[foo] = bar. You see the first going on here; the second is what happens if someone does s[5] = 100 -- the 100 ends up as the value of a __setitem__ call.
I'd like to know what's going on this Python program. I've included the code
Here's the code: http://paste.pocoo.org/show/238093/ My main questions right now are: Is Line 37 mainly the gist of this program? And does it simply calculate this once and then print the result? Ex: self.start + key*self.step with start=1, key=4, step=2 [prints 9] where does the variable 'value' actually come into play here? Line 39. Not worried about the "Exceptions" part of the program. I pretty much understand what it's doing. Lastly, and you really don't have to answer this one as it's probably better as another question "down the road" but I really do not see how __getitem__, __setitem__...etc...you still have to write in your own code to "make it do stuff". :) I'm just not getting what's so "special" about these special methods.
[ "\nYes, more or less.\nThis is the exception. If someone assigns a value to a particular index, the sequence remembers that and will return that value instead of calculating it. Note that the code here does not actually use this function.\nRandom comment instead: the last 3 lines of the getitem function could be ...
[ 3 ]
[]
[]
[ "containers", "python", "types" ]
stackoverflow_0003260488_containers_python_types.txt
Q: Possible Google Riddle? My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant. t-shirt So, I have a couple of guesses as to what it means, but I was just wondering if there is something more. My first guess is that each block represents a page layout, and the logo "You should test that" just means that you should use google website optimizer to test which is the best layout. I hope that this isn't the answer, it just seems to simple and unsatisfying. Well, I've spent the past hour trying to figure out if there is any deeper meaning, but to no avail. So, I'm here hoping that someone might be able to help. I did though write a program to see if the blocks represent something in binary. I'll post the code below. My code tests every permutation of reading a block as 4 bits, and then tries to interpret these bits as letters, hex, and ip addresses. I hope someone knows better. #This code interprets the google t-shirt as a binary code, each box 4 bits. # I try every permutation of counting the bits and then try to interpret these # interpretations as letters, or hex numbers, or ip addresses. # I need more interpretations, maybe one will find a pattern import string #these represent the boxes binary codes from left to right top to bottom boxes = ['1110', '1000', '1111', '0110', '0011', '1011', '0001', '1001'] #changing the ordering permutations = ["1234", "1243", "1324", "1342", "1423", "1432", "2134", "2143", "2314", "2341", "2413", "2431", "3124", "3142", "3214", "3241", "3412", "3421", "4123", "4132", "4213", "4231","4312", "4321"] #alphabet hashing where 0 = a alphabet1 = {'0000':'a', '0001':'b', '0010':'c', '0011':'d', '0100':'e', '0101':'f', '0110':'g', '0111':'h', '1000':'i', '1001':'j', '1010':'k', '1011':'l', '1100':'m', '1101':'n', '1110':'o', '1111':'p'} #alphabet hasing where 1 = a alphabet2 = {'0000':'?', '0001':'a', '0010':'b', '0011':'c', '0100':'d', '0101':'e', '0110':'f', '0111':'g', '1000':'h', '1001':'i', '1010':'j', '1011':'k', '1100':'l', '1101':'m', '1110':'n', '1111':'o'} hex = {'0000':'0', '0001':'1', '0010':'2', '0011':'3', '0100':'4', '0101':'5', '0110':'6', '0111':'7', '1000':'8', '1001':'9', '1010':'a', '1011':'b', '1100':'c', '1101':'d', '1110':'e', '1111':'f'} #code to convert from a string of ones and zeros(binary) to decimal number def bin_to_dec(bin_string): l = len(bin_string) answer = 0 for index in range(l): answer += int(bin_string[l - index - 1]) * (2**index) return answer #code to try and ping ip addresses def ping(ipaddress): #ping the network addresses import subprocess # execute the code and pipe the result to a string, wait 5 seconds test = "ping -t 5 " + ipaddress process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE) # give it time to respond process.wait() # read the result to a string result_str = process.stdout.read() #For now, need to manually check if the ping worked, fix later print result_str #now iterate over the permuation and then the boxes to produce the codes for permute in permutations: box_codes = [] for box in boxes: temp_code = "" for index in permute: temp_code += box[int(index) - 1] box_codes.append(temp_code) #now manipulate the codes using leter translation, network, whatever #binary print string.join(box_codes, "") #alphabet1 print string.join( map(lambda x: alphabet1[x], box_codes), "") #alphabet2 print string.join( map(lambda x: alphabet2[x], box_codes), "") #hex print string.join( map(lambda x: hex[x], box_codes), "") #ipaddress, call ping and see who is reachable ipcodes = zip(box_codes[0:8:2], box_codes[1:8:2]) ip = "" for code in ipcodes: bin = bin_to_dec(code[0] + code[1]) ip += repr(bin) + "." print ip[:-1] #ping(ip[:-1]) print print t-shirt. A: I emailed the Website Optimizer Team, and they said "There's no secret code, unless you find one. :)" A: I think Google are just trying to drive their point home - here are a bunch of different representations of the same page, test them, see which is best. Which block do you like best? A: I think it's simply a design, nothing secret, or mysterious. A: What if it doesn't mean anything, what if it is just a neat design they came up with? A: It says: "You are getting closer". A: Well, I can't see an immediate pattern. But if you are testing IP, why not take two blocks of 4 as a single binary number. A: Probably it's a base 4 notation? I would try that, but I don't have any approach to this. A: It reminded me of cellular automata: http://www.wolframalpha.com/input/?i=rule+110 Anyone going that direction?
Possible Google Riddle?
My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant. t-shirt So, I have a couple of guesses as to what it means, but I was just wondering if there is something more. My first guess is that each block represents a page layout, and the logo "You should test that" just means that you should use google website optimizer to test which is the best layout. I hope that this isn't the answer, it just seems to simple and unsatisfying. Well, I've spent the past hour trying to figure out if there is any deeper meaning, but to no avail. So, I'm here hoping that someone might be able to help. I did though write a program to see if the blocks represent something in binary. I'll post the code below. My code tests every permutation of reading a block as 4 bits, and then tries to interpret these bits as letters, hex, and ip addresses. I hope someone knows better. #This code interprets the google t-shirt as a binary code, each box 4 bits. # I try every permutation of counting the bits and then try to interpret these # interpretations as letters, or hex numbers, or ip addresses. # I need more interpretations, maybe one will find a pattern import string #these represent the boxes binary codes from left to right top to bottom boxes = ['1110', '1000', '1111', '0110', '0011', '1011', '0001', '1001'] #changing the ordering permutations = ["1234", "1243", "1324", "1342", "1423", "1432", "2134", "2143", "2314", "2341", "2413", "2431", "3124", "3142", "3214", "3241", "3412", "3421", "4123", "4132", "4213", "4231","4312", "4321"] #alphabet hashing where 0 = a alphabet1 = {'0000':'a', '0001':'b', '0010':'c', '0011':'d', '0100':'e', '0101':'f', '0110':'g', '0111':'h', '1000':'i', '1001':'j', '1010':'k', '1011':'l', '1100':'m', '1101':'n', '1110':'o', '1111':'p'} #alphabet hasing where 1 = a alphabet2 = {'0000':'?', '0001':'a', '0010':'b', '0011':'c', '0100':'d', '0101':'e', '0110':'f', '0111':'g', '1000':'h', '1001':'i', '1010':'j', '1011':'k', '1100':'l', '1101':'m', '1110':'n', '1111':'o'} hex = {'0000':'0', '0001':'1', '0010':'2', '0011':'3', '0100':'4', '0101':'5', '0110':'6', '0111':'7', '1000':'8', '1001':'9', '1010':'a', '1011':'b', '1100':'c', '1101':'d', '1110':'e', '1111':'f'} #code to convert from a string of ones and zeros(binary) to decimal number def bin_to_dec(bin_string): l = len(bin_string) answer = 0 for index in range(l): answer += int(bin_string[l - index - 1]) * (2**index) return answer #code to try and ping ip addresses def ping(ipaddress): #ping the network addresses import subprocess # execute the code and pipe the result to a string, wait 5 seconds test = "ping -t 5 " + ipaddress process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE) # give it time to respond process.wait() # read the result to a string result_str = process.stdout.read() #For now, need to manually check if the ping worked, fix later print result_str #now iterate over the permuation and then the boxes to produce the codes for permute in permutations: box_codes = [] for box in boxes: temp_code = "" for index in permute: temp_code += box[int(index) - 1] box_codes.append(temp_code) #now manipulate the codes using leter translation, network, whatever #binary print string.join(box_codes, "") #alphabet1 print string.join( map(lambda x: alphabet1[x], box_codes), "") #alphabet2 print string.join( map(lambda x: alphabet2[x], box_codes), "") #hex print string.join( map(lambda x: hex[x], box_codes), "") #ipaddress, call ping and see who is reachable ipcodes = zip(box_codes[0:8:2], box_codes[1:8:2]) ip = "" for code in ipcodes: bin = bin_to_dec(code[0] + code[1]) ip += repr(bin) + "." print ip[:-1] #ping(ip[:-1]) print print t-shirt.
[ "I emailed the Website Optimizer Team, and they said \"There's no secret code, unless you find one. :)\"\n", "I think Google are just trying to drive their point home - here are a bunch of different representations of the same page, test them, see which is best.\nWhich block do you like best?\n", "I think it's ...
[ 15, 5, 5, 2, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000252221_python.txt
Q: blocking socket client example i need to connect to a blocking service using tcp ports (if someone here knows about it, it is a motorola digital wirelink protocol service) , i need a good starting point example, ideally in perl, python or php which are the languages i know better. So far i have tried this basic example with no luck. import socket import sys HOST, PORT = "172.16.10.5", 15142 data = " ".join(sys.argv[1:]) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((HOST, PORT)) print "connected" sock.send(data + "\n") print "data sent" received = sock.recv(1024) print "data received" sock.close() print "Sent: %s" % data print "Received: %s" % received the script just hangs forever after sock.send do anyone of you know of a good example? regards A: You probably need \r\n instead of \n. If you don't terminate properly, a response won't be sent. A: I don't know about this specific protocol, but instead of managing sockets yourself, I would have to recommend the Twisted framework for networking in Python. Twisted is an event-driven networking engine written in Python and licensed under the MIT license.
blocking socket client example
i need to connect to a blocking service using tcp ports (if someone here knows about it, it is a motorola digital wirelink protocol service) , i need a good starting point example, ideally in perl, python or php which are the languages i know better. So far i have tried this basic example with no luck. import socket import sys HOST, PORT = "172.16.10.5", 15142 data = " ".join(sys.argv[1:]) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((HOST, PORT)) print "connected" sock.send(data + "\n") print "data sent" received = sock.recv(1024) print "data received" sock.close() print "Sent: %s" % data print "Received: %s" % received the script just hangs forever after sock.send do anyone of you know of a good example? regards
[ "You probably need \\r\\n instead of \\n. If you don't terminate properly, a response won't be sent.\n", "I don't know about this specific protocol, but instead of managing sockets yourself, I would have to recommend the Twisted framework for networking in Python.\n\nTwisted is an event-driven networking engine ...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003260995_python.txt
Q: How can I download files form web pages? Some web pages, having their urls, have "Download" Text, which are hyperlinks. How can I get the hyperlinks form the urls/pages by python or ironpython. And can I download the files with these hyperlinks by python or ironpython? How can I do that? Are there any C# tools? I am not native english speaker, so sorry for my english. A: You should be able to use the BeautifulSoup library with CPython (normal Python) and IronPython. Check out the findAll() method. This should pull out a list of all the links. soup.findAll('a') A: The easiest way would be to pass the HTML page into an XML/HTML parser, and then call getElementsByTagName("A") on the root node. Once you get that, iterate through the list and pull out the href parameter.
How can I download files form web pages?
Some web pages, having their urls, have "Download" Text, which are hyperlinks. How can I get the hyperlinks form the urls/pages by python or ironpython. And can I download the files with these hyperlinks by python or ironpython? How can I do that? Are there any C# tools? I am not native english speaker, so sorry for my english.
[ "You should be able to use the BeautifulSoup library with CPython (normal Python) and IronPython. Check out the findAll() method. This should pull out a list of all the links.\nsoup.findAll('a')\n\n", "The easiest way would be to pass the HTML page into an XML/HTML parser, and then call getElementsByTagName(\"A\"...
[ 2, 1 ]
[]
[]
[ "c#", "ironpython", "python" ]
stackoverflow_0003261198_c#_ironpython_python.txt
Q: wxPython: Right-align the numbers in a wx.SpinCtrl A primary reason to use wx.SpinCtrl is to restrict the user to input integers, therefore I think that the text inside it would look better if right-aligned. Is there a way to do this in wxPython? A: Actually, there is a control you can use. It's called FloatSpin, which is in the agw sub-library. If you don't already have it, download the wxPython demo and check it out! Mike
wxPython: Right-align the numbers in a wx.SpinCtrl
A primary reason to use wx.SpinCtrl is to restrict the user to input integers, therefore I think that the text inside it would look better if right-aligned. Is there a way to do this in wxPython?
[ "Actually, there is a control you can use. It's called FloatSpin, which is in the agw sub-library. If you don't already have it, download the wxPython demo and check it out!\n\nMike\n\n" ]
[ 1 ]
[]
[]
[ "alignment", "python", "spinner", "wxpython" ]
stackoverflow_0003252671_alignment_python_spinner_wxpython.txt
Q: Django Error: No module named engine I'm trying to implement this code but getting Error: No module named engine http://github.com/robstyles/Massive-Coupon---Open-source-groupon-clone Any thoughts? A: You probably don't have any module named "engine" on your PYTHONPATH anyplace. Either the installation went in the wrong location, or your Django setup was not set to include that path. A: In the github directory you point to, there's a module named "engine". The folder containing this module needs to be available on your python path. A: Check follow steps is PYTHONPATH pointed to massivecoupon project parent path? is your proejct named massivecoupon? if y go 4 else go 3 change your project to massivecoupon make sure all sub folders and parent folder have __init__.py
Django Error: No module named engine
I'm trying to implement this code but getting Error: No module named engine http://github.com/robstyles/Massive-Coupon---Open-source-groupon-clone Any thoughts?
[ "You probably don't have any module named \"engine\" on your PYTHONPATH anyplace. Either the installation went in the wrong location, or your Django setup was not set to include that path.\n", "In the github directory you point to, there's a module named \"engine\". The folder containing this module needs to be ...
[ 0, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003261075_django_python.txt
Q: Parsing XML response of bit.ly I was trying out the bit.ly api for shorterning and got it to work. It returns to my script an xml document. I wanted to extract out the tag but cant seem to parse it properly. askfor = urllib2.Request(full_url) response = urllib2.urlopen(askfor) the_page = response.read() So the_page contains the xml document. I tried: from xml.dom.minidom import parse doc = parse(the_page) this causes an error. what am I doing wrong? A: You don't provide an error message so I can't be sure this is the only error. But, xml.minidom.parse does not take a string. From the docstring for parse: Parse a file into a DOM by filename or file object. You should try: response = urllib2.urlopen(askfor) doc = parse(response) since response will behave like a file object. Or you could use the parseString method in minidom instead (and then pass the_page as the argument). EDIT: to extract the URL, you'll need to do: url_nodes = doc.getElementsByTagName('url') url = url_nodes[0] print url.childNodes[0].data The result of getElementsByTagName is a list of all nodes matching (just one in this case). url is an Element as you noticed, which contains a child Text node, which contains the data you need. A: from xml.dom.minidom import parseString doc = parseString(the_page) See the documentation for xml.dom.minidom.
Parsing XML response of bit.ly
I was trying out the bit.ly api for shorterning and got it to work. It returns to my script an xml document. I wanted to extract out the tag but cant seem to parse it properly. askfor = urllib2.Request(full_url) response = urllib2.urlopen(askfor) the_page = response.read() So the_page contains the xml document. I tried: from xml.dom.minidom import parse doc = parse(the_page) this causes an error. what am I doing wrong?
[ "You don't provide an error message so I can't be sure this is the only error. But, xml.minidom.parse does not take a string. From the docstring for parse:\n\nParse a file into a DOM by filename or file object.\n\nYou should try:\nresponse = urllib2.urlopen(askfor)\ndoc = parse(response)\n\nsince response will be...
[ 2, 1 ]
[]
[]
[ "bit.ly", "parsing", "python", "xml" ]
stackoverflow_0003261372_bit.ly_parsing_python_xml.txt
Q: Run a function each tick in Twisted I'm using the twisted framework, and I need to keep track of how much time has passed since an event has started, and perform an action when a certain amount has passed. The best way to do that seems to me to be to check against a time-stamp each tick of the reactor. If it is the best way, how do I do it? If it isn't, what's a better way? A: You want to use callLater. Here's a complete, runnable example which does what you are asking, "perform an action when a certain amount (of time) has passed since an event has started". from twisted.internet import reactor certainAmount = 0.73 # this is in seconds def startedEvent(): print 'started event' reactor.callLater(certainAmount, performAnAction) def performAnAction(): print 'performed an action' reactor.stop() startedEvent() reactor.run() (I don't think there's really any such thing as a 'tick' in the reactor, at least, not in the sense that I'm guessing you mean.) A: The functionality I was looking for seems to be described here: Running a function periodically in twisted protocol Here's my code: def check_time(self): for game in self.games: if self.games[game]['state'] == 'GAME': game_start_time = self.games[game]['starttime'] if game_start_time is None: continue elif game_start_time + 300 > time.time(): #300 seconds = 5 minutes. continue else: self.end_game(game) def __init__(self): self.timecheck = task.LoopingCall(self.check_time) self.timecheck.start(1)
Run a function each tick in Twisted
I'm using the twisted framework, and I need to keep track of how much time has passed since an event has started, and perform an action when a certain amount has passed. The best way to do that seems to me to be to check against a time-stamp each tick of the reactor. If it is the best way, how do I do it? If it isn't, what's a better way?
[ "You want to use callLater.\nHere's a complete, runnable example which does what you are asking, \"perform an action when a certain amount (of time) has passed since an event has started\".\nfrom twisted.internet import reactor\ncertainAmount = 0.73 # this is in seconds\ndef startedEvent():\n print 'started even...
[ 2, 1 ]
[]
[]
[ "python", "timing", "twisted" ]
stackoverflow_0003260949_python_timing_twisted.txt
Q: Python twisted asynchronous write using deferred With regard to the Python Twisted framework, can someone explain to me how to write asynchronously a very large data string to a consumer, say the protocol.transport object? I think what I am missing is a write(data_chunk) function that returns a Deferred. This is what I would like to do: data_block = get_lots_and_lots_data() CHUNK_SIZE = 1024 # write 1-K at a time. def write_chunk(data, i): d = transport.deferredWrite(data[i:i+CHUNK_SIZE]) d.addCallback(write_chunk, data, i+1) write_chunk(data, 0) But, after a day of wandering around in the Twisted API/Documentation, I can't seem to locate anything like the deferredWrite equivalence. What am I missing? A: As Jean-Paul says, you should use IProducer and IConsumer, but you should also note that the lack of deferredWrite is a somewhat intentional omission. For one thing, creating a Deferred for potentially every byte of data that gets written is a performance problem: we tried it in the web2 project and found that it was the most significant performance issue with the whole system, and we are trying to avoid that mistake as we backport web2 code to twisted.web. More importantly, however, having a Deferred which gets returned when the write "completes" would provide a misleading impression: that the other end of the wire has received the data that you've sent. There's no reasonable way to discern this. Proxies, smart routers, application bugs and all manner of network contrivances can conspire to fool you into thinking that your data has actually arrived on the other end of the connection, even if it never gets processed. If you need to know that the other end has processed your data, make sure that your application protocol has an acknowledgement message that is only transmitted after the data has been received and processed. The main reason to use producers and consumers in this kind of code is to avoid allocating memory in the first place. If your code really does read all of the data that it's going to write to its peer into a giant string in memory first (data_block = get_lots_and_lots_data() pretty directly implies that) then you won't lose much by doing transport.write(data_block). The transport will wake up and send a chunk of data as often as it can. Plus, you can simply do transport.write(hugeString) and then transport.loseConnection(), and the transport won't actually disconnect until either all of the data has been sent or the connection is otherwise interrupted. (Again: if you don't wait for an acknowledgement, you won't know if the data got there. But if you just want to dump some bytes into the socket and forget about it, this works okay.) If get_lots_and_lots_data() is actually reading a file, you can use the included FileSender class. If it's something which is sort of like a file but not exactly, the implementation of FileSender might be a useful example. A: The way large amounts of data is generally handled in Twisted is using the Producer/Consumer APIs. This doesn't give you a write method that returns a Deferred, but it does give you notification about when it's time to write more data.
Python twisted asynchronous write using deferred
With regard to the Python Twisted framework, can someone explain to me how to write asynchronously a very large data string to a consumer, say the protocol.transport object? I think what I am missing is a write(data_chunk) function that returns a Deferred. This is what I would like to do: data_block = get_lots_and_lots_data() CHUNK_SIZE = 1024 # write 1-K at a time. def write_chunk(data, i): d = transport.deferredWrite(data[i:i+CHUNK_SIZE]) d.addCallback(write_chunk, data, i+1) write_chunk(data, 0) But, after a day of wandering around in the Twisted API/Documentation, I can't seem to locate anything like the deferredWrite equivalence. What am I missing?
[ "As Jean-Paul says, you should use IProducer and IConsumer, but you should also note that the lack of deferredWrite is a somewhat intentional omission.\nFor one thing, creating a Deferred for potentially every byte of data that gets written is a performance problem: we tried it in the web2 project and found that it...
[ 8, 1 ]
[]
[]
[ "asynchronous", "python", "twisted" ]
stackoverflow_0003250327_asynchronous_python_twisted.txt
Q: Are there reasons to use get/put methods instead of item access? I find that I have recently been implementing Mapping interfaces on classes which on the surface fit the model (they are essentially just key-value stores with no more meta-data), but underneath they are sometimes quite complex. Here are a couple examples of increasing severity: An object which wraps another mapping converting all objects to strings when set. An object which uses a local database as a back-end to store the key-value pairs. An object which makes HTTP requests to remote servers to get/set data. Lets suppose all of these examples seamlessly implement the Mapping interface, and the only indication that there is something fishy going on is that item access potentially could take a few seconds, and an item may not be retrievable in the same form as stored (if at all). I'm perfectly content with something like the first example, pretty okay with the second, but I'm getting kinda uncomfortable with the last. The question is, is there a line at which the API for these models should not use item access, even though the underlying structure may feel like it fits on the surface? A: It sounds like you are describing the standard anydbm module semantics. And just as anydbm can raise exception anydbm.error, so too could your subclass raise derivatives like MyDbmTimeoutError as needed. Whether you implement it as dictionary operations or function calls, the caller will still have to contend with exceptions anyway (e.g. KeyError, NameError). I think that arbitrary "tied" hashes exist in Python 2 and 3.x is decent justification for saying it is a reasonable approach. Indeed, I've been looking for (and designing in my head) more complex bindings than simple key ⇒ value mappings without a heavy ORM SQL layer in between. added: The more I think about it, the more Pythonic tied dictionaries seem to be. A key ⇒ value collection is a dictionary. Whether it lives in core or on disk or across the network is an implementation detail that is best abstracted away. The only substantive differences are increased latency and possible unavailability; however, on a virtual memory based OS, "core" can have higher latency than RAM and in a multiprocessing OS, "core" can become unavailable too. So these are differences in degree only, not kind. A: From a strictly philosophical point of view, I don't think that there is a line you can cross with this. If some tool provides the needed functionality, but its API is different, adapt away. The only time you shouldn't do this is if the adapted to API simply is not expressive enough to manipulate the adapted component in a way that is needed. I wouldn't hesitate to adapt a database into a dict, because that's a great way to manipulate collections, and it's already compatible with a heck of a lot of other code. If I find that my particular application must make calls to the database connections begin(), commit(), and rollback() methods to work right, then a dict won't do, since dict's don't have transaction semantics.
Are there reasons to use get/put methods instead of item access?
I find that I have recently been implementing Mapping interfaces on classes which on the surface fit the model (they are essentially just key-value stores with no more meta-data), but underneath they are sometimes quite complex. Here are a couple examples of increasing severity: An object which wraps another mapping converting all objects to strings when set. An object which uses a local database as a back-end to store the key-value pairs. An object which makes HTTP requests to remote servers to get/set data. Lets suppose all of these examples seamlessly implement the Mapping interface, and the only indication that there is something fishy going on is that item access potentially could take a few seconds, and an item may not be retrievable in the same form as stored (if at all). I'm perfectly content with something like the first example, pretty okay with the second, but I'm getting kinda uncomfortable with the last. The question is, is there a line at which the API for these models should not use item access, even though the underlying structure may feel like it fits on the surface?
[ "It sounds like you are describing the standard anydbm module semantics. And just as anydbm can raise exception anydbm.error, so too could your subclass raise derivatives like MyDbmTimeoutError as needed. Whether you implement it as dictionary operations or function calls, the caller will still have to contend with...
[ 2, 0 ]
[]
[]
[ "interface", "mapping", "python" ]
stackoverflow_0003261030_interface_mapping_python.txt
Q: Translating Python into JavaScript — Lists? octopusList = {"first": ["red", "white"], "second": ["green", "blue", "red"], "third": ["green", "blue", "red"]} squidList = ["first", "second", "third"] for i in range(1): squid = random.choice(squidList) octopus = random.choice(octopusList[squid]) print squid + " " + octopus Can anyone help me write this in JavaScript? I've got most of my program written into JavaScript but specifically how to get a list with lists in it written in JavaScript has me puzzled. I'm new to programming in general, so thanks for putting up with my questions. :D A: First of all, I'd like to say that that for i in range(1): line is useless. It'll only execute the contents once, and you're not using i. Anyway, the code you posted should work fine with a few tweaks in JavaScript. First you'll need to reimplement random.choice. You could use this: function randomChoice(list) { return list[Math.floor(Math.random()*list.length)]; } Now after that, it's simple: var octopusList = { "first": ["red", "white"], "second": ["green", "blue", "red"], "third": ["green", "blue", "red"] }; var squidList = ["first", "second", "third"]; var squid = randomChoice(squidList); var octopus = randomChoice(octopusList[squid]); // You could use alert instead of console.log if you want. console.log(squid + " " + octopus); A: js> octopusList = {"first": ["red", "white"], "second": ["green", "blue", "red"], "third": ["green", "blue", "red"]} js> squidList = ["first", "second", "third"] first,second,third js> squid = squidList[Math.floor(Math.random() * squidList.length)] third js> oct_squid = octopusList[squid] green,blue,red js> octopus = oct_squid[Math.floor(Math.random() * oct_squid.length)] blue A: ...specifically how to get a list with lists in it written in Javascript has me puzzled. You can ( also ) create a list in with list in it in JavaScript like this: var listWithList = [["a,b,c"],["d,"e","f"], ["h","i","j"]] Because when you code in JavaScript o = { "first" : ["red","green"], "second": ["blue","white"]} You're actually creating a JavaScript object with two properties first and second whose values are a list ( or array ) with to elements each. This works just fine as you can see in icktoofay answer Since that's a JavaScript object you could use this syntax to retrieve them listOne = o.first; listTwo = o.second; A: Consider using the json module to translate data structures from Python to JSON format (which is valid Javascript) -- and viceversa, if you ever need to. For example: >>> octopusList = {"first": ["red", "white"], ... "second": ["green", "blue", "red"], ... "third": ["green", "blue", "red"]} >>> print json.dumps(octopusList) {"second": ["green", "blue", "red"], "third": ["green", "blue", "red"], "first": ["red", "white"]} >>> As you see, in this case the "translation" is just about an identity (the change of ordering in the dictionary entries [[in Python]] / object attributes [[in Javascript]] is irrelevant, as neither Python's dicts nor JS's objects have any concept of "ordering";-).
Translating Python into JavaScript — Lists?
octopusList = {"first": ["red", "white"], "second": ["green", "blue", "red"], "third": ["green", "blue", "red"]} squidList = ["first", "second", "third"] for i in range(1): squid = random.choice(squidList) octopus = random.choice(octopusList[squid]) print squid + " " + octopus Can anyone help me write this in JavaScript? I've got most of my program written into JavaScript but specifically how to get a list with lists in it written in JavaScript has me puzzled. I'm new to programming in general, so thanks for putting up with my questions. :D
[ "First of all, I'd like to say that that for i in range(1): line is useless. It'll only execute the contents once, and you're not using i.\nAnyway, the code you posted should work fine with a few tweaks in JavaScript. First you'll need to reimplement random.choice. You could use this:\nfunction randomChoice(list) {...
[ 4, 1, 1, 1 ]
[]
[]
[ "javascript", "python", "translation" ]
stackoverflow_0003261466_javascript_python_translation.txt
Q: Difference between binary and text I/O in python on Windows I know that I should open a binary file using "rb" instead of "r" because Windows behaves differently for binary and non-binary files. But I don't understand what exactly happens if I open a file the wrong way and why this distinction is even necessary. Other operating systems seem to do fine by treating both kinds of files the same. A: Well this is for historical (or as i like to say it, hysterical) reasons. The file open modes are inherited from C stdio library and hence we follow it. For Windows, there is no difference between text and binary files, just like in any of the Unix clones. No, i mean it! - there are (were) file systems/OSes in which text file is completely different beast from object file and so on. In some you had to specify the maximum length of lines in advance and fixed size records were used... fossils from the times of 80-column paper punch-cards and such. Luckily, not so in Unices, Windows and Mac. However - all other things equal - Unix, Windows and Mac hystorically differ in what characters they use in output stream to mark end of one line (or, same thing, as separator between lines). In Unix, \x0A (\n) is used. In Windows, sequence of two characters \x0D\x0A (\r\n) is used; on Mac - just \xOD (\r). Here are some clues on the origin of use of those two symbols - ASCII code 10 is called Line Feed (LF) and when sent to teletype, would cause it to move down one line (Y++), without changing its horizontal (X) position. Carriage Return (CR) - ASCII 13 - on the other hand, would cause the printing carriage to return to the beginning of the line (X=0) without scrolling one line down. So when sending output to the printer, both \r and \n had to be send, so that the carriage will move to the beginning of a new line. Now when typing on terminal keyboard, operators naturally are expected to press one key and not two for end of line. That on Apple][ was the key 'Return' (\r). At any rate, this is how things settled. C's creators were concerned about portability - much of Unix was written in C, unlike before, when OSes were written in assembler. So they did not want to deal with each platform quirks about text representation, so they added this evil hack to their I/O library depending on the platform, the input and output to that file will be "patched" on the fly so that the program will see the new lines the righteous, Unix-way - as '\n' - no matter if it was '\r\n' from Windows or '\r' from Mac. So the developer need not worry on what OS the program ran, it could still read and write text files in native format. There was a problem, however - not all files are text, there are other formats and in they are very sensitive to replacing one character with another. So they though, we will call those "binary files" and indicate that to fopen() by including 'b' in the mode - and this will flag the library not to do any behind-the-scenes conversion. And that's how it came to be the way it is :) So to recap, if file is open with 'b' in binary mode, no conversions will take place. If it was open in text mode, depending on the platform, some conversions of the new line character(s) may occur - towards Unix point of view. Naturally, on Unix platform there is no difference between reading/writing to "text" or "binary" file. A: This mode is about conversion of line endings. When reading in text mode, the platform's native line endings (\r\n on Windows) are converted to Python's Unix-style \n line endings. When writing in text mode, the reverse happens. In binary mode, no such conversion is done. Other platforms usually do fine without the conversion, because they store line endings natively as \n. (An exception is Mac OS, which used to use \r in the old days.) Code relying on this, however, is not portable. A: In Windows, text mode will convert the newline \n to a carriage return followed by a newline \r\n. If you read text in binary mode, there are no problems. If you read binary data in text mode, it will likely be corrupted.
Difference between binary and text I/O in python on Windows
I know that I should open a binary file using "rb" instead of "r" because Windows behaves differently for binary and non-binary files. But I don't understand what exactly happens if I open a file the wrong way and why this distinction is even necessary. Other operating systems seem to do fine by treating both kinds of files the same.
[ "Well this is for historical (or as i like to say it, hysterical) reasons. The file open modes are inherited from C stdio library and hence we follow it. \nFor Windows, there is no difference between text and binary files, just like in any of the Unix clones. No, i mean it! - there are (were) file systems/OSes in w...
[ 28, 25, 1 ]
[ "For reading files there should be no difference. When writing to text-files Windows will automatically mess up your line-breaks (it will add \\r's before the \\n's). That's why you should use \"wb\".\n" ]
[ -2 ]
[ "file", "file_io", "python", "windows" ]
stackoverflow_0003257869_file_file_io_python_windows.txt
Q: Getting the position of the gtk.StatusIcon on Windows I am assisting with Windows support for a PyGTK app that appears as a system tray applet, but am not so strong on the GTK+ gooey stuff... We have it so when you left-click the systray icon, the window appears right by your tray icon no matter where your system tray is--and on Linux this works great, using the results of gtk.StatusIcon.get_geometry() to calculate the size and position. Of course, the docs for gtk.StatusIcon.get_geometry() point out that "some platforms do not provide this information"--and this includes MS Windows, as I get NoneType as the result. I can make a guess and position the window in the bottom-right corner of the screen, 30 pixels up from the bottom--as this will catch the majority of Windows users who haven't moved the taskbar. But for those that have, it looks all wrong. So is there a Windows-friendly way to get the position of the systray icon so I can place my window there? Please note: I am already using gtk_menu_popup() with gtk_status_icon_position_menu for a pop-up menu which works correctly. But what I am trying to position is a separate gtk.Window, which will not accept gtk_status_icon_position_menu (because it's not a menu). Any other ideas would be appreciated... A: Gtk provides function gtk_status_icon_position_menu that can be passed into gtk_menu_popup as a GtkPositionFunc. This seems to provide the requested functionality. A: The behavior i experienced in windows with gtk_status_icon_position_menu was that it spawns the window at the location the user clicked in the statusicon A: I am also looking for an answer to this but have found something that might help. It seems to me that GTK figures out where to bring up the PopupMenu from the mouse position. Somehow it figures out that the mouse button was clicked over the StatusIcon. Presumably either from mouse events sent by the windowing system or from some sort of knowledge of where the StatusIcon is. What I am getting at is that GTK must either 1) know the actual location of the StatusIcon or 2) get events from the windowing system when the mouse is clicked on the StatusIcon. So it must know the information. I also have a popup window I want to raise near the StatusIcon and I also have a PopupMenu that is working fine. So I tried this, in pygtk: x, y, push = gtk.status_icon_position_menu(popup_menu, status_icon) I passed in the PopupMenu to try to find the StatusIcon even though I'm not trying to popup the menu. This does get a position near the StatusIcon but the weird thing is that it only works after the PopupMenu has been popped up once. Anyway, that got me a little closer and might help you or someone else find a complete solution.
Getting the position of the gtk.StatusIcon on Windows
I am assisting with Windows support for a PyGTK app that appears as a system tray applet, but am not so strong on the GTK+ gooey stuff... We have it so when you left-click the systray icon, the window appears right by your tray icon no matter where your system tray is--and on Linux this works great, using the results of gtk.StatusIcon.get_geometry() to calculate the size and position. Of course, the docs for gtk.StatusIcon.get_geometry() point out that "some platforms do not provide this information"--and this includes MS Windows, as I get NoneType as the result. I can make a guess and position the window in the bottom-right corner of the screen, 30 pixels up from the bottom--as this will catch the majority of Windows users who haven't moved the taskbar. But for those that have, it looks all wrong. So is there a Windows-friendly way to get the position of the systray icon so I can place my window there? Please note: I am already using gtk_menu_popup() with gtk_status_icon_position_menu for a pop-up menu which works correctly. But what I am trying to position is a separate gtk.Window, which will not accept gtk_status_icon_position_menu (because it's not a menu). Any other ideas would be appreciated...
[ "Gtk provides function gtk_status_icon_position_menu that can be passed into gtk_menu_popup as a GtkPositionFunc.\nThis seems to provide the requested functionality.\n", "The behavior i experienced in windows with gtk_status_icon_position_menu was that it spawns the window at the location the user clicked in the ...
[ 1, 0, 0 ]
[]
[]
[ "gtk", "pygtk", "python", "windows" ]
stackoverflow_0001246552_gtk_pygtk_python_windows.txt
Q: dictionary in python problem problem.getSuccessors(getStartState()) - it returns something like ( (4,5) , north, 1) - that means 3 things - tuple, direction,cost. I'm using a dictionary ,closed = {} Now I need to put the output of above function in the dictionary "closed" - how can I do that?? I need to use only dictionary because I need to return "action" i.e North, south....at the end of function. after doing some iterations, my dict is going to have multiple entries such as ((4,5),north,1) , ((3,4),south,1) and I need to extract the key from the dict i.e (4,5) .what shud I use? A: I need to put the output of above function in the dictionary "closed" - how can I do that?? It entirely depends on what you want to use as the key, and what as the value! If the key is something completely unrelated to the tuple ( (4,5) , north, 1) (I'm not sure what the north identifier is supposed to be or how it got thee -- you sure it's not the string 'north' instead?!), then @mipadi's answer is correct. If the first item (the nested tuple) is the key, the other two the value, then, after s = problem.getSuccessors(getStartState()) you'll do: closed[s[0]] = s[1:] If the "tuple and direction", together, are the key, and just the cost is the value, then you'll do, instead: closed[s[:2]] = s[2] So, what is it that you intend to use as the key into the dictionary closed?! A: closed = {} # ... closed["your_key"] = problem.getSuccessors(getStartState()) Responding to comment: If by "take out" you mean you want (4,5) to be the key and (north, 1) to be the value, you can slice the tuple: val = problem.getSuccessors(getStartState()) closed[val[0]] = val[1:] If you just want to drop the (4,5), you can also slice the tuple: closed["your_key"] = problem.getSuccessors(getStartState())[1:] And yes, you can use a variable as a key instead of a hard-coded string.
dictionary in python problem
problem.getSuccessors(getStartState()) - it returns something like ( (4,5) , north, 1) - that means 3 things - tuple, direction,cost. I'm using a dictionary ,closed = {} Now I need to put the output of above function in the dictionary "closed" - how can I do that?? I need to use only dictionary because I need to return "action" i.e North, south....at the end of function. after doing some iterations, my dict is going to have multiple entries such as ((4,5),north,1) , ((3,4),south,1) and I need to extract the key from the dict i.e (4,5) .what shud I use?
[ "\nI need to put the output of above\n function in the dictionary \"closed\" -\n how can I do that??\n\nIt entirely depends on what you want to use as the key, and what as the value! If the key is something completely unrelated to the tuple ( (4,5) , north, 1) (I'm not sure what the north identifier is supposed ...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003262226_python.txt
Q: How to decode JSON string to string, not unicode I'm trying to decode a json of a dictionary with strings as keys. The result is a dictionary with unicode keys. What is the best way to decode to a dictionary with string keys? Better: how do I prevent that strings are decoded into unicode strings? Off course I can loop afterwards... What happens: >>> import simplejson >>> simplejson.loads('{"bar":["baz", null, 1.0, 2]}') {u'bar': [u'baz', None, 1.0, 2]} >>> simplejson.loads('"bar"') u'bar' Desired behaviour: >>> import simplejson >>> simplejson.loads('{"bar":["baz", null, 1.0, 2]}', ...?) {'bar': ['baz', None, 1.0, 2]} >>> simplejson.loads('"bar"', ..?) 'bar' A: You can't. Encode the strings after loading. Or even better, fix the rest of the code so that it doesn't fall over when using unicode.
How to decode JSON string to string, not unicode
I'm trying to decode a json of a dictionary with strings as keys. The result is a dictionary with unicode keys. What is the best way to decode to a dictionary with string keys? Better: how do I prevent that strings are decoded into unicode strings? Off course I can loop afterwards... What happens: >>> import simplejson >>> simplejson.loads('{"bar":["baz", null, 1.0, 2]}') {u'bar': [u'baz', None, 1.0, 2]} >>> simplejson.loads('"bar"') u'bar' Desired behaviour: >>> import simplejson >>> simplejson.loads('{"bar":["baz", null, 1.0, 2]}', ...?) {'bar': ['baz', None, 1.0, 2]} >>> simplejson.loads('"bar"', ..?) 'bar'
[ "You can't. Encode the strings after loading. Or even better, fix the rest of the code so that it doesn't fall over when using unicode.\n" ]
[ 2 ]
[]
[]
[ "json", "python" ]
stackoverflow_0003262850_json_python.txt
Q: High Dimension Nearest Neighbor Search and Locality Sensitivity Hashing Here is the main problem. I have very large database (25,000 or so) of 48 dimensional vectors, each populated with values ranging from 0-255. The specifics are not so important but I figure it might help give context. I don't need a nearest neighbor, so approximate neighbor searches that are within a degree of accuracy are acceptable. I've been toying around with Locality Sensitivity Hashing but I'm very very lost. I've written a hash function as described in the article under "Stable Distributions" as best I can. Here is the code. def lsh(vector, mean, stdev, r = 1.0, a = None, b = None): if not a: a = [normalvariate(mean, stdev) for i in range(48)] if not b: b = uniform(0, r) hashVal = (sum([a[i]*vectorA[i] for i in range(48)]) + b)/r return hashVal The hashing function is 'working' at least some. If I order a list of points by hash value and compute average distance between a point and it's neighbor in the list, the average distance is about 400, compared to an average distance of about 530 for any two randomly selected points. My biggest questions are these. A: Any suggestions on where I can read more about this. My searching hasn't produced a lot of results. B: The method suggests it outputs an integer value (which mine does not). And then you're supposed to try to find matches for this integer value and a match denotes a likely nearest neighbor. I understand I'm supposed to compute some set of tables of hash values for all my points and then check said tables for hash matches, but the values I'm returning don't seem to be fine enough that I'll end up with matches at all. More testing is needed on my part. C: Instructions on how to construct hash functions based on the other hashing methods? A: Maby this is a little off topic but you can try using PCA http://en.wikipedia.org/wiki/Principal_component_analysis for reducing the dimensionality of the dataset. There should be plenty of PCA modules designed for numPy ( for example: http://folk.uio.no/henninri/pca_module/). The method is rather simple and with a ready to use modules it will be a snap. Basicly what it does is reduce the number of dimensions ( you should be able to specify desired number) by maximizing variance within the given number of dimensions. A: Here are two answers: B: The Wikipedia page indicates that math.floor() should be used on hashVal: this is how you obtain integers. C: If you want to use the Hamming method, you can implement it quite simply: each Hamming hash function is simply defined by a coordinate (between 0 and 47) and a bit number (between 0 and 7). You can get the value of an integer at a given bit b with: bool(i & 2**b)
High Dimension Nearest Neighbor Search and Locality Sensitivity Hashing
Here is the main problem. I have very large database (25,000 or so) of 48 dimensional vectors, each populated with values ranging from 0-255. The specifics are not so important but I figure it might help give context. I don't need a nearest neighbor, so approximate neighbor searches that are within a degree of accuracy are acceptable. I've been toying around with Locality Sensitivity Hashing but I'm very very lost. I've written a hash function as described in the article under "Stable Distributions" as best I can. Here is the code. def lsh(vector, mean, stdev, r = 1.0, a = None, b = None): if not a: a = [normalvariate(mean, stdev) for i in range(48)] if not b: b = uniform(0, r) hashVal = (sum([a[i]*vectorA[i] for i in range(48)]) + b)/r return hashVal The hashing function is 'working' at least some. If I order a list of points by hash value and compute average distance between a point and it's neighbor in the list, the average distance is about 400, compared to an average distance of about 530 for any two randomly selected points. My biggest questions are these. A: Any suggestions on where I can read more about this. My searching hasn't produced a lot of results. B: The method suggests it outputs an integer value (which mine does not). And then you're supposed to try to find matches for this integer value and a match denotes a likely nearest neighbor. I understand I'm supposed to compute some set of tables of hash values for all my points and then check said tables for hash matches, but the values I'm returning don't seem to be fine enough that I'll end up with matches at all. More testing is needed on my part. C: Instructions on how to construct hash functions based on the other hashing methods?
[ "Maby this is a little off topic but you can try using PCA http://en.wikipedia.org/wiki/Principal_component_analysis for reducing the dimensionality of the dataset. There should be plenty of PCA modules designed for numPy ( for example: http://folk.uio.no/henninri/pca_module/).\nThe method is rather simple and with...
[ 2, 2 ]
[]
[]
[ "math", "python" ]
stackoverflow_0003262633_math_python.txt
Q: Python: Why does the tab character show up weird in Tkinter? This a screenshot from a Tkinter Listbox in a program I'm writing: Why does the \t character show up as a black bar? On a Mac it shows up normally (as a tab), but on Windows I get this. I think it might have something to do with character encoding because strings are unicode by default in OS X but not Windows? I tried writing the tab as chr(9) instead of \t, but it didn't help. A: On Windows, the tab character is probably not interpreted by the Listbox rendering code but on Mac, it is. Hence, the difference. But I'm unsure about this since, IIRC, Tkinter uses its own rendering code so it should render the same on all platforms. Maybe this is part of the OS's font rendering code (which is more powerful on the Mac). It's not a problem of encoding since the tab character is the same on all encodings (well, with the exception of EBCDIC but you're not on a mainframe, so ...)
Python: Why does the tab character show up weird in Tkinter?
This a screenshot from a Tkinter Listbox in a program I'm writing: Why does the \t character show up as a black bar? On a Mac it shows up normally (as a tab), but on Windows I get this. I think it might have something to do with character encoding because strings are unicode by default in OS X but not Windows? I tried writing the tab as chr(9) instead of \t, but it didn't help.
[ "On Windows, the tab character is probably not interpreted by the Listbox rendering code but on Mac, it is. Hence, the difference. But I'm unsure about this since, IIRC, Tkinter uses its own rendering code so it should render the same on all platforms. Maybe this is part of the OS's font rendering code (which is mo...
[ 0 ]
[]
[]
[ "character_encoding", "python", "special_characters", "tkinter" ]
stackoverflow_0003263227_character_encoding_python_special_characters_tkinter.txt
Q: sets in python problem I want to use sets as data structure. how should i make it possible? what are the commands I need? Like closedset = set() is this ok? And in a set, if i want to get some value out, what is the command for that one? A: Correct. To create an empty set, write foo = set(). To retrieve values, you can iterate over the set: for val in someset: print val You can also write val in someset to check if an item is in a set. Be sure to read the documentation for how to do set operations. A: You can saymySet = set(), which will give you a blank set to work with. Additionally, one method I found useful usually is converting from tuples/lists to sets, which you can do by saying mySet = set([1,2,3,4,5]). What do you mean you'd like to get some value out? As in whether or not an item is a member of the set? For determining membership, you can use the usual python idiom of 1 in mySet to determine whether 1 is in the set or not. And yes, the docs are right here
sets in python problem
I want to use sets as data structure. how should i make it possible? what are the commands I need? Like closedset = set() is this ok? And in a set, if i want to get some value out, what is the command for that one?
[ "Correct. To create an empty set, write foo = set(). To retrieve values, you can iterate over the set: \nfor val in someset:\n print val\n\nYou can also write val in someset to check if an item is in a set.\nBe sure to read the documentation for how to do set operations.\n", "You can saymySet = set(), which wi...
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003263272_python.txt
Q: Creating a matrix from simple three column text fie I'm trying to create a matrix or a contingency table from a file that has this format: Species Date Data 1 Dec 3 2 Jan 4 2 Dec 6 2 Dec 3 Result 1 2 Dec 3 9 Jan 4 More that I'd like to know how to turn myfile into an array that numpy will like. Basically I'm trying to recreate reshape from R Hope this made sense. ThanksBlockquote Made some edits so it might make more sense A: When other people say "Matrix" you have a dictionary with a two-part key. The problem is murky, but you have something like this. matrix = {} # read input matrix[ (row,column) ] = data row_keys = set( r for r,c in matrix.keys() ) col_keys = set( c for r,c in matrix.keys() ) for r in row_keys: print( r, ":", end=' ' ) for c in col_keys: print( matrix.get( (r,c), None ), end=' ' ) print( end='\n' ) [This requires from __future__ import print_function for Python 2.7.]
Creating a matrix from simple three column text fie
I'm trying to create a matrix or a contingency table from a file that has this format: Species Date Data 1 Dec 3 2 Jan 4 2 Dec 6 2 Dec 3 Result 1 2 Dec 3 9 Jan 4 More that I'd like to know how to turn myfile into an array that numpy will like. Basically I'm trying to recreate reshape from R Hope this made sense. ThanksBlockquote Made some edits so it might make more sense
[ "When other people say \"Matrix\" you have a dictionary with a two-part key.\nThe problem is murky, but you have something like this.\nmatrix = {}\n# read input\n matrix[ (row,column) ] = data\n\nrow_keys = set( r for r,c in matrix.keys() )\ncol_keys = set( c for r,c in matrix.keys() )\n\nfor r in row_keys:\n ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003263759_python.txt
Q: How to make a python regex? I am working on a loginMiddleware class for Django. This middleware class must send a user to the login page when it's not logedin. But there are a few exceptions. Because i run the build-in django server i had to make a media url. But know is de problem that when the login page loads a javascript file, the javascript file is the loginpage, because the user isn't logedin. Because of that reason i made a statement: from django.http import HttpResponseRedirect from django.conf import settings import re class loginMiddelware: def process_request(self,request): if request.path != settings.LOGIN_PATH and request.user.is_anonymous(): if request.path.find('media') <= 0: return HttpResponseRedirect(settings.LOGIN_PATH) else: return None I mean the line with: if request.path.find('media') <= 0:. It works, but i don't find this a good method. I think that i must use a regex for that. So i looked to the re.match function, and tried different thinks, but nothing worked. I want a regex what allows only al urls beginning with /media/ and ending with one of the next extentions: js, css, png, gif or jpg. How is this posible? Thanx! Tom A: Sure: DIRECT_ACCESS = re.compile(r'^/media/.*\.(js|css|png|gif|jpg)$') ... if DIRECT_ACCESS.match(url): ... Hint: If you want to make sure your regexp works, write a couple of unit tests that execute it. That way, you won't get any nasty surprises. A: You don't need a regex: if request.path.startswith('/path/to/your/media'): #do something should do the trick. You are complaining about the fact, that if the request path contains: /protected/secure/media/bla that your implentation will let the user through. So using a absolute path with the string method startswith is sufficient for your problem. A: Take a look at Matt Grayson's Require Login Middleware. It lets you define a bunch of URLs that do not require logging in using a custom LOGIN_REQUIRED_URLS_EXCEPTIONS setting.
How to make a python regex?
I am working on a loginMiddleware class for Django. This middleware class must send a user to the login page when it's not logedin. But there are a few exceptions. Because i run the build-in django server i had to make a media url. But know is de problem that when the login page loads a javascript file, the javascript file is the loginpage, because the user isn't logedin. Because of that reason i made a statement: from django.http import HttpResponseRedirect from django.conf import settings import re class loginMiddelware: def process_request(self,request): if request.path != settings.LOGIN_PATH and request.user.is_anonymous(): if request.path.find('media') <= 0: return HttpResponseRedirect(settings.LOGIN_PATH) else: return None I mean the line with: if request.path.find('media') <= 0:. It works, but i don't find this a good method. I think that i must use a regex for that. So i looked to the re.match function, and tried different thinks, but nothing worked. I want a regex what allows only al urls beginning with /media/ and ending with one of the next extentions: js, css, png, gif or jpg. How is this posible? Thanx! Tom
[ "Sure:\nDIRECT_ACCESS = re.compile(r'^/media/.*\\.(js|css|png|gif|jpg)$')\n\n...\n\nif DIRECT_ACCESS.match(url):\n ...\n\nHint: If you want to make sure your regexp works, write a couple of unit tests that execute it. That way, you won't get any nasty surprises.\n", "You don't need a regex:\nif request.path.st...
[ 3, 2, 1 ]
[]
[]
[ "django", "python", "regex" ]
stackoverflow_0003263819_django_python_regex.txt
Q: reading from stdin, while consuming no more memory than needed I am trying to create a line-by-line filter in python. However, stdin.readlines() reads all lines in before starting to process, and python runs out of memory (MemoryError). How can I have just one line in memory at a time? The kind of code I have: for line in sys.stdin.readlines(): if( filter.apply( line ) ): print( line ) (note: I'm on 2.6) A: for line in sys.stdin: ... Or call .readline() in a loop. A: import sys while 1: line = sys.stdin.readline() if not line: break if (filter.apply(line)): print(line)
reading from stdin, while consuming no more memory than needed
I am trying to create a line-by-line filter in python. However, stdin.readlines() reads all lines in before starting to process, and python runs out of memory (MemoryError). How can I have just one line in memory at a time? The kind of code I have: for line in sys.stdin.readlines(): if( filter.apply( line ) ): print( line ) (note: I'm on 2.6)
[ "for line in sys.stdin:\n ...\n\nOr call .readline() in a loop.\n", "import sys\nwhile 1:\n line = sys.stdin.readline()\n if not line:\n break\n if (filter.apply(line)):\n print(line)\n\n" ]
[ 13, 2 ]
[]
[]
[ "line_by_line", "pipe", "python", "stdin" ]
stackoverflow_0003263665_line_by_line_pipe_python_stdin.txt
Q: Multiple Python Installations of the same python version on a single computer I want to install the new Python 2.7 on my Windows XP 32bit PC. having CDO (thats OCD with initials sorted in alphabetical order) I want to install it multiple times on the same computer (to different TARGETDIRs). how do i do that ? double clicking on the installer, or running msiexec multiple times did not work for me Coincidentally, I noticed that the windows python installation does not ask me if I want to add a Start Menu option. I want my installations of python not to show up on the Start Menu. How do I do that? be well A: If I understand correctly you want multiple independent copies of Python 2.7 running on Windows. I assume that is so you can install just the packages you need for each project and not have different projects fighting over conflicting versions. Try using virtualenv (http://pypi.python.org/pypi/virtualenv). You install Python once, then whenever you need a new copy you run virtualenv.py and it effectively gives you a clean environment with an activate script (activate.bat on Windows) that makes that environment the current one. Having said all that, I've only used virtualenv on Linux so I don't know how well it works on Windows, but it certainly claims to work on Windows so give it a go. Edit: For running Python scripts on machines without having to worry whether or not it is already there, the usual solution is to use py2exe (http://www.py2exe.org/). That bundles your application and all libraries together with Python in a single standalone file which can be run without any installation. A: Based on one of your comments, it looks like you don't actually need to install it, you just need it on the computer so your program can run. In that case you can take a page from Dropbox's book and include the interpreter, DLL, and standard library in one of your directories, and just use it from there.
Multiple Python Installations of the same python version on a single computer
I want to install the new Python 2.7 on my Windows XP 32bit PC. having CDO (thats OCD with initials sorted in alphabetical order) I want to install it multiple times on the same computer (to different TARGETDIRs). how do i do that ? double clicking on the installer, or running msiexec multiple times did not work for me Coincidentally, I noticed that the windows python installation does not ask me if I want to add a Start Menu option. I want my installations of python not to show up on the Start Menu. How do I do that? be well
[ "If I understand correctly you want multiple independent copies of Python 2.7 running on Windows. I assume that is so you can install just the packages you need for each project and not have different projects fighting over conflicting versions.\nTry using virtualenv (http://pypi.python.org/pypi/virtualenv). You in...
[ 1, 0 ]
[]
[]
[ "installation", "python", "windows_installer" ]
stackoverflow_0003263769_installation_python_windows_installer.txt
Q: access memory mapped file created on .net via python I made a memory mapped file using MemoryMappedFile.CreateNew(mapName, capacity) of .net 4 Can i access this mmf by the mapName from cpython ? I tried like below. import mmap map = mmap.mmap(-1, 0, mapName, 1) but it returns WindowsError [error 87] saying the parameter is incorrect. I'm using windows vista. A: I have absolutely no experience with C#, but I'll attempt to answer your question. CreateNew should create a mapping to a file that doesn't reside in the filesystem. Note that this isn't cross platform in any way. On Windows, the tagname parameter of mmap.mmap should allow you to map these tagged mappings. Since the mapping is not backed by a file, the -1 for fileno is correct also. The length of 0 will obtain the entire mapping. The issue then lies with access. There is a mention that not providing the access parameter will give write-through mapping on Windows, you might try experimenting with this. If all else fails, try falling back to using a file-backed memory mapping, it's more portable, and far more common. The C# MemoryMappedFile class provides the CreateFromFile method for this.
access memory mapped file created on .net via python
I made a memory mapped file using MemoryMappedFile.CreateNew(mapName, capacity) of .net 4 Can i access this mmf by the mapName from cpython ? I tried like below. import mmap map = mmap.mmap(-1, 0, mapName, 1) but it returns WindowsError [error 87] saying the parameter is incorrect. I'm using windows vista.
[ "I have absolutely no experience with C#, but I'll attempt to answer your question.\nCreateNew should create a mapping to a file that doesn't reside in the filesystem. Note that this isn't cross platform in any way. On Windows, the tagname parameter of mmap.mmap should allow you to map these tagged mappings. Since ...
[ 1 ]
[]
[]
[ ".net", "memory_mapped_files", "python" ]
stackoverflow_0003257109_.net_memory_mapped_files_python.txt
Q: Any way to keep track of the last 5 data points in python So I have an array that holds several numbers. As my script runs, more and more numbers are appended to this array. However, I am not interested in all the numbers but just want to keep track of the last 5 numbers. Currently, I just store all the numbers in the array. However, this array gets really big and it's full of unnecessary information. I have thought about making a function that when it adds an element to the array, also removes the last element if the array already contains 5 numbers. I also thought about making a new class to create a data structure that does what I want. However, I only need to reference this array occasionally and is only a small part of the script. So I think it is overkill if I create a whole new class to do this. What is the best way to do this? A: Try using a deque: http://docs.python.org/library/collections.html#deque-objects "If maxlen is not specified or is None, deques may grow to an arbitrary length. Otherwise, the deque is bounded to the specified maximum length. Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end. Bounded length deques provide functionality similar to the tail filter in Unix. They are also useful for tracking transactions and other pools of data where only the most recent activity is of interest." A: I fully agree with the idea of using Python's limited-length deque if it's available, and if not, Michael Anderson's simple solution is quite adequate. (I upvoted both) But I just wanted to mention the third option of a ring buffer, which is often used for this kind of task when low memory footprint and high execution speed are important. (In other words, in situations when you probably wouldn't be using Python :-p) For example, the Linux kernel uses this structure to store log messages generated during the boot process, before the system logger starts. A Python implementation could look like this: class RingBuffer(object): def __init__(self, n): self._buf = [None] * n self._index = 0 self._valid = 0 def add(self, obj): n = len(self._buf) self._buf[self._index] = obj self._index += 1 if self._index == n self._index = 0 if self._valid < n: self._valid += 1 def __len__(self): return self._valid # could include other methods for accessing or modifying the contents Basically what it does is preallocate an array (in Python, a list) of the desired length and fill it with dummy values. The buffer also contains an "index" which points to the next spot in the list that should be filled with a value. Each time a value is added, it's stored in that spot and the index is incremented. When the index reaches the length of the array, it's reset back to zero. Here's an example (I'm using 0 instead of None for the dummy value just because it's quicker to type): [0,0,0,0,0] ^ # add 1 [1,0,0,0,0] ^ # add 2 [1,2,0,0,0] ^ # add 3 [1,2,3,0,0] ^ # add 4 [1,2,3,4,0] ^ # add 5 [1,2,3,4,5] ^ # add 6 [6,2,3,4,5] ^ # add 7 [6,7,3,4,5] ^ and so on. A: The class can be pretty trivial: class ListOfFive: def __init__(self): self.data = [] def add(self,val): if len(self.data)==5: self.data=self.data[1:]+[val] else: self.data+=[val] l = ListOfFive() for i in range(1,10): l.add(i) print l.data Output is: [1] [1, 2] [1, 2, 3] [1, 2, 3, 4] [1, 2, 3, 4, 5] [2, 3, 4, 5, 6] [3, 4, 5, 6, 7] [4, 5, 6, 7, 8] [5, 6, 7, 8, 9] A: Another neat ring buffer implementation can be found in the ActiveState Recipes - your ring buffer object starts out as an instance of RingBuffer while filling up at first, and then your instance changes its class to RingBufferFull, an optimized full implementation. It always makes me smile. class RingBuffer: def __init__(self,size_max): self.max = size_max self.data = [] def append(self,x): """append an element at the end of the buffer""" self.data.append(x) if len(self.data) == self.max: self.cur=0 self.__class__ = RingBufferFull def get(self): """ return a list of elements from the oldest to the newest""" return self.data class RingBufferFull: def __init__(self,n): raise "you should use RingBuffer" def append(self,x): self.data[self.cur]=x self.cur=(self.cur+1) % self.max def get(self): return self.data[self.cur:]+self.data[:self.cur] A: From your description, I would add the following type of statement just after the code that extends your list: mylist = mylist[-5:] It will then only ever be a maximum of 5 values in length Here is a quick example: >>> mylist = [] >>> i = 1 >>> while i<6: print ("\n Pre addition: %r" % mylist) mylist += range(i) print (" Addition: %r" % mylist) mylist = mylist[-5:] print (" Chopped: %r" % mylist) i += 1 Pre addition: [] Addition: [0] Chopped: [0] Pre addition: [0] Addition: [0, 0, 1] Chopped: [0, 0, 1] Pre addition: [0, 0, 1] Addition: [0, 0, 1, 0, 1, 2] Chopped: [0, 1, 0, 1, 2] Pre addition: [0, 1, 0, 1, 2] Addition: [0, 1, 0, 1, 2, 0, 1, 2, 3] Chopped: [2, 0, 1, 2, 3] Pre addition: [2, 0, 1, 2, 3] Addition: [2, 0, 1, 2, 3, 0, 1, 2, 3, 4] Chopped: [0, 1, 2, 3, 4] >>>
Any way to keep track of the last 5 data points in python
So I have an array that holds several numbers. As my script runs, more and more numbers are appended to this array. However, I am not interested in all the numbers but just want to keep track of the last 5 numbers. Currently, I just store all the numbers in the array. However, this array gets really big and it's full of unnecessary information. I have thought about making a function that when it adds an element to the array, also removes the last element if the array already contains 5 numbers. I also thought about making a new class to create a data structure that does what I want. However, I only need to reference this array occasionally and is only a small part of the script. So I think it is overkill if I create a whole new class to do this. What is the best way to do this?
[ "Try using a deque:\nhttp://docs.python.org/library/collections.html#deque-objects\n\"If maxlen is not specified or is None, deques may grow to an arbitrary length. Otherwise, the deque is bounded to the specified maximum length. Once a bounded length deque is full, when new items are added, a corresponding number ...
[ 14, 7, 4, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003261090_python.txt
Q: how to interact with an external script(program) there is a script that expects keyboard input, i can call that script with os.system('./script') in python, how is it possible to send back an input to the script from another calling script? update: the script is: $ cat script #!/usr/bin/python for i in range(4): name=raw_input('enter your name') print 'Welcome %s :) ' % name when i try without a for loop, it works but it shows the output only when the script quits. >>> p = subprocess.Popen('./script',stdin=subprocess.PIPE) >>> p.communicate('navras') enter your nameWelcome navras :) when i try it with the foor loop, it throws error, How to display the statements interactive as and when the stdout is updated with new print statements >>> p.communicate('megna') enter your nameWelcome megna :) enter your nameTraceback (most recent call last): File "./script", line 3, in <module> name=raw_input('enter your name') EOFError: EOF when reading a line (None, None) A: You can use subprocess instead of os.system: p = subprocess.Popen('./script',stdin=subprocess.PIPE) p.communicate('command') its not testet
how to interact with an external script(program)
there is a script that expects keyboard input, i can call that script with os.system('./script') in python, how is it possible to send back an input to the script from another calling script? update: the script is: $ cat script #!/usr/bin/python for i in range(4): name=raw_input('enter your name') print 'Welcome %s :) ' % name when i try without a for loop, it works but it shows the output only when the script quits. >>> p = subprocess.Popen('./script',stdin=subprocess.PIPE) >>> p.communicate('navras') enter your nameWelcome navras :) when i try it with the foor loop, it throws error, How to display the statements interactive as and when the stdout is updated with new print statements >>> p.communicate('megna') enter your nameWelcome megna :) enter your nameTraceback (most recent call last): File "./script", line 3, in <module> name=raw_input('enter your name') EOFError: EOF when reading a line (None, None)
[ "You can use subprocess instead of os.system:\np = subprocess.Popen('./script',stdin=subprocess.PIPE)\np.communicate('command')\n\nits not testet\n" ]
[ 1 ]
[ "In fact, os.system and os.popen are now deprecated and subprocess is the recommended way to handle all sub process interaction.\n" ]
[ -2 ]
[ "bash", "externalinterface", "interaction", "python" ]
stackoverflow_0003264257_bash_externalinterface_interaction_python.txt
Q: How to pass variable in exec statment in python I am having two python files as 1.py and 2.py. **1.py is as** class A: def __init__(self): x = 5 y = 7 NUMBERS = self fp = open(filePath) temp = fp.read() exec(temp) fp.close() ADD_METHOD() **2.py is as** def ADD_METHOD(): print NUMBERS.x + NUMBERS.y Now My question how this NUMBERS varaible is available in 2.py file. This is example for better view of problem, i know i can do this by importing module but the problem is that i have to do solution with exec() method and ho can i get NUMBERS in 2.py file ie should i have to pass this with exec as argument or some other approach. Any Help really appreciable Thanks A: If these are both Python files that you wrote yourself, why not just create a function in 2.py that you can import and call in 1.py? This is a much easier and cleaner abstraction. It also avoids the creation of a new process. You could write something like this: # **1.py is as** from 2 import ADD_METHOD class A: def __init__(self): x = 5 y = 7 ADD_METHOD(x, y) # **2.py is as** def ADD_METHOD(x, y): print x + y Note that you really should pick better names than 1.py and 2.py to avoid confusion later ;) A: I'm not sure what exactly you need, but I have a solution to your trivial example that follows your limitations. # 1.py ... os.execl( "2.py", str( NUMBERS.x ), str( NUMBERS.y ) ) # 2.py from collections import namedtuple A = namedtuple( "A", "x y" ) NUMBERS = A( x=sys.argv[1], y=sys.argv[2] ) ...
How to pass variable in exec statment in python
I am having two python files as 1.py and 2.py. **1.py is as** class A: def __init__(self): x = 5 y = 7 NUMBERS = self fp = open(filePath) temp = fp.read() exec(temp) fp.close() ADD_METHOD() **2.py is as** def ADD_METHOD(): print NUMBERS.x + NUMBERS.y Now My question how this NUMBERS varaible is available in 2.py file. This is example for better view of problem, i know i can do this by importing module but the problem is that i have to do solution with exec() method and ho can i get NUMBERS in 2.py file ie should i have to pass this with exec as argument or some other approach. Any Help really appreciable Thanks
[ "If these are both Python files that you wrote yourself, why not just create a function in 2.py that you can import and call in 1.py? This is a much easier and cleaner abstraction. It also avoids the creation of a new process. You could write something like this:\n# **1.py is as**\nfrom 2 import ADD_METHOD\nclass A...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003263656_python.txt
Q: Which python installation should I use? I'm about to refresh myself in programming and I have decided on Python 2.6 for that. I have searched the net and it gave me two possible installers for download. One is from the Python site and another is from Activestate. Which one should I install on my Windows computer? A: ActiveState gives you paid support. While this may be very important / critical to some companies, most do just fine with python.org version, particularly those who experiment. There are other crazy ones like Stackless Python, Google's implementation in C++, Cython, etc. I would say that those are not that important to you unless speed / efficient multithreading is a must. Use the regular one. CPython may be an order of magnitude slower than C, but it works just fine AND it is the most popular Python implementation out there, so you know it is well-tested for a free version. A: I suggest you to download from python site A: ActivePython is essentially the same as python.org's distro - except you also get the following: PyPM: a binary package manager from ActiveState, so you can install extra modules without having to compile them yourself. (See available modules) Additional packages: virtualenv, setuptools/easy_install, pip PyWin32 - Accessing Windows API from Python Extra documentation/tutorials (CHM on Windows) such as Dive Into Python, FAQs, PEPs, etc.. PythonWin IDE (although Komodo Edit may suit some better) If you are a business owner, then ActiveState can also provide commercial support. A: If all you want is refresh your programming skill, then installing the version from the official site should be more than enough A: Download Python 2.6 from the python.org and read its tutorial as a start. A: Since you're running Windows you may want to also install (after Python 2.6) Pywin32 - Python Extensions for Windows: . It also has a very nice IDE (PythonWin) which you may prefer to IDLE. A version of Pywin32 is also available for Python 3.x. A: I also do recommend ACTIVESTATE - with the standard python.org package you will have lots of trouble when you want to install packages! BUT be prepared to be bitten from time to time by ActiveState: D:\>pypm search lxml *** Packages marked [BE] below require a valid *** Business Edition license to install. Please visit *** http://www.activestate.com/business-edition for more details. domstripper lxml.html based DOM manipulator flea Test WSGI applications using lxml gocept.lxml Primarily proivdes zope3 interface definitions for lxml lwebstring lxml-based implementation of webstring, an XML template engine [BE] lxml Powerful and Pythonic XML processing library combining libxml2/libxsl [BE] lxml-wrapper lxml wrapper that simplifies xml generation code. [BE] lxmlmiddleware stack of middleware to deal with a response as a LXML etree [BE] lxmlproc lxml version of xsltproc plone.recipe.lxml Buildout recipe that creates a lxml egg repoze.xmliter Wrapper for ``lxml`` trees which serializes to string upon iteration. z3c.recipe.staticlxml A recipe to build lxml they do not provide lxml for free with their package manager, you need a business license.
Which python installation should I use?
I'm about to refresh myself in programming and I have decided on Python 2.6 for that. I have searched the net and it gave me two possible installers for download. One is from the Python site and another is from Activestate. Which one should I install on my Windows computer?
[ "ActiveState gives you paid support. While this may be very important / critical to some companies, most do just fine with python.org version, particularly those who experiment. \nThere are other crazy ones like Stackless Python, Google's implementation in C++, Cython, etc. I would say that those are not that impor...
[ 6, 5, 5, 1, 1, 1, 0 ]
[]
[]
[ "activepython", "installation", "python", "windows" ]
stackoverflow_0002126001_activepython_installation_python_windows.txt
Q: does python multiplicative expression evaluates faster if finds a zero? suppose i a have a multiplicative expression with lots of multiplicands (small expressions) expression = a*b*c*d*....*w where for example c is (x-1), d is (y**2-16), k is (xy-60)..... x,y are numbers and i know that c,d,k,j maybe zero Does the order i write the expression matters for faster evaluation? Is it better to write cdkj....*w or python will evaluate all expression no matter the order i write? A: Python v2.6.5 does not check for zero values. def foo(): a = 1 b = 2 c = 0 return a * b * c >>> import dis >>> dis.dis(foo) 2 0 LOAD_CONST 1 (1) 3 STORE_FAST 0 (a) 3 6 LOAD_CONST 2 (2) 9 STORE_FAST 1 (b) 4 12 LOAD_CONST 3 (3) 15 STORE_FAST 2 (c) 5 18 LOAD_FAST 0 (a) 21 LOAD_FAST 1 (b) 24 BINARY_MULTIPLY 25 LOAD_FAST 2 (c) 28 BINARY_MULTIPLY 29 RETURN_VALUE Update: I tested Baldur's expressions, and Python can and will optimize code that involve constant expressions. The weird is that test6 isn't optimized. def test1(): return 0 * 1 def test2(): a = 1 return 0 * a * 1 def test3(): return 243*(5539**35)*0 def test4(): return 0*243*(5539**35) def test5(): return (256**256)*0 def test6(): return 0*(256**256) >>> dis.dis(test1) # 0 * 1 2 0 LOAD_CONST 3 (0) 3 RETURN_VALUE >>> dis.dis(test2) # 0 * a * 1 5 0 LOAD_CONST 1 (1) 3 STORE_FAST 0 (a) 6 6 LOAD_CONST 2 (0) 9 LOAD_FAST 0 (a) 12 BINARY_MULTIPLY 13 LOAD_CONST 1 (1) 16 BINARY_MULTIPLY 17 RETURN_VALUE >>> dis.dis(test3) # 243*(5539**35)*0 9 0 LOAD_CONST 1 (243) 3 LOAD_CONST 5 (104736434394484...681759461305771899L) 6 BINARY_MULTIPLY 7 LOAD_CONST 4 (0) 10 BINARY_MULTIPLY 11 RETURN_VALUE >>> dis.dis(test4) # 0*243*(5539**35) 12 0 LOAD_CONST 5 (0) 3 LOAD_CONST 6 (104736433252667...001759461305771899L) 6 BINARY_MULTIPLY 7 RETURN_VALUE >>> dis.dis(test5) # (256**256)*0 15 0 LOAD_CONST 4 (0L) 3 RETURN_VALUE >>> dis.dis(test6) # 0*(256**256) 18 0 LOAD_CONST 1 (0) 3 LOAD_CONST 3 (323170060713110...853611059596230656L) 6 BINARY_MULTIPLY 7 RETURN_VALUE In brief, if the expression includes variables, the order doesn't matter. Everything will be evaluated. A: Don't try to optimize before you benchmark. With that in mind, it is true that all expressions will be evaluated even if an intermediate term is zero. Order may still matter. Expressions are evaluated from left to right. If a,b,c,... are very large numbers, they could force Python to allocate a lot of memory, slowing down the calculation before it comes to j=0. (If j=0 came earlier in the expression, then the product would never get as large and no additional memory allocation would be needed). If, after timing your code with timeit or cProfile, you feel this may be your situation, then you could try pre-evaluating c,d,k,j, and testing if not all (c,d,k,j): expression = 0 else: expression = a*b*c*d*....*w Then time this with timeit or cProfile as well. The only way to really tell if this is useful in your situation is to benchmark. In [333]: import timeit In [334]: timeit.timeit('10**100*10**100*0') Out[334]: 1.2021231651306152 In [335]: timeit.timeit('0*10**100*10**100') Out[335]: 0.13552498817443848 Although PyPy is much faster, it does not appear to optimize this either: % pypy-c Python 2.7.3 (d994777be5ab, Oct 12 2013, 14:13:59) [PyPy 2.2.0-alpha0 with GCC 4.6.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. And now for something completely different: ``http://twitpic.com/52ae8f'' >>>> import timeit >>>> timeit.timeit('10**100*10**100*0') 0.020643949508666992 >>>> timeit.timeit('0*10**100*10**100') 0.003732919692993164 A: This is just a quick check in Python 3.1: >>> import timeit >>> timeit.timeit('243*325*(5539**35)*0') 0.5147271156311035 >>> timeit.timeit('0*243*325*(5539**35)') 0.153839111328125 and this in Python 2.6: >>> timeit.timeit('243*325*(5539**35)*0') 0.72972488403320312 >>> timeit.timeit('0*243*325*(5539**35)') 0.26213502883911133 So the order does enter into it. Also I got this result in Python 3.1: >>> timeit.timeit('(256**256)*0') 0.048995018005371094 >>> timeit.timeit('0*(256**256)') 0.1501758098602295 Why on Earth? A: >>> import timeit >>> timeit.timeit('1*2*3*4*5*6*7*8*9*9'*6) 0.13404703140258789 >>> timeit.timeit('1*2*3*4*5*6*7*8*9*0'*6) 0.13294696807861328 >>>
does python multiplicative expression evaluates faster if finds a zero?
suppose i a have a multiplicative expression with lots of multiplicands (small expressions) expression = a*b*c*d*....*w where for example c is (x-1), d is (y**2-16), k is (xy-60)..... x,y are numbers and i know that c,d,k,j maybe zero Does the order i write the expression matters for faster evaluation? Is it better to write cdkj....*w or python will evaluate all expression no matter the order i write?
[ "Python v2.6.5 does not check for zero values.\ndef foo():\n a = 1\n b = 2\n c = 0\n return a * b * c\n\n>>> import dis\n>>> dis.dis(foo)\n 2 0 LOAD_CONST 1 (1)\n 3 STORE_FAST 0 (a)\n\n 3 6 LOAD_CONST 2 (2)\n 9 STO...
[ 7, 5, 5, 2 ]
[ "Probably not. Multiplication is one of the cheapest operations of all. If a 0 should be faster then it would be necessary to check for zeros before and that's probably slower than just doing the multiplication.\nThe fastest solution should be multiply.reduce()\n" ]
[ -1 ]
[ "evaluation", "math", "optimization", "python" ]
stackoverflow_0003264345_evaluation_math_optimization_python.txt
Q: Blocks within blocks I'm having problems displaying nested blocks in a template. eg. {% for category in categories %} //code to display category info {% products = products.object.filter(category = category) %} {% for product in products%} //code to display product info {% endfor %} {% endfor %} I'm getting a "Invalid block tag: 'endfor'" error. Any ideas? A: You cannot assign to variables in the Django template system. Your two attempts: {% products = products.object.filter(category = category) %} and {% products = category.get_products %} are both invalid Django syntax. Some Python templating systems are PHP-like: they let you embed Python code into HTML files. Django doesn't work this way. Django defines its own simplified syntax, and that syntax does not include assignment. You can do this: {% for category in categories %} //code to display category info {% for product in category.get_products %} //code to display product info {% endfor %} {% endfor %} A: I think you cannot use arguemnts for methods. You have to modify your categories object, so that you kann use: {% for product in category.products %} A: {% products = products.object.filter(category = category) %} is not recognized as a valid tag in the django template system. Therefore django complains about the missing endfor, although the {% for x in y %) is not the error. This should work {% for category in categories %} {% for product in products.object.all %} //code to display product info {% endfor %} {% endfor %} But this is not that, what you want to achieve. Simply you are not able to filter on product.objects with the argument category. You have to write your own tag which takes arguments on filtering or rethink your problem.
Blocks within blocks
I'm having problems displaying nested blocks in a template. eg. {% for category in categories %} //code to display category info {% products = products.object.filter(category = category) %} {% for product in products%} //code to display product info {% endfor %} {% endfor %} I'm getting a "Invalid block tag: 'endfor'" error. Any ideas?
[ "You cannot assign to variables in the Django template system. Your two attempts:\n{% products = products.object.filter(category = category) %}\n\nand\n{% products = category.get_products %}\n\nare both invalid Django syntax.\nSome Python templating systems are PHP-like: they let you embed Python code into HTML fi...
[ 1, 0, 0 ]
[]
[]
[ "block", "django", "django_templates", "python" ]
stackoverflow_0003264101_block_django_django_templates_python.txt
Q: Can modules be added to the Python search path (e.g site-packages dir) using symbolic links on Windows? I tried to create a symbolic link in the Python site-packages directory using the mklink /D syntax (on a Windows 7 machine). Unfortunately the module is not found when using import clause. When I copy the module physicaly to site-package directory, it works OK. Am I doing something wrong or is this just not possible on Windows? I am using Python 2.6. A: I just did it on Windows 7 using Python 2.7, and it works. Here are the steps I followed. open a windows command prompt with necessary privileges cd to the site-packages directory cd c:\Python27\Lib\site-packages create the link mklink /D modulename c:\path\to\module\real\location\modulename
Can modules be added to the Python search path (e.g site-packages dir) using symbolic links on Windows?
I tried to create a symbolic link in the Python site-packages directory using the mklink /D syntax (on a Windows 7 machine). Unfortunately the module is not found when using import clause. When I copy the module physicaly to site-package directory, it works OK. Am I doing something wrong or is this just not possible on Windows? I am using Python 2.6.
[ "I just did it on Windows 7 using Python 2.7, and it works. Here are the steps I followed.\n\nopen a windows command prompt with necessary privileges\ncd to the site-packages directory\ncd c:\\Python27\\Lib\\site-packages\ncreate the link\nmklink /D modulename c:\\path\\to\\module\\real\\location\\modulename\n\n" ]
[ 1 ]
[]
[]
[ "python", "symlink", "windows" ]
stackoverflow_0003155462_python_symlink_windows.txt
Q: Python Lists Beginner I created a list in Python: mylist=os.listdir("/User/Me/Folder") now I have a list of files in a List. What I would like to do is: Take one file name after the other and add a URL to it: /myurl/ + each item in mylist And then I would like to write the result in a html template from Django. So that it display all the images in that folder in a list of html How can I achieve this? Thanks A: Using list comprehensions, you can transform your original list, "mylist", into a list with the URL prefix like so: urllist = ['/myurl/%s' % the_file for the_file in mylist] Analysis: a) the expression in the square brackets is the list comprehension. it says: iterate over each item in "mylist", temporarily calling the iterated item "the_file" and transform it using the subexpression: '/myurl/%s' % the_file b) the transformation expression says, create a string where %s is replaced by the string represented by the value of "the_file" A: {% for filename in listoffilenames %} /myurl/{{ filename }} {% endfor %} A: For contrast, if you feel like doing this in the view (even though there's no good reason to do so): mylist[:] = [url + x for x in mylist] If you don't need to modify the existing list then you can drop the [:].
Python Lists Beginner
I created a list in Python: mylist=os.listdir("/User/Me/Folder") now I have a list of files in a List. What I would like to do is: Take one file name after the other and add a URL to it: /myurl/ + each item in mylist And then I would like to write the result in a html template from Django. So that it display all the images in that folder in a list of html How can I achieve this? Thanks
[ "Using list comprehensions, you can transform your original list, \"mylist\", into a list with the URL prefix like so:\nurllist = ['/myurl/%s' % the_file for the_file in mylist]\n\nAnalysis:\na) the expression in the square brackets is the list comprehension. it says: iterate over each item in \"mylist\", temporari...
[ 5, 3, 1 ]
[]
[]
[ "django", "list", "python" ]
stackoverflow_0003264804_django_list_python.txt
Q: Type error in python! closedset = set() root = (5,6) for u,v in root: if v is not closedset: closedset.add(root) print closedset Error: for u,v in root: TypeError: unpack non-sequence What should i do with type of error? A: root = [(5,6)] ...should work. for iterates through a list or set, returning first u, then v. If you want to return both parts of the set, you'll have to add itself to a list. A: I'm not sure I understand what you're trying to do. Maybe: roots = [(5, 6), (2, 3)] for u, v in roots: if f not in closed: closed.add(v) print closed Note a few changes: roots is now a list of tuples. for u, v in roots will correctly "unpack" each tuple into u and v by if v is not closed your probably meant if f not in closed, if closed is a dictionary of some kind if close.add is a method (of a set?), then it has to be called with parens () and not brackets () A: root = ((5, 6),) or u, v = root Depending on what your intentions are. A: for u,v in [root]: print u,v will do what you want.
Type error in python!
closedset = set() root = (5,6) for u,v in root: if v is not closedset: closedset.add(root) print closedset Error: for u,v in root: TypeError: unpack non-sequence What should i do with type of error?
[ "root = [(5,6)]\n\n...should work.\nfor iterates through a list or set, returning first u, then v. If you want to return both parts of the set, you'll have to add itself to a list.\n", "I'm not sure I understand what you're trying to do. Maybe:\nroots = [(5, 6), (2, 3)]\n\nfor u, v in roots:\n if f not in closed...
[ 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003263057_python.txt
Q: Changing C variables from python? I have an embedded python interpreter in my program. I'd like to export a module with values defined in my program and be able to change them from a python script. e.g. in c: int x = 1; in python: import embedded embedded.x = 2 in c: printf("%d",x); output: 2 Is this possible or do I have to export functions to change anything in c? A: There's no need to export functions, but the easiest way to do this would be to use PyModule_GetDict() with PyDict_GetItemString() to get the value assigned to the x attribute. A: If you don't want to actively check the value of a PyObject in your C code, I think you need to export functions to modify the representation in C. I'm no expert, but I don't think there's an automatic mapping.
Changing C variables from python?
I have an embedded python interpreter in my program. I'd like to export a module with values defined in my program and be able to change them from a python script. e.g. in c: int x = 1; in python: import embedded embedded.x = 2 in c: printf("%d",x); output: 2 Is this possible or do I have to export functions to change anything in c?
[ "There's no need to export functions, but the easiest way to do this would be to use PyModule_GetDict() with PyDict_GetItemString() to get the value assigned to the x attribute.\n", "If you don't want to actively check the value of a PyObject in your C code, I think you need to export functions to modify the repr...
[ 0, 0 ]
[]
[]
[ "api", "c", "python" ]
stackoverflow_0003265232_api_c_python.txt
Q: Django Abstract Models vs simple Python mixins vs Python ABCs This is a question prompted by another question from me. Django provides Abstract base classes functionality (which are not to same as ABC classes in Python?) so that one can make a Model (Django's models.Model) from which one can inherit, but without that Model having an actual table in the database. One triggers this behavior by setting the 'abstract' attribute in the Model's Meta class. Now the question: why does Django solve it this way? Why the need for this special kind of 'Abstract base class' Model? Why not make a Model mixin by just inheriting from the object class and mixing that in with an existing Model? Or could this also by a task for Python ABCs? (mind you I'm not very familiar with ABC classes in Python, my ignorance might show here) A: I'll try to be reasonably brief, since this can easily turn into a lengthy diatribe: ABCs are out because they were only introduced in Python 2.6, and the Django developers have a set roadmap for Python version support (2.3 support was only dropped in 1.2). As for object-inheriting mixins, they would be less Pythonic in more ways than just reducing readability. Django uses a ModelBase metaclass for Model objects, which actually analyses the defined model properties on initialisation, and populates Model._meta with the fields, Meta options, and other properties. It makes sense to reuse that framework for both types of models. This also allows Django to prevent abstract model fields from being overriden by inheriting models. There's plenty more reasons I can think of, all of them minor in themself, but they add up to make the current implementation much more Pythonic. There's nothing inherently wrong with using object-inheriting mixins though. A: One of the reasons is because of the way fields are defined on a model. Fields are specified declaratively, in a way that a normal class would treat as class attributes. Yet they need to become instance attributes for when the class is actually instantiated, so that each instance can have its own value for each field. This is managed via the metaclass. This wouldn't work with a normal abstract base class.
Django Abstract Models vs simple Python mixins vs Python ABCs
This is a question prompted by another question from me. Django provides Abstract base classes functionality (which are not to same as ABC classes in Python?) so that one can make a Model (Django's models.Model) from which one can inherit, but without that Model having an actual table in the database. One triggers this behavior by setting the 'abstract' attribute in the Model's Meta class. Now the question: why does Django solve it this way? Why the need for this special kind of 'Abstract base class' Model? Why not make a Model mixin by just inheriting from the object class and mixing that in with an existing Model? Or could this also by a task for Python ABCs? (mind you I'm not very familiar with ABC classes in Python, my ignorance might show here)
[ "I'll try to be reasonably brief, since this can easily turn into a lengthy diatribe:\nABCs are out because they were only introduced in Python 2.6, and the Django developers have a set roadmap for Python version support (2.3 support was only dropped in 1.2).\nAs for object-inheriting mixins, they would be less Pyt...
[ 14, 8 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003263417_django_python.txt
Q: Unpickling a Python class I have a problem trying to unpickle subclasses of this class. When I unpickle it, the stuff isn't there. What gives? class Account: def __init__(self, server, port, smtp_server, smtp_port): self.server = server self.port = port self.smtp_server = smtp_server self.smtp_port = smtp_port self.save() def save(self): #save account for later loading self.name = tkFileDialog.asksaveasfilename(title = "Save as..") pickle.dump(self, open(self.name, "wr")) A: Does your class inherit object? Either way, you can specify what you want to pickle by overwriting __getstate__. Otherwise it should normally copy __dict__ if you're inheriting object. A: So, Here's how I just figured it out- i moved the ugly pickle stuff (see comment) to the unpickling class, imported the classes I was pickling, and it seems like it works.
Unpickling a Python class
I have a problem trying to unpickle subclasses of this class. When I unpickle it, the stuff isn't there. What gives? class Account: def __init__(self, server, port, smtp_server, smtp_port): self.server = server self.port = port self.smtp_server = smtp_server self.smtp_port = smtp_port self.save() def save(self): #save account for later loading self.name = tkFileDialog.asksaveasfilename(title = "Save as..") pickle.dump(self, open(self.name, "wr"))
[ "Does your class inherit object?\nEither way, you can specify what you want to pickle by overwriting __getstate__. Otherwise it should normally copy __dict__ if you're inheriting object.\n", "So, Here's how I just figured it out- i moved the ugly pickle stuff (see comment) to the unpickling class, imported the cl...
[ 1, 0 ]
[]
[]
[ "class", "pickle", "python" ]
stackoverflow_0003265454_class_pickle_python.txt
Q: how to write a program to validate another program/script? How to write a program to test another program/script? I need to test a ruby script that is an echo server; how should I write a program to validate the correct working of the echo server script ? A: You might be interested in Expect and dejaGnu. A: You could start with something like this for a TCP echo server: require "socket" hostname = "localhost" port = 2000 s = TCPSocket.open(hostname, port) s.print "something\n" # was "something" line = s.gets line.chop! if line == "something" puts "echo test passed" else puts "echo test failed: rcvd [#{line}]\n" end s.close Depending of what kind of testing you need, you can grow the test client, use several sockets, multiple threads, a test framework such as Test::Unit, Cucumber ... EDIT: it works with the following echo server, I just had to add a '\n' to the client data require 'socket' port = 2000 server = TCPServer.open(port) loop { client = server.accept data = client.gets client.puts data client.close } A: Ruby has a built-in unit testing framework called Test::Unit. However, I tend to prefer working with the Rspec BDD framework. Ideally, BDDers like to write the tests before the actual code, but you can certainly write tests after the fact.
how to write a program to validate another program/script?
How to write a program to test another program/script? I need to test a ruby script that is an echo server; how should I write a program to validate the correct working of the echo server script ?
[ "You might be interested in Expect and dejaGnu.\n", "You could start with something like this for a TCP echo server:\nrequire \"socket\"\n\nhostname = \"localhost\"\nport = 2000\n\ns = TCPSocket.open(hostname, port)\n\ns.print \"something\\n\" # was \"something\"\n\nline = s.gets\nline.chop!\n\nif line == \"s...
[ 1, 1, 0 ]
[]
[]
[ "python", "ruby", "testing", "validation" ]
stackoverflow_0003263663_python_ruby_testing_validation.txt
Q: importing from parent directory I have this kind of path architecture : >main_path/ __init__.py config/ __init__.py common.py app_1/ __init__.py config.py index.py > I'd like to be able to do so in config.py : >from main_path.config import common > Though it does not work. Python tells me : > $> pwd ..../main_path/app_1 $> python index.py [...] ImportError: No module named main_path.config > As far as I understand, this would be possible if i loaded everything up from the main_path, though the aim is to have multiple apps with a common config file. I tried to add the parent directory to the __path__ in the app_1/__init__.py but it changed nothing. My next move would be to have a symbolic link, though I don't really like this "solution", so if you have any idea to help me out, this would be much appreciated ! Thanks in advance ! A: According to the Modules documentation a module has to be in your PYTHONPATH environment variable to be imported. You can modify this within your program with something like: import sys sys.path.append('PATH_TO/config') import common For more information, you may want to see Modifying Python's Search Path in Installing Python Modules. A: If you want to modify python's search path without having to set PYTHONPATH each time, you can add a path configuration file (.pth file) to a directory that is already on the python path. This document describes it in detail: http://docs.python.org/install/#inst-search-path The most convenient way is to add a path configuration file to a directory that’s already on Python’s path, usually to the .../site-packages/ directory. Path configuration files have an extension of .pth, and each line must contain a single path that will be appended to sys.path. A: You can tweak your PYTHONPATH environment variable or edit sys.path.
importing from parent directory
I have this kind of path architecture : >main_path/ __init__.py config/ __init__.py common.py app_1/ __init__.py config.py index.py > I'd like to be able to do so in config.py : >from main_path.config import common > Though it does not work. Python tells me : > $> pwd ..../main_path/app_1 $> python index.py [...] ImportError: No module named main_path.config > As far as I understand, this would be possible if i loaded everything up from the main_path, though the aim is to have multiple apps with a common config file. I tried to add the parent directory to the __path__ in the app_1/__init__.py but it changed nothing. My next move would be to have a symbolic link, though I don't really like this "solution", so if you have any idea to help me out, this would be much appreciated ! Thanks in advance !
[ "According to the Modules documentation a module has to be in your PYTHONPATH environment variable to be imported. You can modify this within your program with something like:\nimport sys\nsys.path.append('PATH_TO/config')\nimport common\n\nFor more information, you may want to see Modifying Python's Search Path i...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003265631_python.txt
Q: Dynamically add instance variables via decorator to a class in Python I want to instrument a class via a decorator, to add some instance variables that are specified by the author of the class. I started with the following code, but this just adds class variables and I want instance variables (those that are normally 'declared' in __ init __) What is a pythonic way to do this, while allowing the class author control over what they put in __ init __? def add_list_attributes(klass): for attribute in klass.list_attributes: setattr(klass, attribute, []) return klass @add_list_attributes class Person(object): list_attributes = [ 'phone_numbers' ] def __init__(self): pass p1 = Person() p1.phone_numbers.append('01234') print p1.phone_numbers A: You would have to wrap __init__() in a separate function that would call the original method, then add its own attributes to the first argument. A: You can do this by wrapping the __init__ method to do your bidding, and then call the original __init__: def add_list_attributes(klass): old_init = klass.__init__ def new_init(self, *args, **kwargs): for attribute in klass.list_attributes: setattr(self, attribute, []) old_init(self, *args, **kwargs) klass.__init__ = new_init return klass @add_list_attributes class Person(object): list_attributes = [ 'phone_numbers' ] def __init__(self): pass p1 = Person() p1.phone_numbers.append('01234') p2 = Person() p2.phone_numbers.append('56789') print p1.phone_numbers print p2.phone_numbers A: You can create a custom __new__ method: def add_list_attributes(klass): def new(cls, *args, **kwargs): result = super(cls, cls).__new__(cls) for attribute in klass.list_attributes: setattr(result, attribute, []) return result klass.__new__ = staticmethod(new) return klass @add_list_attributes class Person(object): list_attributes = [ 'phone_numbers' ] def __init__(self): pass p1 = Person() p2 = Person() p1.phone_numbers.append('01234') print p1.phone_numbers, p2.phone_numbers
Dynamically add instance variables via decorator to a class in Python
I want to instrument a class via a decorator, to add some instance variables that are specified by the author of the class. I started with the following code, but this just adds class variables and I want instance variables (those that are normally 'declared' in __ init __) What is a pythonic way to do this, while allowing the class author control over what they put in __ init __? def add_list_attributes(klass): for attribute in klass.list_attributes: setattr(klass, attribute, []) return klass @add_list_attributes class Person(object): list_attributes = [ 'phone_numbers' ] def __init__(self): pass p1 = Person() p1.phone_numbers.append('01234') print p1.phone_numbers
[ "You would have to wrap __init__() in a separate function that would call the original method, then add its own attributes to the first argument.\n", "You can do this by wrapping the __init__ method to do your bidding, and then call the original __init__:\ndef add_list_attributes(klass):\n old_init = klass.__i...
[ 2, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003265770_python.txt
Q: Making a LazilyEvaluatedConstantProperty class in Python There's a little thing I want to do in Python, similar to the built-in property, that I'm not sure how to do. I call this class LazilyEvaluatedConstantProperty. It is intended for properties that should be calculated only once and do not change, but they should be created lazily rather than on object creation, for performance. Here's the usage: class MyObject(object): # ... Regular definitions here def _get_personality(self): # Time consuming process that creates a personality for this object. print('Calculating personality...') time.sleep(5) return 'Nice person' personality = LazilyEvaluatedConstantProperty(_get_personality) You can see that the usage is similar to property, except there's only a getter, and no setter or deleter. The intention is that on the first access to my_object.personality, the _get_personality method will be called, and then the result will be cached and _get_personality will never be called again for this object. What is my problem with implementing this? I want to do something a bit tricky to improve performance: I want that after the first access and _get_personality call, personality will become a data attribute of the object, so lookup will be faster on subsequent calls. But I don't know how it's possible since I don't have a reference to the object. Does anyone have an idea? A: I implemented it: class CachedProperty(object): ''' A property that is calculated (a) lazily and (b) only once for an object. Usage: class MyObject(object): # ... Regular definitions here def _get_personality(self): print('Calculating personality...') time.sleep(5) # Time consuming process that creates personality return 'Nice person' personality = CachedProperty(_get_personality) ''' def __init__(self, getter, name=None): ''' Construct the cached property. You may optionally pass in the name that this property has in the class; This will save a bit of processing later. ''' self.getter = getter self.our_name = name def __get__(self, obj, our_type=None): if obj is None: # We're being accessed from the class itself, not from an object return self value = self.getter(obj) if not self.our_name: if not our_type: our_type = type(obj) (self.our_name,) = (key for (key, value) in vars(our_type).iteritems() if value is self) setattr(obj, self.our_name, value) return value For the future, the maintained implementation could probably be found here: https://github.com/cool-RR/GarlicSim/blob/master/garlicsim/garlicsim/general_misc/caching/cached_property.py
Making a LazilyEvaluatedConstantProperty class in Python
There's a little thing I want to do in Python, similar to the built-in property, that I'm not sure how to do. I call this class LazilyEvaluatedConstantProperty. It is intended for properties that should be calculated only once and do not change, but they should be created lazily rather than on object creation, for performance. Here's the usage: class MyObject(object): # ... Regular definitions here def _get_personality(self): # Time consuming process that creates a personality for this object. print('Calculating personality...') time.sleep(5) return 'Nice person' personality = LazilyEvaluatedConstantProperty(_get_personality) You can see that the usage is similar to property, except there's only a getter, and no setter or deleter. The intention is that on the first access to my_object.personality, the _get_personality method will be called, and then the result will be cached and _get_personality will never be called again for this object. What is my problem with implementing this? I want to do something a bit tricky to improve performance: I want that after the first access and _get_personality call, personality will become a data attribute of the object, so lookup will be faster on subsequent calls. But I don't know how it's possible since I don't have a reference to the object. Does anyone have an idea?
[ "I implemented it:\nclass CachedProperty(object):\n '''\n A property that is calculated (a) lazily and (b) only once for an object.\n\n Usage:\n\n class MyObject(object):\n\n # ... Regular definitions here\n\n def _get_personality(self):\n print('Calculating pers...
[ 1 ]
[]
[]
[ "attributes", "properties", "python" ]
stackoverflow_0003265221_attributes_properties_python.txt
Q: Validation on ManyToManyField before Save in Models.py I have the following models: class Application(models.Model): users = models.ManyToManyField(User, through='Permission') folder = models.ForeignKey(Folder) class Folder(models.Model): company = models.ManyToManyField(Compnay) class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile') company = models.ManyToManyField(Company) What I would like to do is to check whether one of the users of the Application has the same company as the Application (via Folder). If this is the case the Application instance should not be saved. The problem is that the ManyToManyFields aren't updated until after the 'post-save' signal. The only option seems to be the new m2m_changed signal. But I'm not sure how I then roll back the save that has already happened. Another option would be to rewrite the save function (in models.py, because I'm talking about the admin here), but I'm not sure how I could access the manytomanyfield content. Finally I've read something about rewriting the save function in the admin of the model in admin.py, however I still wouldn't know how you would access the manytomanyfield content. I have been searching for this everywhere but nothing I come across seems to work for me. If anything is unclear, please tell me. Thanks for your help! Heleen A: Because I didn't get a reply from Botondus I decided to ask a new question in the Django Users Google Group and finally got the answer from jaymz. I figured that Botondus method was the right way of doing it, it just wasn't quite working. The reason that it doesn't work in this case is because I'm using a Through model for the field I would like to do the validation on. Because of some earlier feedback I got on a previously posted question I gathered that first the Application instance is saved and then the ManyToMany instances are saved (I believe this is right, but correct me if I'm wrong). So I thought that, if I would perform the validation on the ManyToMany Field in the Through model, this would not prevent the Application instance being saved. But in fact it does prevent that from happening. So if you have a ManyToMany Field inline in your model's admin and you would like to do validation on that field, you specify the clean function in the through model, like this: admin.py class PermissionInline(admin.TabularInline): form = PermissionForm model = Permission extra = 3 forms.py class PermissionForm(forms.ModelForm): class Meta: model = Permission def clean(self): cleaned_data = self.cleaned_data user = cleaned_data['user'] role = cleaned_data['role'] if role.id != 1: folder = cleaned_data['application'].folder if len(filter(lambda x:x in user.profile.company.all(),folder.company.all())) > 0: # this is an intersection raise forms.ValidationError("One of the users of this Application works for one of the Repository's organisations!") return cleaned_data If the validation results in an error NOTHING (neither the application instance, nor the manytomany users instances) is saved and you get the chance to correct the error. A: forms.py class ApplicationForm(ModelForm): class Meta: model = Application def clean(self): cleaned_data = self.cleaned_data users = cleaned_data['users'] folder = cleaned_data['folder'] if users.filter(profile__company__in=folder.company.all()).count() > 0: raise forms.ValidationError('One of the users of this Application works in one of the Folder companies!') return cleaned_data admin.py class ApplicationAdmin(ModelAdmin): form = ApplicationForm Edit: Replaced initial (wrong) model validation example with form validation.
Validation on ManyToManyField before Save in Models.py
I have the following models: class Application(models.Model): users = models.ManyToManyField(User, through='Permission') folder = models.ForeignKey(Folder) class Folder(models.Model): company = models.ManyToManyField(Compnay) class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile') company = models.ManyToManyField(Company) What I would like to do is to check whether one of the users of the Application has the same company as the Application (via Folder). If this is the case the Application instance should not be saved. The problem is that the ManyToManyFields aren't updated until after the 'post-save' signal. The only option seems to be the new m2m_changed signal. But I'm not sure how I then roll back the save that has already happened. Another option would be to rewrite the save function (in models.py, because I'm talking about the admin here), but I'm not sure how I could access the manytomanyfield content. Finally I've read something about rewriting the save function in the admin of the model in admin.py, however I still wouldn't know how you would access the manytomanyfield content. I have been searching for this everywhere but nothing I come across seems to work for me. If anything is unclear, please tell me. Thanks for your help! Heleen
[ "Because I didn't get a reply from Botondus I decided to ask a new question in the Django Users Google Group and finally got the answer from jaymz.\nI figured that Botondus method was the right way of doing it, it just wasn't quite working. The reason that it doesn't work in this case is because I'm using a Through...
[ 1, 0 ]
[]
[]
[ "admin", "django", "python", "validation" ]
stackoverflow_0003052427_admin_django_python_validation.txt
Q: GAE is any good ? if yes then JAVA or Python? Basically I am coding websites in PHP from last year. But now I want to use something else and GAE looks a good option. So I want to know if GAE is good for making a little website to share favorite youtube videos ? I have done single website in Python+Django few months back, it looks good to me. But JAVA is the language that I want to learn too (never coded in JAVA since School days ). Phew, it is hard to choose, so I need opinions !! Specifically : Want to know if any glitch/problem in using either python or Java under GAE. Or if GAE is preferred or not. Not gonna make website for learning only, it will be for a client. A: Java and Python are both excellent languages. It is a matter of taste and believe which you choose. If you prefer a lightweight solution, use Python. If you have enterprise needs, whatever that means, use Java. If you ask for my personal believe, my subjective stand-of-point is: Use Python wherever possible and stick to other languages if there is a need to. So this is my opinion, but as S.Lott commented on your question: Opinions are going to be useless. A: Most people here are missing the fact that the question is really about App Engine, not java or python in general. The Java and Python SDKs and App Engine runtimes have pretty much the same abilities at this point. One caveat with the current java runtime is that if you use a lot of external libraries, your loading hits (the first time someone hits your website, and app engine has to spin up your app) can be a bit slow. A: If you want to learn Java, then use Java! If you feel that Java is too verbose compared to Python, you could try Scala, which runs on the JVM like Java. Scala is more concise and well designed. A: You'll be able to accomplish the exact same results using either Python or Java. Java is much more verbose than Python, which can make it have a bit of a steeper learning curve. The fact that you have some experience in Django (which GAE's webapp is largely based on and which you can even use directly if you want) will make it easier for you to get the website up and running in the immediate term. So again, it does depend on what you want to accomplish. If your goal is to learn Java, then doing a project in Java is the best way to learn it. If your main goal is to get the site up and running, Python will be a better choice as it will let you focus less on struggling with learning new Java syntax and more on simply getting the website off the ground. A: I would personally go with a Java based solution. If this is just a little website for yourself, then it would be a good idea to learn a new technology, in this case Java. Little projects like this are ideal for learning new technologies and seeing if they are suitable for you as a developer and other projects you may decide to do in the future A: You need an IRL mentor.
GAE is any good ? if yes then JAVA or Python?
Basically I am coding websites in PHP from last year. But now I want to use something else and GAE looks a good option. So I want to know if GAE is good for making a little website to share favorite youtube videos ? I have done single website in Python+Django few months back, it looks good to me. But JAVA is the language that I want to learn too (never coded in JAVA since School days ). Phew, it is hard to choose, so I need opinions !! Specifically : Want to know if any glitch/problem in using either python or Java under GAE. Or if GAE is preferred or not. Not gonna make website for learning only, it will be for a client.
[ "Java and Python are both excellent languages. It is a matter of taste and believe which you choose. \n\nIf you prefer a lightweight solution, use Python.\nIf you have enterprise needs, whatever that means, use Java.\n\nIf you ask for my personal believe, my subjective stand-of-point is:\n\nUse Python wherever poss...
[ 3, 3, 2, 2, 1, 1 ]
[]
[]
[ "google_app_engine", "java", "python" ]
stackoverflow_0003263847_google_app_engine_java_python.txt
Q: Get thumbnail image for Yahoo video? (python) The question has a similar intent as this question: Get img thumbnails from Vimeo? but that one was for vimeo. So, I have a url for the yahoo video, is there any way I could get the standard thumbnail using the url? Thanks A: Well, Yahoo supports oembed. So, you can take the video url e.g., http://video.yahoo.com/watch/5202550/13742849 and pass it on to their oembed service like this: http://video.yahoo.com/services/oembed?url=http://video.yahoo.com/watch/5202550/13742849 The response to that will contain the thumbnail image url.
Get thumbnail image for Yahoo video? (python)
The question has a similar intent as this question: Get img thumbnails from Vimeo? but that one was for vimeo. So, I have a url for the yahoo video, is there any way I could get the standard thumbnail using the url? Thanks
[ "Well, Yahoo supports oembed. So, you can take the video url e.g., \nhttp://video.yahoo.com/watch/5202550/13742849 and pass it on to their oembed service like this:\nhttp://video.yahoo.com/services/oembed?url=http://video.yahoo.com/watch/5202550/13742849\nThe response to that will contain the thumbnail image url.\n...
[ 1 ]
[]
[]
[ "python", "video", "yahoo" ]
stackoverflow_0003262532_python_video_yahoo.txt