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: Trouble porting a function in Python to C using the Python C API I have a checksum function in Python: def checksum(data): a = b = 0 l = len(data) for i in range(l): a += ord(data[i]) b += (l - i)*ord(data[i]) return (b << 16) | a, a, b that I am trying to port to a C module for s...
Trouble porting a function in Python to C using the Python C API
I have a checksum function in Python: def checksum(data): a = b = 0 l = len(data) for i in range(l): a += ord(data[i]) b += (l - i)*ord(data[i]) return (b << 16) | a, a, b that I am trying to port to a C module for speed. Here's the C function: static PyObject * checksum(PyObject *self...
[ "I would guess that you have some kind of overflow in your local variables. Probably b gets to large. Just dump the values for debugging purposes and you should see if it's the problem. As you mention, that you are porting the method for performance reasons. Have you checked psyco? Might be fast enough and much eas...
[ 1, 1 ]
[]
[]
[ "algorithm", "checksum", "python" ]
stackoverflow_0004700725_algorithm_checksum_python.txt
Q: "Operation not permitted" while dropping privileges using setuid() function Why this simple programs that use os.setuid()/gid() fails? Is written in python but I think that is not a language relative problem (at the end are all the same posix system call): import os, pwd if os.getenv("SUDO_UID") and os.getenv("SU...
"Operation not permitted" while dropping privileges using setuid() function
Why this simple programs that use os.setuid()/gid() fails? Is written in python but I think that is not a language relative problem (at the end are all the same posix system call): import os, pwd if os.getenv("SUDO_UID") and os.getenv("SUDO_GID"): orig_uid=int(os.getenv("SUDO_UID")) orig_gid=int(os.getenv("SUDO_GI...
[ "Only the superuser or processes with the CAP_SETGID capability are allowed to set the GID. After the setuid() call, the effective UID isn't 0 any more, so you are not allowed to call setgid(). Try to reorder the two calls.\n", "I've fixed using this library \nhttp://pypi.python.org/pypi/privilege/1.0\nThat sec...
[ 26, 2 ]
[]
[]
[ "operating_system", "privileges", "python", "setuid" ]
stackoverflow_0004692720_operating_system_privileges_python_setuid.txt
Q: SQLAlchemy: Passing a Parameter to Object I am using SQLAlchemy in my project. I have two classes, call them Bar and Foo class Bar(object): def valueize(self, name): # do some crazy magic return value class Foo(Base): id = Column(... name = Column(... @property def value(self): ...
SQLAlchemy: Passing a Parameter to Object
I am using SQLAlchemy in my project. I have two classes, call them Bar and Foo class Bar(object): def valueize(self, name): # do some crazy magic return value class Foo(Base): id = Column(... name = Column(... @property def value(self): return self._bar.valueize(self.name) F...
[ "If you only need one Bar for all Foos, you can use a class property or method in Foo. Since you haven't taken this obvious path, you seem to need to construct a new Bar for every new Foo. Probably instrumentation has the needed events. The caching example has to have a way to intercept load events.\n" ]
[ 0 ]
[]
[]
[ "dependency_injection", "python", "sqlalchemy" ]
stackoverflow_0004700363_dependency_injection_python_sqlalchemy.txt
Q: Callback functions in field in Python ctypes I am trying to register callback functions for .dll library in Python with ctypes. But it requires callback functions in structure/field. Because it doesn't work (no errors but callback functions are doing nothing) I suppose I am wrong. Could someone, please, help me? ...
Callback functions in field in Python ctypes
I am trying to register callback functions for .dll library in Python with ctypes. But it requires callback functions in structure/field. Because it doesn't work (no errors but callback functions are doing nothing) I suppose I am wrong. Could someone, please, help me? There is a code hopefully explaining what I am try...
[ "You have to initialize tHandlerStructure:\nstHandlerStructure = tHandlerStructure(OnFirst,OnSecond)\n\nThere are other syntax errors in your code. It is best to cut-and-paste the code giving you an error, and provide the tracebacks as well. Below works:\nfrom ctypes import *\n\nfirsttype = CFUNCTYPE(c_void_p, c_...
[ 1, 0 ]
[]
[]
[ "callback", "ctypes", "field", "python" ]
stackoverflow_0004691867_callback_ctypes_field_python.txt
Q: python - returns incorrect positive # what i'm trying to do is write a quadratic equation solver but when the solution should be -1, as in quadratic(2, 4, 2) it returns 1 what am i doing wrong? #!/usr/bin/python import math def quadratic(a, b, c): #a = raw_input("What\'s your `a` value?\t") #b = r...
python - returns incorrect positive #
what i'm trying to do is write a quadratic equation solver but when the solution should be -1, as in quadratic(2, 4, 2) it returns 1 what am i doing wrong? #!/usr/bin/python import math def quadratic(a, b, c): #a = raw_input("What\'s your `a` value?\t") #b = raw_input("What\'s your `b` value?\t") ...
[ "Unless the formula has changed since I went to school (one can never be too sure), it's (-b +- sqrt(b^2-4ac)) / 2a, you have b in your code.\n[edit] May I suggest a refactor?\ndef quadratic(a, b, c):\n discriminant = b**2 - 4*a*c\n if discriminant < 0:\n return []\n elif discriminant == 0:\n ret...
[ 12, 2, 1, 0 ]
[]
[]
[ "function", "math", "module", "python", "quadratic" ]
stackoverflow_0004701383_function_math_module_python_quadratic.txt
Q: Pass one parameter in a Tornado HttpGet with several parameters I want pass one parameter in a Url (to update one of many paramaters contained by my URL) like this: httpGet.setURI(new URI(url/user?"nickname"="John") ServerSide in Python: class GetInfo(BaseHandler): def Get(self): nickname = self.get_ar...
Pass one parameter in a Tornado HttpGet with several parameters
I want pass one parameter in a Url (to update one of many paramaters contained by my URL) like this: httpGet.setURI(new URI(url/user?"nickname"="John") ServerSide in Python: class GetInfo(BaseHandler): def Get(self): nickname = self.get_argument("nickname") gender = self.get_argument("gender") ...
[ "First your URI seems to be wrong.\nhttpGet.setURI(new URI(url + \"/user?nickname=John\") \n\nAnd if you test from emulator to webserver and you use both on the same machine, use the IP address of the server instead of something like localhost or 127.0.0.1\nExample:\nString url = \"http://192.168.1.104\";\nhttpGet....
[ 2 ]
[]
[]
[ "android", "http_get", "http_post", "python", "tornado" ]
stackoverflow_0004701365_android_http_get_http_post_python_tornado.txt
Q: How to implement a Mutex in Python when using Gtk with PyGTK I have an application that starts several threads using gobject.timeout_add(delay, function) Now in my function I want to test and set on some variable, e.g. def function(self): if flag == True: flag = False doSomething() Now to mak...
How to implement a Mutex in Python when using Gtk with PyGTK
I have an application that starts several threads using gobject.timeout_add(delay, function) Now in my function I want to test and set on some variable, e.g. def function(self): if flag == True: flag = False doSomething() Now to make this threadsafe, I would have to lock the function using some mu...
[ "I just found out that gobject.timeout_add(delay, function) and gobject.idle_add(function) are safe to use. I tried it using\nfor i in range(X):\n gobject.idle_add(workerFunction)\n\nand found out that there are NEVER two worker threads executing at the same time. That means it seems like the function calls perf...
[ 0 ]
[]
[]
[ "gtk", "multithreading", "mutex", "pygtk", "python" ]
stackoverflow_0004699573_gtk_multithreading_mutex_pygtk_python.txt
Q: Get the currently used url when an on the template in django for us in a breadcrumb? I have an app which serves two purposes - displays members and centres of my company. They both work exactly the same, save a different variable when filtering my model. Problem is I can't get the current url onto the template to ...
Get the currently used url when an on the template in django for us in a breadcrumb?
I have an app which serves two purposes - displays members and centres of my company. They both work exactly the same, save a different variable when filtering my model. Problem is I can't get the current url onto the template to use in my custom breadcrumbs. I have this urlpattern in my main urls.py: # --- urls.py --...
[ "You don't need to use a function. Your view is passed the request object, which has an attribute path which is the path that was called. See the request docs.\n" ]
[ 3 ]
[]
[]
[ "django", "django_templates", "python", "urlconf" ]
stackoverflow_0004700660_django_django_templates_python_urlconf.txt
Q: python timed execution of code I want to execute a piece of my code in exactly the same time every time I execute it, somewhat like playing a media file... (the same piece of code is executed in exactly the same amount of time every time) Is this possible in python? A: This should do the trick: def run_with_del...
python timed execution of code
I want to execute a piece of my code in exactly the same time every time I execute it, somewhat like playing a media file... (the same piece of code is executed in exactly the same amount of time every time) Is this possible in python?
[ "This should do the trick:\ndef run_with_delay(funcs, interval):\n for f in funcs[:-1]:\n before = time()\n f()\n # compensate the interval with the execution time.\n # NB: careful for functions that have a greater\n # execution time than interval\n after = time()\n ...
[ 2, 1, 0 ]
[]
[]
[ "python", "timed_events" ]
stackoverflow_0004701576_python_timed_events.txt
Q: Problem with cyrillic symbols in console sorry for bad English. It's Ruby code. s = "мистика" `touch #{s}` `cat #{s}` `cat < #{s}` Can anybody tell why it's code fails? With sh: cannot open ми�тика: No such file But thic code works fine s = "работает" `touch #{s}` `cat #{s}` `cat < #{s}` Problem is o...
Problem with cyrillic symbols in console
sorry for bad English. It's Ruby code. s = "мистика" `touch #{s}` `cat #{s}` `cat < #{s}` Can anybody tell why it's code fails? With sh: cannot open ми�тика: No such file But thic code works fine s = "работает" `touch #{s}` `cat #{s}` `cat < #{s}` Problem is only when Russian symbol 'с' in the word and wi...
[ "This is a bug in dash, shell which Debian uses by default (symlink /bin/sh leads to /bin/dash; and python's os.system uses sh. Ruby probably uses sh too). dash cannot properly parse 8-bit text, including UTF-8. To workaround your problem, replace it by bash:\nsudo dpkg-reconfigure dash\n\nand select \"No\". This w...
[ 1, 0, 0 ]
[ "use ruby 1.9 it has force_encoding methods in String object\n" ]
[ -2 ]
[ "bash", "python", "ruby", "ubuntu" ]
stackoverflow_0004546285_bash_python_ruby_ubuntu.txt
Q: How to install django? I have installed python 2.7 and ran the setup.py it executed various commands on command prompt but how can i see tha face of django i don't know what next step is. Whether i should have to set the path or not and how can i start the framework after setting the path. Thanks in advance. A: ...
How to install django?
I have installed python 2.7 and ran the setup.py it executed various commands on command prompt but how can i see tha face of django i don't know what next step is. Whether i should have to set the path or not and how can i start the framework after setting the path. Thanks in advance.
[ "For installing django you should use python setup.py install\nAfter it if you're using Windows you should add django-admin.py to your system path. On Linux this is done automatically. (You may choose not to do this if you don't want, but then you have to specify path to django-admin.py everytime you use it.)\nWhen...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004701671_python.txt
Q: Python imports confusion I've got a strange issue with importing a module. I've got a virtualenv setup and one module is available in {env}/lib/python2.6/site-packages/pkgname. There is a __init__.py file and pkgname.py inside. Now, if I run {env}/bin/python and execute import pkgname.pkgname, it works just fine. ...
Python imports confusion
I've got a strange issue with importing a module. I've got a virtualenv setup and one module is available in {env}/lib/python2.6/site-packages/pkgname. There is a __init__.py file and pkgname.py inside. Now, if I run {env}/bin/python and execute import pkgname.pkgname, it works just fine. But if I create a script in {e...
[ "Call it pkgname. Done. OK, then it won't start if you doubleclick in it WIndows, but that's usually not a problem.\n", "You can modify sys.path. It's just a list of paths to search and the current folder should be the first entry. Your file should run if you move the current folder to the end of the list. But I ...
[ 2, 0 ]
[]
[]
[ "import", "package", "python" ]
stackoverflow_0004701714_import_package_python.txt
Q: What's the best way to implement a Live chat system on my webserver? I'm interested in something based on Jabber but I didn't find a free/opensource one so I'm thinking of writing one. I've installed a Jabber server and now thinking about the ways in which I can write the client. I'm thinking of one of either thes...
What's the best way to implement a Live chat system on my webserver?
I'm interested in something based on Jabber but I didn't find a free/opensource one so I'm thinking of writing one. I've installed a Jabber server and now thinking about the ways in which I can write the client. I'm thinking of one of either these two methods. 1) An ajax call made to a jabber script running on the webs...
[ "Jabber is usually called XMPP nowadays, and there are dozens of clients and servers, something for every language. If you are using Javascript (you mention Ajax), you probably want Strophe. Most servers are modular, so you only load the features you need (consider Tigase, ejabberd, or xmpppy). Writing your own ...
[ 3, 1 ]
[]
[]
[ "perl", "python", "xmpp" ]
stackoverflow_0004701232_perl_python_xmpp.txt
Q: subversion post commit hooks I've got a situation where I'm contemplating using subversion/svn as the repository/version control system for a project. I'm trying to figure out if it's possible, (and if so, how) to be able to have the subversion system, on a post commit hook/process to to write the user/file/time (...
subversion post commit hooks
I've got a situation where I'm contemplating using subversion/svn as the repository/version control system for a project. I'm trying to figure out if it's possible, (and if so, how) to be able to have the subversion system, on a post commit hook/process to to write the user/file/time (and maybe msg) to either an extern...
[ "Indeed it is very possible, in your repository root there should be a folder named hooks, inside which should be a file named post-commit (if not, create one), add whatever bash code you put there and it will execute after every commit.\nNote, there are 2 variables that are passed into the script $1 is the reposit...
[ 0, 0 ]
[]
[]
[ "hook", "php", "python", "svn", "svn_hooks" ]
stackoverflow_0004701902_hook_php_python_svn_svn_hooks.txt
Q: Recursively show all differences between two Python lists In Python, I have an application that writes a list to a CSV file, but it has to be almost absolutely sure that the write occurred with no errors or mistakes. The latter is important because although it does catch exceptions from the writer and then the rea...
Recursively show all differences between two Python lists
In Python, I have an application that writes a list to a CSV file, but it has to be almost absolutely sure that the write occurred with no errors or mistakes. The latter is important because although it does catch exceptions from the writer and then the reader, a mistake could happen and the result data be different th...
[ "Use difflib from Python's standard library. Pulling one of several examples directly from the documentation:\n>>> s1 = ['bacon\\n', 'eggs\\n', 'ham\\n', 'guido\\n']\n>>> s2 = ['python\\n', 'eggy\\n', 'hamster\\n', 'guido\\n']\n>>> for line in context_diff(s1, s2, fromfile='before.py', tofile='after.py'):\n... ...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0004700369_python.txt
Q: Django model field choices - wouldn't a dict be better? Given a field; domain_status_choices = ( (1,'Live') (2,'Offline') (3,'Dev') ) status = models.SmallIntegerField( choices=domain_status_choices ) I know I can get and set numeric representation and use get_status_display() to get the text label. B...
Django model field choices - wouldn't a dict be better?
Given a field; domain_status_choices = ( (1,'Live') (2,'Offline') (3,'Dev') ) status = models.SmallIntegerField( choices=domain_status_choices ) I know I can get and set numeric representation and use get_status_display() to get the text label. But if a user posts status=Offline how can I get the numeric v...
[ "I believe the keys of a dict are not guaranteed to be sorted (unless you use OrderedDict obviously). That is, you \"might\" get \"Offline\", \"Dev\", \"Live\" choices with your version.\nImplementation note on dict.items:\n\nKeys and values are listed in an arbitrary order which is non-random, varies across Python...
[ 14, 3 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0004698972_django_django_models_python.txt
Q: Django Serialization of DateTime Objects within Dictionary My Django view method is below. I want to pass place_data as a response from an HTTPRequest (within a getJSON call on the client side, but that's irrelevant to the issue). I can pass the dictionary fine until I include the event_occurrences, which is doi...
Django Serialization of DateTime Objects within Dictionary
My Django view method is below. I want to pass place_data as a response from an HTTPRequest (within a getJSON call on the client side, but that's irrelevant to the issue). I can pass the dictionary fine until I include the event_occurrences, which is doing some behind the scenes work to pass a dictionary of events wi...
[ "Django's serialization framework is for QuerySets, not dicts. If you want to just dump a dictionary to JSON, just use json.dumps. It can easily be made to serialize objects by passing in a custom serialization class - there's one included with Django that deals with datetimes already:\nfrom django.core.serializers...
[ 29 ]
[]
[]
[ "datetime", "django", "python", "serialization" ]
stackoverflow_0004702044_datetime_django_python_serialization.txt
Q: SCons Regexp Instead of Glob? Is there an SCons function the provides the functionality of Glob, but using Regular Expressions instead? A: You can use os.listdir() to get all the entries in a directory, and then filter those by regular expression: import os import re print([x for x in os.listdir(".") if re.matc...
SCons Regexp Instead of Glob?
Is there an SCons function the provides the functionality of Glob, but using Regular Expressions instead?
[ "You can use os.listdir() to get all the entries in a directory, and then filter those by regular expression:\nimport os\nimport re\n\nprint([x for x in os.listdir(\".\") if re.match(r\"[a-z]+[0-9]+\", x)])\n\n" ]
[ 2 ]
[]
[]
[ "filesystems", "python", "regex", "scons" ]
stackoverflow_0004702274_filesystems_python_regex_scons.txt
Q: Django: FieldError cannot resolve keyword '___' into a field I'm having a FieldError. I have a model: class Foo(models.Model): __bar = models.TextField(default=lambda: cPickle.dumps(set()), primary_key=True) def get_bar(self): return cPickle.loads(str(self.__bar)) def set_bar(self, values):...
Django: FieldError cannot resolve keyword '___' into a field
I'm having a FieldError. I have a model: class Foo(models.Model): __bar = models.TextField(default=lambda: cPickle.dumps(set()), primary_key=True) def get_bar(self): return cPickle.loads(str(self.__bar)) def set_bar(self, values): self.__bar = cPickle.dumps(values) bar = property(ge...
[ "Because you've prefixed __bar with two underscores, Python is performing name mangling (doc link) in an attempt to enforce private access to the variable. \nPrivate variables, of course, don't exist in Python, but by using the double-underscore convention you've asked Python to reformat __bar as _(classname)__bar,...
[ 5 ]
[]
[]
[ "database", "django", "django_admin", "python" ]
stackoverflow_0004702402_database_django_django_admin_python.txt
Q: Release resource being held by another process In SimPy, if I've process a, b and resource r and do: yield request, self, r #request done in process a How can I release the resource from process b? yield release, a, r #release done in b (being a an instance of class a), doesn't work I've also tried: r.activeQ.re...
Release resource being held by another process
In SimPy, if I've process a, b and resource r and do: yield request, self, r #request done in process a How can I release the resource from process b? yield release, a, r #release done in b (being a an instance of class a), doesn't work I've also tried: r.activeQ.remove(a) And it actually removes from the active que...
[ "Well, my problem was process b was actually inactive and therefore any yield call would be unsuccessful.\nA workaround I came up with was\nactivate(a, a.function()) #called from process b\n\nWhere\nclass a(Process):\n def function(self):\n yield release, self, r\n yield passivate, self\n\nHope thi...
[ 1 ]
[]
[]
[ "python", "simpy" ]
stackoverflow_0004701910_python_simpy.txt
Q: Python 3.1: Syntax Error for Everything! (Mac OS X) I updated to Python 3.1.3 (I've got OS X 10.6). If I type python in Terminal, I get a working 2.6.1 environment. If I type python3 in Terminal, I get a 3.1.3 environment. Everything looks fine until I do something. If I try to run print "hello", I get a syntax er...
Python 3.1: Syntax Error for Everything! (Mac OS X)
I updated to Python 3.1.3 (I've got OS X 10.6). If I type python in Terminal, I get a working 2.6.1 environment. If I type python3 in Terminal, I get a 3.1.3 environment. Everything looks fine until I do something. If I try to run print "hello", I get a syntax error. This problem is the same in IDLE. I tried deleting e...
[ "In Python 3.x, print is a function, so use\nprint(\"Hello\")\n\ninstead.\n", "In Python 3, you need to use Print as a function:\nprint(\"Hello\")\n\n" ]
[ 10, 8 ]
[]
[]
[ "macos", "python", "python_idle", "shell", "syntax_error" ]
stackoverflow_0004702556_macos_python_python_idle_shell_syntax_error.txt
Q: Copying a boost.python object I have some boost python classes, which I instantiate in python. I want to copy them. So, if I have p = Bernoulli(0.5) I want to do q = Bernoulli(p) But what if I don't know p's type? I tried to do this: q = copy.deepcopy(p) but python said it couldn't pickle p. Is my only solut...
Copying a boost.python object
I have some boost python classes, which I instantiate in python. I want to copy them. So, if I have p = Bernoulli(0.5) I want to do q = Bernoulli(p) But what if I don't know p's type? I tried to do this: q = copy.deepcopy(p) but python said it couldn't pickle p. Is my only solution to add a clone() function to th...
[ "From http://mail.python.org/pipermail/cplusplus-sig/2009-May/014505.html\n#define PYTHON_ERROR(TYPE, REASON) \\\n{ \\\n PyErr_SetString(TYPE, REASON); \\\n throw bp::error_already_set(); \\\n}\n\ntemplate<class T>\ninline PyObject * managingPyObject(T *p)\n{\n return typename bp::manage_new_object::apply<...
[ 4, 2, 1 ]
[]
[]
[ "boost_python", "python" ]
stackoverflow_0004696966_boost_python_python.txt
Q: How can I get all objects a user has specific permissions to in django guardian? I am currently doing a really clumsy loop over all the objects but that is going to get slow: videos = Video.objects.all() video_list = [] for video in videos: checker = ObjectPermissionChecker(request.user) if checker.has_per...
How can I get all objects a user has specific permissions to in django guardian?
I am currently doing a really clumsy loop over all the objects but that is going to get slow: videos = Video.objects.all() video_list = [] for video in videos: checker = ObjectPermissionChecker(request.user) if checker.has_perm('view_video', video): video_list.append(video) I figure there must be a way...
[ "a few days ago there were update with new shortcut function called \"get_objects_for_user\". If you use older version of guardian and cannot update, you can simply copy codes from there.\nfrom guardian.shortcuts import get_objects_for_user\n...\nvideos = get_objects_for_user(request.user, \"view_video\", Video.obj...
[ 10, 1, 1 ]
[]
[]
[ "django", "permissions", "python" ]
stackoverflow_0004663694_django_permissions_python.txt
Q: Start the correct python program via symbolic link I recently installed ActivePython 2.7. So I've got a symbolic link in /usr/local/bin/python which points to the 2.7 directory. Trouble is, when I type "python" at the command line, it starts up MacPython 2.6 in /usr/bin/python. I don't understand why the symbolic ...
Start the correct python program via symbolic link
I recently installed ActivePython 2.7. So I've got a symbolic link in /usr/local/bin/python which points to the 2.7 directory. Trouble is, when I type "python" at the command line, it starts up MacPython 2.6 in /usr/bin/python. I don't understand why the symbolic link is not taking precedence. /usr/local/bin is on my P...
[ "When you type “python” on the command line, the shell checks the values in your $PATH from left to right, and invokes the program it finds first. Check your current $PATH setting like this:\n$ echo $PATH\n\nIf it contains both /usr/bin and /usr/local/bin then whichever comes first will take precedence.\n", "in y...
[ 3, 2 ]
[]
[]
[ "activepython", "python", "symlink" ]
stackoverflow_0004702988_activepython_python_symlink.txt
Q: Python - Server and client problems I'm trying to create a basic server and client script. The idea is that the client can connect to the server and execute commands. Kinda like SSH but very simple. Heres my server code: import sys, os, socket host = '' port = 50103 s = socket.socket(socket.AF_INE...
Python - Server and client problems
I'm trying to create a basic server and client script. The idea is that the client can connect to the server and execute commands. Kinda like SSH but very simple. Heres my server code: import sys, os, socket host = '' port = 50103 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, por...
[ "When you makefile() on the socket and then use readlines() on it, it will continue until you reach an end of file, which in the socket case is that it closed from the other end.\nUsing makefile() in this case makes no sense to me, especially since you create it and close it after each command. Just use send() and ...
[ 2, 1 ]
[]
[]
[ "client", "connection", "python" ]
stackoverflow_0004703187_client_connection_python.txt
Q: How do I handle database ORM situations like this in Django? params['blog_posts'] = Content.objects.get(user = blah) params['other_vars'] = "other stuff" params['votes'] = 4245 if request.GET.get("format") == "json": response = json.dumps(params) return HttpResponse(response) else: return render_to_r...
How do I handle database ORM situations like this in Django?
params['blog_posts'] = Content.objects.get(user = blah) params['other_vars'] = "other stuff" params['votes'] = 4245 if request.GET.get("format") == "json": response = json.dumps(params) return HttpResponse(response) else: return render_to_response("posts.html", params, RequestContext(request)) In my temp...
[ "One option is to have your model class itself contain the knowledge of how to serialize itself:\nclass MyBaseModel(BaseModel):\n def serialize():\n abstract # this will throw an error if it's called without being overwritten\n\nclass Post(MyBaseModel):\n title = db.stringProperty()\n body = db.text...
[ 3 ]
[]
[]
[ "database", "django", "mysql", "python" ]
stackoverflow_0004703185_database_django_mysql_python.txt
Q: Scraping information from site using lxml I'm trying to grab a list of all titles from the site Reddit.com using lxml. I used this query: reddit = etree.HTML( urllib.urlopen("http://www.reddit.com/r/all/top").read() ) reddit.xpath("//div[contains(@class,'title')]//b/text()") However, when I run the expressio...
Scraping information from site using lxml
I'm trying to grab a list of all titles from the site Reddit.com using lxml. I used this query: reddit = etree.HTML( urllib.urlopen("http://www.reddit.com/r/all/top").read() ) reddit.xpath("//div[contains(@class,'title')]//b/text()") However, when I run the expression nothing comes up in the Python shell. Is the...
[ "Reddit has API. You don't need to scrape it. Just add '.json' at the end of the url:\n#!/usr/bin/env python\nimport json\nimport urllib2\n\nurl = \"http://www.reddit.com/r/all/top/.json\"\ndata = json.load(urllib2.urlopen(url))\nfor child in data['data']['children']:\n print child['data']['title']\n\nExample Ou...
[ 6, 2 ]
[]
[]
[ "html", "lxml", "parsing", "python", "screen_scraping" ]
stackoverflow_0004703052_html_lxml_parsing_python_screen_scraping.txt
Q: How to render a Google App Engine template? I know you can render a template by using something like: template_values = { 'contacts': contacts, 'url': url, 'url_linktext': url_linktext, } path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.out...
How to render a Google App Engine template?
I know you can render a template by using something like: template_values = { 'contacts': contacts, 'url': url, 'url_linktext': url_linktext, } path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.out.write(template.render(path, template_values)) M...
[ "the template.render accept 2 arguments , when there is no values to pass just use this {}\nso it will be template.render(templatefile , {})\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004703031_google_app_engine_python.txt
Q: Store comparison in variable (or execute comparison when it's given as an string) I'd like to know if the super-powerful python allows to store a comparison in a variable or, if not, if it's possible calling/executing a comparison when given as an string ("==" or "!=") I want to allow the users of my program the c...
Store comparison in variable (or execute comparison when it's given as an string)
I'd like to know if the super-powerful python allows to store a comparison in a variable or, if not, if it's possible calling/executing a comparison when given as an string ("==" or "!=") I want to allow the users of my program the chance of giving a comparison in an string. For instance, let's say I have a list of... ...
[ "I haven't used SQLAlchemy much, but I'd guess it uses Python's operator overloading to handle those comparisons. If that's true, then you can use the properties' magic methods. For example:\nProduct.manufacturer == 'bar' => Product.manufacturer.__eq__('bar')\nProduct.manufacturer != 'foo' => Product.manufacturer._...
[ 2 ]
[]
[]
[ "call", "python", "sqlalchemy" ]
stackoverflow_0004703279_call_python_sqlalchemy.txt
Q: Problems connecting to a server running on a (sometimes virtualized) Windows machine ***Sorry for using the Term Host & Guest I see that has confused things slightly. By Host I mean Client which listens on your desired port for incoming connections and by Guest I mean Server which attempts to retrieve the IP of yo...
Problems connecting to a server running on a (sometimes virtualized) Windows machine
***Sorry for using the Term Host & Guest I see that has confused things slightly. By Host I mean Client which listens on your desired port for incoming connections and by Guest I mean Server which attempts to retrieve the IP of your pre-defined Dyndns.org address. Then tries a connection. You may say that's 'backwards'...
[ "So maybe there is some windows limitations for listenings pors. As far as I remeber some Windows can have max 5 ports open for listening. But I don't remeber exacly.\n", "Sounds like a firewall problem. I would add either the port or python.exe to the approved list.\nAre any of the Windows machines joined to a...
[ 1, 0 ]
[]
[]
[ "python", "twisted", "virtualization", "windows" ]
stackoverflow_0004702422_python_twisted_virtualization_windows.txt
Q: Can't parse a table child with xpath I'm parsing a site with some messy html, they're 130 subsites and the only one that fails is the last one. The part in which fails is the bolded one. I get an empty list when I should be getting 3(parent and 2 childs). All sites have the same structure so I don't have a clue ho...
Can't parse a table child with xpath
I'm parsing a site with some messy html, they're 130 subsites and the only one that fails is the last one. The part in which fails is the bolded one. I get an empty list when I should be getting 3(parent and 2 childs). All sites have the same structure so I don't have a clue how to solve this. from lxml.html import par...
[ "According to validator.w3.org when pointed at http://www.whfoods.com/genpage.php?tname=foodspice&dbid=97:\nLine 253, column 147: non SGML character number 150\n\n …ed mushrooms by Liquid Chromatography Mass Spectroscopy. The 230th ACS Natio…\n\nThe problem character is between \"Chromatography\" and \"Mass\". Th...
[ 1 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0004702710_lxml_python.txt
Q: SQLAlchemy - loading user by username Just diving into pylons here, and am trying to get my head around the basics of SQLALchemy. I have figured out how to load a record by id: user_q = session.query(model.User) user = user_q.get(user_id) But how do I query by a specific field (i.e. username)? I assume there is...
SQLAlchemy - loading user by username
Just diving into pylons here, and am trying to get my head around the basics of SQLALchemy. I have figured out how to load a record by id: user_q = session.query(model.User) user = user_q.get(user_id) But how do I query by a specific field (i.e. username)? I assume there is a quick way to do it with the model rather...
[ "I believe you want something like this:\nuser = meta.Session.query(model.User).filter_by(name=user_name).first()\n\nWhich is short for this:\nuser = meta.Session.query(model.User).filter(model.User.name=user_name).first()\n\nHere's more documentation\nIf you change first() into one() it will raise an exception if ...
[ 4 ]
[]
[]
[ "pylons", "python", "sqlalchemy" ]
stackoverflow_0004703522_pylons_python_sqlalchemy.txt
Q: How to specify a condition on which to complete installation with python setuptools I'm trying to make a distributable egg with setuptools and my program depends on wget being present, which obviously isn't available in PyPi. I have a little script which checks for the presence of wget, asking the user to install...
How to specify a condition on which to complete installation with python setuptools
I'm trying to make a distributable egg with setuptools and my program depends on wget being present, which obviously isn't available in PyPi. I have a little script which checks for the presence of wget, asking the user to install it and returning -1 if it isn't installed, or returning 0 if it is installed. I'd like...
[ "Before you call the setup() method in your setup.py, you can check if the wget exists, if it does not, then you can exit with a note saying that you need wget as a dependency for your software.\nif __name__ == '__main__':\n\n # Check for wget\n if sys.platform == 'linux2' and not ((os.path.exists('/usr/bin/w...
[ 1, 0 ]
[]
[]
[ "external_dependencies", "python", "setuptools" ]
stackoverflow_0004512445_external_dependencies_python_setuptools.txt
Q: What can I use the Google App Engine for? This question possibly doesn't belong here. We'll see how the answers pan out, if this doesn't belong here please move it to where it belongs. I'm following the getting started guide for Google App Engine, and I'm seeing what it can and can't do. Basically, I'm seei...
What can I use the Google App Engine for?
This question possibly doesn't belong here. We'll see how the answers pan out, if this doesn't belong here please move it to where it belongs. I'm following the getting started guide for Google App Engine, and I'm seeing what it can and can't do. Basically, I'm seeing it's very similar to an MVC pattern. You c...
[ "Google App Engine isn't a framework. Google App Engine is platform as a service. The App Engine is a platform for developing applications where the server components are managed for you by Google so that you aren't distracted by the mundane details of configuring a server. It let's you focus on what you do best...
[ 11, 5, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004701139_google_app_engine_python.txt
Q: conditional iterators in Python: How can I pick out a particular iteration? In django templates I accomplish this with {% if forloop.first %} but im not sure how to do this in regular 'ole python without writing a clunky counter to count up as my conditional iterates. Is their an easy way out? A: Take a look at ...
conditional iterators in Python: How can I pick out a particular iteration?
In django templates I accomplish this with {% if forloop.first %} but im not sure how to do this in regular 'ole python without writing a clunky counter to count up as my conditional iterates. Is their an easy way out?
[ "Take a look at enumerate.\n\nReturn an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the corresponding value obtained from i...
[ 5 ]
[]
[]
[ "conditional_operator", "django", "iterator", "python" ]
stackoverflow_0004703879_conditional_operator_django_iterator_python.txt
Q: Mercurial API : repo.changectx(change) doesn't exist! i'm trying to make a Mercurial support plugin for a Python IDE and i have a lot of troubles understanding the API. Right now i'm only making experiments for understanding the uses of the different commands of the api, but i can't find the api's doc or anything ...
Mercurial API : repo.changectx(change) doesn't exist!
i'm trying to make a Mercurial support plugin for a Python IDE and i have a lot of troubles understanding the API. Right now i'm only making experiments for understanding the uses of the different commands of the api, but i can't find the api's doc or anything like it. My problem is that r.changectx doesn't work becaus...
[ "I think it needs a local repo for it to work like that. Also, you need a revision for changectx.\nfrom mercurial import ui, hg, commands\n\nmyui = ui.ui()\nrepourl = \"https://ninja-ide.googlecode.com/hg/\"\n\ncommands.clone(myui, repourl, 'ninja')\nr = hg.repository(myui, './ninja')\nc = r.changectx(\"tip\")\n\n#...
[ 3 ]
[]
[]
[ "mercurial", "mercurial_extension", "python" ]
stackoverflow_0004703067_mercurial_mercurial_extension_python.txt
Q: python-nose: assertion library? Is there a library which of nose-friendly assertions things like membership and identity (eg, assert_contains(x, y), assert_is(a, b))? A: Nose provides stand-alone versions of the stdlib assertions: from nose.tools import assert_in, assert_is For older Pythons, the unittest2 vers...
python-nose: assertion library?
Is there a library which of nose-friendly assertions things like membership and identity (eg, assert_contains(x, y), assert_is(a, b))?
[ "Nose provides stand-alone versions of the stdlib assertions:\nfrom nose.tools import assert_in, assert_is\n\nFor older Pythons, the unittest2 versions can likely be wrapped using a technique similar to what's in tools.py.\n", "Stdlib unittest provide both assertIn and assertIs and can be run via nose. Are you lo...
[ 10, 3 ]
[]
[]
[ "assertion", "nosetests", "python" ]
stackoverflow_0004703961_assertion_nosetests_python.txt
Q: Django Admin interface with pickled set I have a model that has a pickled set of strings. (It has to be pickled, because Django has no built in set field, right?) class Foo(models.Model): __bar = models.TextField(default=lambda: cPickle.dumps(set()), primary_key=True) def get_bar(self): return cP...
Django Admin interface with pickled set
I have a model that has a pickled set of strings. (It has to be pickled, because Django has no built in set field, right?) class Foo(models.Model): __bar = models.TextField(default=lambda: cPickle.dumps(set()), primary_key=True) def get_bar(self): return cPickle.loads(str(self.__bar)) def set_bar...
[ "Uhm. Django usually stores it's data in an SQL database. Storing a set as a pickled string is definietly not the best way to use an SQL database. It's not immediately obvious which is the right solution in your case, that depends what is in that set, but this is the wrong solution in any case.\nYou might want a ne...
[ 2 ]
[]
[]
[ "django", "django_admin", "python", "user_interface" ]
stackoverflow_0004703150_django_django_admin_python_user_interface.txt
Q: has Python 3 been widely adopted yet? I know that when it launched, a lot of people didn't think it would be picked up very easily. I was wondering if thats changed at all. Do many of the major modules and libraries support Python 3 yet? Is it gaining acceptance or are people mostly sticking with 2.x? A: If you ...
has Python 3 been widely adopted yet?
I know that when it launched, a lot of people didn't think it would be picked up very easily. I was wondering if thats changed at all. Do many of the major modules and libraries support Python 3 yet? Is it gaining acceptance or are people mostly sticking with 2.x?
[ "If you go to python.org and click on Download, there's this message:\n\nIf you don't know which version to use, start with Python 2.7; more existing third party software is compatible with Python 2 than Python 3 right now.\n\nI think that's the case. Python 2 is still more useful.\nExample: you don't have WSGI wor...
[ 11, 8 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0004693352_python_python_3.x.txt
Q: Should I be using abstract methods in this Python scenario? I'm not sure my approach is good design and I'm hoping I can get a tip. I'm thinking somewhere along the lines of an abstract method, but in this case I want the method to be optional. This is how I'm doing it now... from pymel.core import * class A(obje...
Should I be using abstract methods in this Python scenario?
I'm not sure my approach is good design and I'm hoping I can get a tip. I'm thinking somewhere along the lines of an abstract method, but in this case I want the method to be optional. This is how I'm doing it now... from pymel.core import * class A(object): def __init__(self, *args, **kwargs): if callable...
[ "You still have a problem, when you will inherit your class B, and this will call A.__init__ and if you don't implement createDrivers in the subclass this line callable(self.createDrivers) will throw an error as that createDrivers doesn't exist (AttributeError) i think if i were you i will do it like so:\nclass A(...
[ 3, 2, 1 ]
[]
[]
[ "abstract_methods", "option_type", "pymel", "python", "subclass" ]
stackoverflow_0004704541_abstract_methods_option_type_pymel_python_subclass.txt
Q: asyncore callbacks launching threads... ok to do? I'm unfamiliar with asyncore, and have very limited knowledge of asynchronous programming except for a few intro to twisted tutorials. I am most familiar with threads and use them in all my apps. One particular app uses a couchdb database as its interface. This inv...
asyncore callbacks launching threads... ok to do?
I'm unfamiliar with asyncore, and have very limited knowledge of asynchronous programming except for a few intro to twisted tutorials. I am most familiar with threads and use them in all my apps. One particular app uses a couchdb database as its interface. This involves longpolling the db looking for changes and update...
[ "Wouldn't this create a new thread every time the server returns a new document? I would guess that you are best creating a pool of worker threads before you call anything on the server, and just add a job to the queue that these threads are reading their work from in the dispatch method.\nBut there is no reason wh...
[ 3 ]
[]
[]
[ "asyncore", "couchdb", "multithreading", "python" ]
stackoverflow_0004704285_asyncore_couchdb_multithreading_python.txt
Q: Python validation API I'm looking for a Python (<3) validation API something like Java's Bean Validation or Spring validation. I'm not looking for a library that is limited to form validation, since I want to validate domain objects. Do you know a Python API for validating of domain objects? A: maybe you should...
Python validation API
I'm looking for a Python (<3) validation API something like Java's Bean Validation or Spring validation. I'm not looking for a library that is limited to form validation, since I want to validate domain objects. Do you know a Python API for validating of domain objects?
[ "maybe you should try formencode? it's not form-only validation library\n", "Spring.py\n", "The only libraries that are a bit like Java's Bean validation that I know (and have used) are:\n\nZope 3's zope.schema , but this is tied to using zope interfaces I think\nSQLAlchamy's Elixir, but this is tied to using S...
[ 3, 2, 1, 1 ]
[]
[]
[ "bean_validation", "domain_driven_design", "java", "python", "validation" ]
stackoverflow_0003996124_bean_validation_domain_driven_design_java_python_validation.txt
Q: Does python have automatic resource management? All versions of Java require the user to close resources manually - usually handled in the finally block. Java 7 is about to get ARM (automatic resource management) blocks. Firstly I don't see a finally block concept in python. Or do you close resources in the catc...
Does python have automatic resource management?
All versions of Java require the user to close resources manually - usually handled in the finally block. Java 7 is about to get ARM (automatic resource management) blocks. Firstly I don't see a finally block concept in python. Or do you close resources in the catch for each raised exceptions ? Is there a library tha...
[ "There is a try: except: finally: in python. \nYou can also use the with: statement, which I believe is what you are after for ARM. These are called context managers. http://www.python.org/dev/peps/pep-0343/\n", "There is some automated resource management in Python. Most objects who open resources will close th...
[ 10, 2 ]
[]
[]
[ "java", "python" ]
stackoverflow_0004704558_java_python.txt
Q: Documentation for gnomekeyring Python lib Is there a documentation for Python 'gnomekeyring' lib somewhere in the Web? A: There is the reference for the C library which the Python package uses. Most function names are identical (except for the "gnome_keyring_" prefix). The Bending Gnome Keyring with Python blog ...
Documentation for gnomekeyring Python lib
Is there a documentation for Python 'gnomekeyring' lib somewhere in the Web?
[ "There is the reference for the C library which the Python package uses. Most function names are identical (except for the \"gnome_keyring_\" prefix). The Bending Gnome Keyring with Python blog series should give you a good start as well.\nAnd as the keyring package was already mentioned: If I remember correctly, t...
[ 5, 2 ]
[]
[]
[ "gnome", "python" ]
stackoverflow_0004704732_gnome_python.txt
Q: Using Pygame Module from imported script Greetings! I'm creating a simple snake game. I want to expand my classes in different modules e.i. have menu class in a separate script from my main game loop. In other words, I want my imported script to take the pygame init which was called earlier in main script. Here is...
Using Pygame Module from imported script
Greetings! I'm creating a simple snake game. I want to expand my classes in different modules e.i. have menu class in a separate script from my main game loop. In other words, I want my imported script to take the pygame init which was called earlier in main script. Here is a quick example using pseudo code of my probl...
[ "The imports of the module that imports module X don't leak through to X's namespace (which is a good thing - it would either require dynamic scoping or C/C++-style #include, both are almost never useful and often even harmful). It's a completely seperate namespace on its own. If you want to use something (e.g. pyg...
[ 3, 1 ]
[]
[]
[ "import", "namespaces", "pygame", "python" ]
stackoverflow_0004704634_import_namespaces_pygame_python.txt
Q: Can Python be used as an effective script language for Windows Server environment? I'm currently working on a strategy for managing multiple Windows Server 2003 to 2008 running SQL Server 2000 - 2008 and I want/need a unified scripting platform for automating tasks. I'm becoming a big fan of Python and as such I'...
Can Python be used as an effective script language for Windows Server environment?
I'm currently working on a strategy for managing multiple Windows Server 2003 to 2008 running SQL Server 2000 - 2008 and I want/need a unified scripting platform for automating tasks. I'm becoming a big fan of Python and as such I'd like to know if Python has been used effectively as a scripting language for administe...
[ "Notwithstanding my love of Python, I think PowerShell fits more.\nFrom Wikipedia:\n\nWindows PowerShell is Microsoft's task automation framework, consisting of a command-line shell and associated scripting language built on top of, and integrated with the .NET Framework. PowerShell provides full access to COM and ...
[ 9, 4, 1, 1, 0 ]
[]
[]
[ "ironpython", "python", "windows_server" ]
stackoverflow_0004702133_ironpython_python_windows_server.txt
Q: New to django : Having a bug when creating models hello i have an unknown error when creating a model class(check the code below ). im following the tutorial on the official django website , but it's not working for some reason, and i have been struggling over it for a while but with no results . is there anything...
New to django : Having a bug when creating models
hello i have an unknown error when creating a model class(check the code below ). im following the tutorial on the official django website , but it's not working for some reason, and i have been struggling over it for a while but with no results . is there anything wrong with what im doing ? >>> class a(models.Model):...
[ "The module containing your models should be named myapp.models from the Python interpreter's perspective. This error means that it's resolving as just models.\nFirst, the Python module containing this model needs to be inside of a Django application folder which is on the PYTHONPATH. Try using python manage.py s...
[ 3, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004703242_django_python.txt
Q: Multiprocessing in python - ensuring a minimum number of child processes are active I want to ensure that a mininum number of child processes spawned are still active at any given time; the currently spawns as below: pool = Pool(processes=WORKERS) pool.map(worker.run, range(WORKERS)) # pass process a number as its...
Multiprocessing in python - ensuring a minimum number of child processes are active
I want to ensure that a mininum number of child processes spawned are still active at any given time; the currently spawns as below: pool = Pool(processes=WORKERS) pool.map(worker.run, range(WORKERS)) # pass process a number as its ID There are certain cases where the workers would return or crash and burn because of ...
[ "Here's a simple (dumb?) solution: periodically check all your workers, pop those that have returned and add new ones to the worker list (base code borrowed from Doug Hellman):\nimport multiprocessing, random, time\n\ndef worker(num):\n \"\"\"thread worker function\"\"\"\n time.sleep(random.randint(1,10))\n ...
[ 2 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0004685253_multiprocessing_python.txt
Q: Trouble getting QMainWindow to scroll A minimal example: class MainWindow(QtGui.QMainWindow): def __init__(self, parent = None): QtGui.QMainWindow.__init__(self, parent) winWidth = 683 winHeight = 784 screen = QtGui.QDesktopWidget().availableGeometry() screenCenterX = (screen.width() - wi...
Trouble getting QMainWindow to scroll
A minimal example: class MainWindow(QtGui.QMainWindow): def __init__(self, parent = None): QtGui.QMainWindow.__init__(self, parent) winWidth = 683 winHeight = 784 screen = QtGui.QDesktopWidget().availableGeometry() screenCenterX = (screen.width() - winWidth) / 2 screenCenterY = (screen.hei...
[ "Accomplished via... \nmainWidget = QtGui.QWidget()\nmainWidget.setLayout(layout)\n\nscrollWidget = QtGui.QScrollArea()\nscrollWidget.setWidget(mainWidget)\nscrollWidget.setWidgetResizable(True) # <---------------\n\nself.setCentralWidget(scrollWidget)\n\n", "I would suggest setting the form directly as the wi...
[ 1, 0 ]
[]
[]
[ "pyqt", "python", "qt", "user_interface" ]
stackoverflow_0004690979_pyqt_python_qt_user_interface.txt
Q: How to turn this simple 5 bytes back into 4 bytes ? (algorithm to convert 4 bytes into 5 bytes is known) The algorithm to convert input 8 digit hex number into 10 digit are following: Given that the 8 digit number is: '12 34 56 78' x1 = 1 * 16^8 * 2^3 x2 = 2 * 16^7 * 2^2 x3 = 3 * 16^6 * 2^1 x4 = 4 * 16^4 * 2^4 x...
How to turn this simple 5 bytes back into 4 bytes ? (algorithm to convert 4 bytes into 5 bytes is known)
The algorithm to convert input 8 digit hex number into 10 digit are following: Given that the 8 digit number is: '12 34 56 78' x1 = 1 * 16^8 * 2^3 x2 = 2 * 16^7 * 2^2 x3 = 3 * 16^6 * 2^1 x4 = 4 * 16^4 * 2^4 x5 = 5 * 16^3 * 2^3 x6 = 6 * 16^2 * 2^2 x7 = 7 * 16^1 * 2^1 x8 = 8 * 16^0 * 2^0 Final 10 digit hex is: => x1 +...
[ "From this conversion algorithm:\nx1 = 1 * 16^8 * 2^3\nx2 = 2 * 16^7 * 2^2\nx3 = 3 * 16^6 * 2^1\nx4 = 4 * 16^4 * 2^4\nx5 = 5 * 16^3 * 2^3\nx6 = 6 * 16^2 * 2^2\nx7 = 7 * 16^1 * 2^1\nx8 = 8 * 16^0 * 2^0\n\nYou can see that after 16^4 it skipped to 16^6.\nPull one off so that it arranges nicely.\nx1 = 1 * 16^7 * 16^1 ...
[ 5 ]
[]
[]
[ "algorithm", "math", "python" ]
stackoverflow_0004704989_algorithm_math_python.txt
Q: Creating interruptible process in python I'm creating a python script of which parses a large (but simple) CSV. It'll take some time to process. I would like the ability to interrupt the parsing of the CSV so I can continue at a later stage. Currently I have this - of which lives in a larger class: (unfinished) Ed...
Creating interruptible process in python
I'm creating a python script of which parses a large (but simple) CSV. It'll take some time to process. I would like the ability to interrupt the parsing of the CSV so I can continue at a later stage. Currently I have this - of which lives in a larger class: (unfinished) Edit: I have some changed code. But the system w...
[ "If under linux, hit Ctrl-Z and stop the running process. Type \"fg\" to bring it back and start where you stopped it.\n", "You can use signal to catch the event. This is a mockup of a parser than can catch CTRL-C on windows and stop parsing:\nimport signal, tme, sys\n\ndef onInterupt(signum, frame):\n raise I...
[ 2, 1, 1, 0 ]
[]
[]
[ "csv", "interrupt_handling", "python", "windows" ]
stackoverflow_0004599759_csv_interrupt_handling_python_windows.txt
Q: How to query multiple tables in SQLAlchemy ORM I'm a newcomer to SQLAlchemy ORM and I'm struggling to accomplish complex-ish queries on multiple tables - queries which I find relatively straightforward to do in Doctrine DQL. I have data objects of Cities, which belong to Countries. Some Cities also have a County I...
How to query multiple tables in SQLAlchemy ORM
I'm a newcomer to SQLAlchemy ORM and I'm struggling to accomplish complex-ish queries on multiple tables - queries which I find relatively straightforward to do in Doctrine DQL. I have data objects of Cities, which belong to Countries. Some Cities also have a County ID set, but not all. As well as the necessary primary...
[ "The mapping for Suit is not present but based on the propel query I would assume it has a text_strings attribute.\nThe relevant portion of SQLAlchemy documentation describing aliases with joins is at:\nhttp://www.sqlalchemy.org/docs/orm/tutorial.html#using-aliases\ngeneration of functions is at:\nhttp://www.sqlalc...
[ 5, 0 ]
[]
[]
[ "doctrine", "python", "sqlalchemy" ]
stackoverflow_0004619959_doctrine_python_sqlalchemy.txt
Q: Replace special characters in python I have some text coming from the web as such: £6.49 Obviously I would like this to be displayed as: £6.49 I have tried the following so far: s = url['title'] s = s.encode('utf8') s = s.replace(u'Â','') And a few variants on this (after finding it on this very same forum) But ...
Replace special characters in python
I have some text coming from the web as such: £6.49 Obviously I would like this to be displayed as: £6.49 I have tried the following so far: s = url['title'] s = s.encode('utf8') s = s.replace(u'Â','') And a few variants on this (after finding it on this very same forum) But still no luck as I keep getting: Unicode...
[ "If, s=url['title'] makes s equal to this:\nIn [48]: s=u'Oscar Winners Best Pictures Box Set \\xc2\\xa36.49'\n\nThen the problem is \n\nin the code that defines url,\nor else the content from the web is\nmal-formed.\n\nIf Case 1, we'd need to see the code that defines url. \nIf Case 2, a quick-and-dirty workaround ...
[ 7, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0004705793_python_string.txt
Q: Skip sanitization for videos in html5lib I am using a wmd-editor in django, much like this one in which I am typing. I would like to allow the users to embed videos in it. For that I am using the Markdown video extension here. The problem is that I am also sanitizing user input using html5lib sanitization and it d...
Skip sanitization for videos in html5lib
I am using a wmd-editor in django, much like this one in which I am typing. I would like to allow the users to embed videos in it. For that I am using the Markdown video extension here. The problem is that I am also sanitizing user input using html5lib sanitization and it doesn't allow object tags which are required to...
[ "A better solution would be to append 'object' to html5lib.sanitizer.HTMLSanitizer.acceptable_elements. A great solution would be to subclass html5lib.sanitizer.HTMLSanitizer so you can conditionally accept or remove the object in sanitize_token.\nThe implementation seems clear enough to tackle.\n" ]
[ 3 ]
[]
[]
[ "django", "html5lib", "python", "sanitization" ]
stackoverflow_0002951123_django_html5lib_python_sanitization.txt
Q: Replace symbols in python script on distribution I have a python script that outputs the program name, version number and the author when called with command line arguments like --help or --version. Currently this information is hardcoded in the python script itself. But I use distutils for building/packaging the ...
Replace symbols in python script on distribution
I have a python script that outputs the program name, version number and the author when called with command line arguments like --help or --version. Currently this information is hardcoded in the python script itself. But I use distutils for building/packaging the application so all this information is already present...
[ "Do it the other way around. Add the version number, the author name and other metadata you need in the script to the script itself. Then import or execfile() the script in setup.py, and use the metadata defined in the script as arguments to the setup() function.\n", "Have a file __version__.py in your package'...
[ 3, 2, 0 ]
[]
[]
[ "distutils", "python" ]
stackoverflow_0004705723_distutils_python.txt
Q: Need help with Django tutorial I'm doing the Django tutorial here: http://docs.djangoproject.com/en/1.2/intro/tutorial03/ My TEMPLATE_DIRS in the settings.py looks like this: TEMPLATE_DIRS = ( "/webapp2/templates/" "/webapp2/templates/polls" # Put strings here, like "/home/html/django_templates" or "C...
Need help with Django tutorial
I'm doing the Django tutorial here: http://docs.djangoproject.com/en/1.2/intro/tutorial03/ My TEMPLATE_DIRS in the settings.py looks like this: TEMPLATE_DIRS = ( "/webapp2/templates/" "/webapp2/templates/polls" # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Alwa...
[ "TEMPLATE_DIRS = (\n \"/webapp2/templates/\"\n \"/webapp2/templates/polls\"\n)\n\nPython concatenates those strings during compilation if you don't put a comma in between.\nAnd another thing: Usually you don't need to hardcode template directories. The following should be enough for most cases:\ndef fromRelat...
[ 3, 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004705962_django_python.txt
Q: Python: listing IP ranges I have problem with the netaddr package - version 0.7.5. This code works as expected and prints out the list of ip addresses in the range: from netaddr import IPNetwork ipnetwork = '192.168.0.0/24' print list(IPNetwork(ipnetwork).iter_hosts()) However, if I change the network to, say, '...
Python: listing IP ranges
I have problem with the netaddr package - version 0.7.5. This code works as expected and prints out the list of ip addresses in the range: from netaddr import IPNetwork ipnetwork = '192.168.0.0/24' print list(IPNetwork(ipnetwork).iter_hosts()) However, if I change the network to, say, '192.168.0.0/8' my script just h...
[ "Are you sure that it's not just taking a lot of time? You are making a list out of the iterator. When I run that on my machine, I get 100% CPU usage and memory usage increase. I can also print out the entire range if I use the iterator directly.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0004706144_python.txt
Q: Python, Twisted, Django, reactor.run() causing problem I have a Django web application. I also have a spell server written using twisted running on the same machine having django (running on localhost:8090). The idea being when user does some action, request comes to Django which in turn connects to this twisted s...
Python, Twisted, Django, reactor.run() causing problem
I have a Django web application. I also have a spell server written using twisted running on the same machine having django (running on localhost:8090). The idea being when user does some action, request comes to Django which in turn connects to this twisted server & server sends data back to Django. Finally Django put...
[ "The above two answers are correct. However, considering that you've already implemented a spelling server then run it as one. You can start by running it on the same machine as a separate process - at localhost:PORT. Right now it seems you have a very simple binary protocol interface already - you can implement an...
[ 4, 3, 1 ]
[]
[]
[ "django", "python", "twisted", "twisted.client", "twisted.internet" ]
stackoverflow_0004534740_django_python_twisted_twisted.client_twisted.internet.txt
Q: Can I run Bottle.py on my Apache server without disrupting my PHP apps? I'm antsy to get Python running on my webserver after just recently picking it up. I chose Bottle.py because it looks simple, accessible, and contained. I have very little experience with or knowledge of how exactly webservers work (how to mes...
Can I run Bottle.py on my Apache server without disrupting my PHP apps?
I'm antsy to get Python running on my webserver after just recently picking it up. I chose Bottle.py because it looks simple, accessible, and contained. I have very little experience with or knowledge of how exactly webservers work (how to mess with them) and I'm reluctant to play with my server's Apache if I don't nee...
[ "Run it in a WSGI container such as mod_wsgi.\n", "You can also run Apace as a proxy to your application. I believe using mod_proxy would get you there. I myself run a nginx front end as reverse proxy to a bottle application running on bjoern. Bjoern itself is quite capable of running the bottle app, so I didn't ...
[ 5, 2 ]
[]
[]
[ "apache2", "bottle", "python" ]
stackoverflow_0004389905_apache2_bottle_python.txt
Q: How to save a figure remotely with pylab? I'm trying to generate a figure at a remote computer with the command pylab.savefig. But I got such error: Unable to access the X Display, is $DISPLAY set properly? How can I save the figure properly? A: By default, matplotlib will use something like the TkAgg backend. ...
How to save a figure remotely with pylab?
I'm trying to generate a figure at a remote computer with the command pylab.savefig. But I got such error: Unable to access the X Display, is $DISPLAY set properly? How can I save the figure properly?
[ "By default, matplotlib will use something like the TkAgg backend. This requires an X-server to be running.\nWhile you can just use X-forwarding, there will be a noticeable lag as matplotlib tries to connect with the remote X-server. If you don't need to interact with the plot, it's often nicer to speed things up...
[ 152, 1 ]
[]
[]
[ "figure", "matplotlib", "python" ]
stackoverflow_0004706451_figure_matplotlib_python.txt
Q: I am writing a small app in bottle. I have some conceptual problem help me to solve it out from bottle import route, run, debug, error, request, template @route('/home') @route('/home/') def login(): return template('templates/login') @route('/home', method='POST') @route('/home/', method='POST') def welocm...
I am writing a small app in bottle. I have some conceptual problem help me to solve it out
from bottle import route, run, debug, error, request, template @route('/home') @route('/home/') def login(): return template('templates/login') @route('/home', method='POST') @route('/home/', method='POST') def welocme(): data = request.POST if data: password = data.get('password') check_...
[ "If the user goes to the \"/home\" page, don't you want to check to see if they're logged in before showing them the login screen? It appears like you assume they're not already logged in if the HTTP method is not POST.\nI don't know much about your framework, but I assume if the login is successful you should set...
[ 1, 1, 0 ]
[]
[]
[ "bottle", "python" ]
stackoverflow_0004289115_bottle_python.txt
Q: python __import__ from same folder fails I have a directory structure like so: |- project |- commands.py |- Modules | |- __init__.py | |- base.py | \- build.py \- etc.... I have the following code in __init__.py commands = [] hooks = [] def load_modules(): """ dynamically loads commands from the ...
python __import__ from same folder fails
I have a directory structure like so: |- project |- commands.py |- Modules | |- __init__.py | |- base.py | \- build.py \- etc.... I have the following code in __init__.py commands = [] hooks = [] def load_modules(): """ dynamically loads commands from the /modules subdirectory """ path = "\\".join...
[ "All you're missing is having Modules on the system path. Add\nimport sys\nsys.path.append(path)\n\nafter your path = ... line and you should be set. Here's my test script:\nimport os, os.path, sys\n\nprint '\\n'.join(sys.path) + '\\n' * 3\n\ncommands = []\nhooks = []\n\ndef load_modules():\n \"\"\" dynamically ...
[ 2 ]
[]
[]
[ "import", "importerror", "python" ]
stackoverflow_0004496156_import_importerror_python.txt
Q: MySQL python DBAPI. How to get a dictionary instead of a tuple? Python DB API returns a list of tuples when fetchall is invoked on an executed cursor. If you work with the _mysql module, fetch_row has a how parameter that allows to get a dictionary instead of a tuple. How can I achieve the same with the cursor ? ...
MySQL python DBAPI. How to get a dictionary instead of a tuple?
Python DB API returns a list of tuples when fetchall is invoked on an executed cursor. If you work with the _mysql module, fetch_row has a how parameter that allows to get a dictionary instead of a tuple. How can I achieve the same with the cursor ?
[ "Quoting from the documentation\nDictCursor\n Like Cursor except it returns rows as dictionaries.\n\n" ]
[ 4 ]
[]
[]
[ "mysql", "python", "python_db_api" ]
stackoverflow_0004706660_mysql_python_python_db_api.txt
Q: How to keep an App Engine/Java app running with deaf requests from a Java/Python web cron? App Engine allows you 30 seconds to load your application My application takes around 30 seconds - sometimes more, sometimes less. I don't know how to fix this. If the app is idle (does not receive a request for a while), it...
How to keep an App Engine/Java app running with deaf requests from a Java/Python web cron?
App Engine allows you 30 seconds to load your application My application takes around 30 seconds - sometimes more, sometimes less. I don't know how to fix this. If the app is idle (does not receive a request for a while), it needs to be re-loaded. So, to avoid the app needing to be reloaded, I want to simulate user ...
[ "It would probably be easier use the cron built in to App Engine to keep your application alive.\n", "I think what you want is just:\nimport httplib\nhcon = httplib.HTTPConnection(\"foo.appspot.com\")\nhcon.request(\"GET\", \"/someURL\")\nhcon.close()\n\n", "the simplest Java http pinger:\nURLConnection hcon = ...
[ 2, 1, 1, 1 ]
[]
[]
[ "google_app_engine", "httpwebrequest", "java", "keep_alive", "python" ]
stackoverflow_0001113066_google_app_engine_httpwebrequest_java_keep_alive_python.txt
Q: ImportError: cannot import name ModuleA I have the following stacktrace when I try to import ModuleA: Traceback (most recent call last): File "menu.py", line 9, in <module> from tmserver impor...
ImportError: cannot import name ModuleA
I have the following stacktrace when I try to import ModuleA: Traceback (most recent call last): File "menu.py", line 9, in <module> from tmserver import Module1 ...
[ "That would seem like the logical conclusion; perhaps if you posted samples of the code you were running you'd be able to get a better reply?\n" ]
[ 3 ]
[]
[]
[ "import", "importerror", "module", "python" ]
stackoverflow_0004707111_import_importerror_module_python.txt
Q: Guidance for Python logic programming I am having difficulty figuring out how to go about coding a simple logic program to calculate pendulum movement. See this doc, I am stuck on task two. What I have so far is: Defined variables Raw_input for variables Code pasted from the PDF. Unfortunately I'm not sure how t...
Guidance for Python logic programming
I am having difficulty figuring out how to go about coding a simple logic program to calculate pendulum movement. See this doc, I am stuck on task two. What I have so far is: Defined variables Raw_input for variables Code pasted from the PDF. Unfortunately I'm not sure how to go on since I have very limited experienc...
[ "Since this is homework, I won't give you a complete answer - I'll just give some hints.\nThe question asks you to reduce the timestep. To do this change this line:\ndt = 0.1 # Use a smaller value.\n\nIt then asks you to verify that the period and amplitude of the oscillation are correct. The simplest way to do thi...
[ 1 ]
[]
[]
[ "logic", "python" ]
stackoverflow_0004707087_logic_python.txt
Q: Django find oldest entry in database Looking for a way in a Django view to find the oldest entry in the database. Then take that value and to a time since. There has to be a simple way to do this with writing a complicated query. A: If you have a created timestamp on your model, then could you sort ascending by ...
Django find oldest entry in database
Looking for a way in a Django view to find the oldest entry in the database. Then take that value and to a time since. There has to be a simple way to do this with writing a complicated query.
[ "If you have a created timestamp on your model, then could you sort ascending by this field and grab the first value?\nTo do the differences between the dates, you may be able to use an aggregate function to find the highest and lowest date, but I am uncertain. Something along the following lines might work:\nMyMod...
[ 3 ]
[]
[]
[ "datetime", "django", "python", "view" ]
stackoverflow_0004707136_datetime_django_python_view.txt
Q: ImportError: cannot import name aliases I just installed the Python 2.7.1 on Windows Vista using installer from official site, and get such error when run python.exe C:\Python27>python.exe Traceback (most recent call last): File "C:\Python27\Lib\site.py", line 553, in <module> main() File "C:\Python27\Lib\...
ImportError: cannot import name aliases
I just installed the Python 2.7.1 on Windows Vista using installer from official site, and get such error when run python.exe C:\Python27>python.exe Traceback (most recent call last): File "C:\Python27\Lib\site.py", line 553, in <module> main() File "C:\Python27\Lib\site.py", line 542, in main aliasmbcs() ...
[ "The only reference I could find points to a virus problem:\nStarts here: http://mail.python.org/pipermail/tutor/2009-January/066730.html\nGoes through: http://mail.python.org/pipermail/tutor/2009-January/066739.html\nAnd ends: http://mail.python.org/pipermail/tutor/2009-January/066750.html\nIf your \\Lib\\encoding...
[ 3 ]
[]
[]
[ "installation", "python", "windows" ]
stackoverflow_0004707030_installation_python_windows.txt
Q: How does the get_or_create function in Django return two values? I have used the get_or_create function on my models in Django. This function returns two values. One is the object itself and the other a boolean flag that indicates whether an existing object was retrieved or a new one created. Normally, a function ...
How does the get_or_create function in Django return two values?
I have used the get_or_create function on my models in Django. This function returns two values. One is the object itself and the other a boolean flag that indicates whether an existing object was retrieved or a new one created. Normally, a function can return a single value or a collection of values like a tuple, list...
[ "get_or_create() simply returns a tuple of the two values. You can then use sequence unpacking to bind the two tuple entries to two names, like in the documentation example:\np, created = Person.objects.get_or_create(\n first_name='John', last_name='Lennon',\n defaults={'birthday': date(1940, 10, 9)})\n\n", ...
[ 30, 6, 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004706697_django_python.txt
Q: How can I update QTextEdit as user writes on it? (on Python) I'm working on a Python+Qt WebSMS app/script. It asks for a number and message, and sends it to Vodafone via mechanize. Since Vodafone of my country doesn't support UTF-8, at least for WebSMS and every SMS should be shorter than 160 chars, I'm using this...
How can I update QTextEdit as user writes on it? (on Python)
I'm working on a Python+Qt WebSMS app/script. It asks for a number and message, and sends it to Vodafone via mechanize. Since Vodafone of my country doesn't support UTF-8, at least for WebSMS and every SMS should be shorter than 160 chars, I'm using this setup: def setMesaj(): global mesaj mesaj = unicode(self.text...
[ "def setMesaj(self):\n mesaj = unicode(self.toPlainText().toUtf8(), \"utf-8\")\n ascii = mesaj.encode(\"ascii\", \"ignore\")\n if ascii != mesaj:\n self.setPlainText(ascii)\n\n if (len(mesaj)) > 159:\n QtGui.QMessageBox.warning(self, 'warning', \"[WARN-1] Mesaj 160 karakterden fazla?\")\n i = len(mesaj...
[ 0, 0 ]
[]
[]
[ "python", "qt" ]
stackoverflow_0004706954_python_qt.txt
Q: Problem with python cgi in Firefox I have written an html form and am trying to incorporate a python cgi script with it. I have already configured my apache server to execute cgi scripts from the cgi-bin directory. Here's the html form: <html> <body> <form name="input" action="c:/xampp/cgi-bin/test2.py" method="po...
Problem with python cgi in Firefox
I have written an html form and am trying to incorporate a python cgi script with it. I have already configured my apache server to execute cgi scripts from the cgi-bin directory. Here's the html form: <html> <body> <form name="input" action="c:/xampp/cgi-bin/test2.py" method="post"> <input type="text" name="qry" /...
[ "You are correct: it has something to do with the path to the CGI script on the HTML page. The form's action attribute should refer to the path where the CGI script is getting interpreted on the server, e.g., /cgi-bin/test2.py.\nSince you made this mistake, I'm assuming you are new to web development. Consider usin...
[ 1 ]
[]
[]
[ "cgi", "firefox", "forms", "python" ]
stackoverflow_0004707318_cgi_firefox_forms_python.txt
Q: Implicit Module Search in Python? I'm working on a more complete understanding of Python Virtual Environment for portablity issues across cheap hosting solutions and development platforms and there are pieces I don't understand. I've been building virtual environments, but I'm not seeing the COMPLETE ISOLATION I n...
Implicit Module Search in Python?
I'm working on a more complete understanding of Python Virtual Environment for portablity issues across cheap hosting solutions and development platforms and there are pieces I don't understand. I've been building virtual environments, but I'm not seeing the COMPLETE ISOLATION I need for copying virtual environments to...
[ "Are you talking about virtualenv? There's an option when you create the virtual environment that excludes all existing site packages. I think that's what you want.\nvirtualenv --no-site-packages env\n\n" ]
[ 2 ]
[]
[]
[ "pinax", "python" ]
stackoverflow_0004706892_pinax_python.txt
Q: How can I detect whether an image is a PNG or APNG format? Possible Duplicate: Can I programatically determine if a PNG is animated? APNG is backwards compatible with PNG. I opened up an apng and png file in a hex editor and the first few bytes look identical. So if a user uploads either of these formats, how do...
How can I detect whether an image is a PNG or APNG format?
Possible Duplicate: Can I programatically determine if a PNG is animated? APNG is backwards compatible with PNG. I opened up an apng and png file in a hex editor and the first few bytes look identical. So if a user uploads either of these formats, how do I detect what the format really is? I've seen this done on som...
[ "From http://en.wikipedia.org/wiki/Apng:\n\nAmong users and maintainers of the PNG and MNG formats, APNG was not \n well received. In particular, PNG was conceived to be a single-image \n format [2]. APNG hides the subsequent frames in PNG ancillary chunks \n in such a way that APNG-unaware applications would ig...
[ 1, 1, 0, 0 ]
[]
[]
[ "apng", "perl", "php", "python", "ruby" ]
stackoverflow_0004705674_apng_perl_php_python_ruby.txt
Q: How to send custom http_headers for RPC calls using python xmlrpclib? How can I send custom HTTP Headers using python xmlrpclib library ! ? I need to send some special custom http_headers at the time of calling RPC methods. A: You can subclass xmlrpclib.Transport and pass that as an argument to ServerProxy. Pick...
How to send custom http_headers for RPC calls using python xmlrpclib?
How can I send custom HTTP Headers using python xmlrpclib library ! ? I need to send some special custom http_headers at the time of calling RPC methods.
[ "You can subclass xmlrpclib.Transport and pass that as an argument to ServerProxy. Pick a method to override (I chose send_content) and you're set.\n# simple test program (from the XML-RPC specification)\nfrom xmlrpclib import ServerProxy, Transport, Error\n\nclass SpecialTransport(Transport):\n\n def send_conte...
[ 14 ]
[]
[]
[ "http_headers", "python", "xml_rpc", "xmlrpclib" ]
stackoverflow_0004624085_http_headers_python_xml_rpc_xmlrpclib.txt
Q: Ways to avoid MySQLdb's "Commands out of sync; you can't run this command now" (2014) exception Following code, using python 2.6.6 and MySQLdb 1.2.2 causes Commands out of sync; you can't run this command now MySQLdb exception: import MySQLdb conn = MySQLdb.connect( db="test", user="root" ) cursor = conn.cursor( ...
Ways to avoid MySQLdb's "Commands out of sync; you can't run this command now" (2014) exception
Following code, using python 2.6.6 and MySQLdb 1.2.2 causes Commands out of sync; you can't run this command now MySQLdb exception: import MySQLdb conn = MySQLdb.connect( db="test", user="root" ) cursor = conn.cursor( MySQLdb.cursors.DictCursor ) cursor.execute( "BEGIN; CREATE TABLE t1 ( t1_id INT PRIMARY KEY AUTO_IN...
[ "DB-API tries to handle transactions on its own, starting a transaction on the first command and having its own API call to commit it, so:\ncursor.execute( \"CREATE TABLE t1 ( t1_id INT PRIMARY KEY AUTO_INCREMENT )\" )\ncursor.commit()\ncursor.execute( \"CREATE TABLE t2 ( t2_id INT PRIMARY KEY AUTO_INCREMENT )\" )\...
[ 10 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0004707957_mysql_python.txt
Q: Compiling a PyObjC application for 10.5 (Leopard) into xcode 10.6 (Snow Leopard) I'm trying to deploy on 10.5 a PyObjC (or Cocoa-Python) application developed on Xcode 3.2.X (Snow Leopard) which runs perfectly fine on 10.6 systems. The application doesn't launch on 10.5;it crashes at launch giving this error mess...
Compiling a PyObjC application for 10.5 (Leopard) into xcode 10.6 (Snow Leopard)
I'm trying to deploy on 10.5 a PyObjC (or Cocoa-Python) application developed on Xcode 3.2.X (Snow Leopard) which runs perfectly fine on 10.6 systems. The application doesn't launch on 10.5;it crashes at launch giving this error message (found on Crash Report): Dyld Error Message: Library not loaded: /System/Libr...
[ "The path you're seeing may very well be a legitimate path to the version of the Python framework you linked against. That's the correct path for the most recent version of SnowLeopard (10.6.5), at least. You may very well have set up the path to the framework correctly in your Xcode project. \nIf I had to guess...
[ 1, 0 ]
[]
[]
[ "cocoa", "pyobjc", "python", "xcode" ]
stackoverflow_0003282053_cocoa_pyobjc_python_xcode.txt
Q: Is this parallel calculation using the new concurrent.futures lib OK? I submitted the following, which runs OK for me, but I only have a single core machine and I take the documentations comment that it will be spread over more cores if I had them; automatically. from concurrent import futures import math NUMBERS...
Is this parallel calculation using the new concurrent.futures lib OK?
I submitted the following, which runs OK for me, but I only have a single core machine and I take the documentations comment that it will be spread over more cores if I had them; automatically. from concurrent import futures import math NUMBERS = [ 112272537195293, 112582718962171, 112272537095293, 115...
[ "I bought a multi-core laptop for xmas. The example worked fine.\n" ]
[ 0 ]
[]
[]
[ "concurrency", "parallel_processing", "python" ]
stackoverflow_0004497619_concurrency_parallel_processing_python.txt
Q: Exercise 7.9 in "How to Think Like a Computer Scientist (python)" measuring occurrences of a character in a string The question is how to write a program that measures how many times a character appears in a string in a generalizable way in python. The code that I wrote: def countLetters(str, ch): count=0 in...
Exercise 7.9 in "How to Think Like a Computer Scientist (python)" measuring occurrences of a character in a string
The question is how to write a program that measures how many times a character appears in a string in a generalizable way in python. The code that I wrote: def countLetters(str, ch): count=0 index=0 for ch in str: if ch==str[index]: count=count+1 index=index+1 print count when I use this ...
[ "You are over-writing your 'ch' variable:\ndef countLetters(str, ch):\n# ^ the character you are looking for\n count=0\n index=0\n for ch in str:\n# ^ the string character you are trying to check\n if ch==str[index]: # ???\n count=count+1\n index=index+...
[ 5, 2, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0004708273_python_string.txt
Q: python __getattr__ help Reading a Book, i came across this code... # module person.py class Person: def __init__(self, name, job=None, pay=0): self.name = name self.job = job self.pay = pay def lastName(self): return self.name.split()[-1] def giveRaise(self, percen...
python __getattr__ help
Reading a Book, i came across this code... # module person.py class Person: def __init__(self, name, job=None, pay=0): self.name = name self.job = job self.pay = pay def lastName(self): return self.name.split()[-1] def giveRaise(self, percent): self.pay = int(se...
[ "\nIn your __init__ you instantiate a Person object which gets assigned to self.person.\nYou then override attribute lookups on the Manager instance (by implementing __getattr__ for this class) and redirect these attributes to be looked up on the self.person variable instead (which is the Person object from 1 in th...
[ 2, 0, 0 ]
[]
[]
[ "getattr", "python", "python_datamodel" ]
stackoverflow_0004706173_getattr_python_python_datamodel.txt
Q: How do i estimate download time when response header does not contain content-length? how do i estimate download progress/time when the file to be downloaded lacks the content-length information? Thanks A: You you find yourself in the rather improbable situation that the server won't send you content lengths but...
How do i estimate download time when response header does not contain content-length?
how do i estimate download progress/time when the file to be downloaded lacks the content-length information? Thanks
[ "You you find yourself in the rather improbable situation that the server won't send you content lengths but accepts byte range requests (and you really really need to know how long it'll take), you can use the code in Python seek on remote file using HTTP and do a binary search to get some notion about the file si...
[ 1 ]
[]
[]
[ "content_length", "python", "urllib2" ]
stackoverflow_0004268494_content_length_python_urllib2.txt
Q: Is it possible to override the method used to call Django's admin delete confirmation page? On Django's admin pages, I'd like to perform an action when the administrator clicks the Delete button for an object. In other words, I'd like to execute some code prior to arriving on the "Are you sure?" delete confirmati...
Is it possible to override the method used to call Django's admin delete confirmation page?
On Django's admin pages, I'd like to perform an action when the administrator clicks the Delete button for an object. In other words, I'd like to execute some code prior to arriving on the "Are you sure?" delete confirmation page. I realize I could override the template page for this object, but I was hoping for somet...
[ "You can override ModelAdmin.delete_view() method, like:\nclass MyModelAdmin(ModelAdmin):\n def delete_view(self, request, object_id, extra_context=None):\n # if request.POST is set, the user already confirmed deletion\n if not request.POST:\n perform_my_action()\n super(MyModelAd...
[ 7, 3 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0001015072_django_django_admin_python.txt
Q: python authenticate with urllib2 and cookielib and get login passed/failed result Here is cut from my code which I use to login into the remote site. My problem is that I don't know how to handle authentication pass/fail result. def prepareLoginData(self): self.post_login_data = urllib.urlencode({ ...
python authenticate with urllib2 and cookielib and get login passed/failed result
Here is cut from my code which I use to login into the remote site. My problem is that I don't know how to handle authentication pass/fail result. def prepareLoginData(self): self.post_login_data = urllib.urlencode({ 'login': self.user, ...
[ "Maybe you can look at the source code of the returned page:\nIn a lot of moderns websites, every xhtml element of the page has an id or a class or is child on an element with an id or a class, so i think you can use an xhtml parser like BeautifulSoup to extract error messages from the website.\nBeautifulSoup is ve...
[ 0 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0004701111_python_urllib2.txt
Q: How to I modify a class of a library to get it to use my extension of another library class? Short story: I want to make slight changes to the behavior of a MainClass, and a HelperClass on which it depends, in a popular library. I can easily extend both by subclassing, but how do I tell the top-level class to use...
How to I modify a class of a library to get it to use my extension of another library class?
Short story: I want to make slight changes to the behavior of a MainClass, and a HelperClass on which it depends, in a popular library. I can easily extend both by subclassing, but how do I tell the top-level class to use my extended version of the helper class? The MainClass generates instances of HelperClass via s...
[ "That's some ugly way to design a class, and I guess there's an even uglier way to hack around it:\nfrom django.forms import forms\n\nclass MyBoundField(object):\n pass\n\nforms.BoundField = MyBoundField\n\n" ]
[ 1 ]
[]
[]
[ "django", "oop", "python" ]
stackoverflow_0004708380_django_oop_python.txt
Q: Asynchronously updating PyGTK tray icon As explained here, I have a simple tray icon using PyGTK. Being very new to GTK, it appears to me that gtk.main() is synchronous, blocking any further processing until the respective UI is closed. So how can I periodically (e.g. every 5 seconds) update/refresh StatusIcon's i...
Asynchronously updating PyGTK tray icon
As explained here, I have a simple tray icon using PyGTK. Being very new to GTK, it appears to me that gtk.main() is synchronous, blocking any further processing until the respective UI is closed. So how can I periodically (e.g. every 5 seconds) update/refresh StatusIcon's icon - do I have to resort to Twisted et al. f...
[ "You can use gobject.timeout_add() to add periodical tasks. The first parameter is the interval in seconds, the second parameter is the callback you want to be called. The callback is called as long as it returns something that evaluates to True when used as a bool.\nSee also section 20 of the PyGTK FAQ, in parti...
[ 4, 0 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0004708636_gtk_pygtk_python.txt
Q: Check secure OpenID redirect? The process for openid login for my server redirects to google, for example, then google redirects back to a page with parameters in the parameter string. how do I verify this really came from google? A: Those parameters probably contain an OpenID assertion (or an error). You can ...
Check secure OpenID redirect?
The process for openid login for my server redirects to google, for example, then google redirects back to a page with parameters in the parameter string. how do I verify this really came from google?
[ "Those parameters probably contain an OpenID assertion (or an error). You can verify the assertion by following the instructions in the OpenID spec:\nhttp://openid.net/specs/openid-authentication-2_0.html#verification\nYou probably don't want to do all the work yourself, though, since it's a bit complicated. The ...
[ 1 ]
[]
[]
[ "openid", "python" ]
stackoverflow_0004693882_openid_python.txt
Q: Page not found after click in Django I have a simple menu-list {% block menu %} <ul> {% for item in list %} <li><a href="{{item}}/">{{ item }}</a></li> {% endfor %} </ul> {% endblock %} and a list: MENU = ['Home','Contact','About'] When I press Contact then go to the address 127.0.0.1:8000/C...
Page not found after click in Django
I have a simple menu-list {% block menu %} <ul> {% for item in list %} <li><a href="{{item}}/">{{ item }}</a></li> {% endfor %} </ul> {% endblock %} and a list: MENU = ['Home','Contact','About'] When I press Contact then go to the address 127.0.0.1:8000/Contact with this same template but if I ag...
[ "The particular issue here is that the HTML you emit has links to \"Contact/\", which if you're already at a /Contact URL, will go to a /Contact/Contact like you see here.\nThe quick fix is to add a / right before the {{item}}, like this:\n<li><a href=\"/{{item}}/\">{{ item }}</a></li>\n\nHowever, django has better...
[ 6, 1, 0 ]
[]
[]
[ "django", "menu", "python" ]
stackoverflow_0004708802_django_menu_python.txt
Q: connect to url in python i am trying to connect to a url with a username and password with the following code: urllib.request.urlopen("http://username:password@......etc...", None) but i'm getting urllib.error.URLError: urlopen error [Errno 11003] getaddrinfo failed anyone know what's up? A: I'm sorry. I didn...
connect to url in python
i am trying to connect to a url with a username and password with the following code: urllib.request.urlopen("http://username:password@......etc...", None) but i'm getting urllib.error.URLError: urlopen error [Errno 11003] getaddrinfo failed anyone know what's up?
[ "I'm sorry. I didn't notice you are using py3k.\nSee urllib.request - FancyURLopener. I personally don't know py3k very well.\nBasically, you need to subclass urllib.request.FancyURLopener, override prompt_user_passwd(host, realm), and then call YourClass.urlopen(url).\nBelow is for py2 \nThis is what you want, ur...
[ 5, 2, 1 ]
[]
[]
[ "authentication", "http", "python", "python_3.x" ]
stackoverflow_0004706342_authentication_http_python_python_3.x.txt
Q: Start with some C++ framework or python I am thinking about to learn new language or framework. Now I deal with C# and WPF, WCF, Winforms. I have some free time so I would like get new skills. But I have dilema, start with some C++ framework (such as Platinum, Reason, Evocosm, ACF) or try Python / python framework...
Start with some C++ framework or python
I am thinking about to learn new language or framework. Now I deal with C# and WPF, WCF, Winforms. I have some free time so I would like get new skills. But I have dilema, start with some C++ framework (such as Platinum, Reason, Evocosm, ACF) or try Python / python framework. I you are on my place which possibility you...
[ "Python is incredibly easy to learn, very powerful, and very useful (especially for web development IMO).\nC++ is very widespread and is similar to other languages like C# and Java. Python's syntax is quite unique and AFAIK is not very similar to any other languages. Nonetheless, Python syntax is far easier to read...
[ 4, 1, 0, 0, 0, 0 ]
[]
[]
[ "c++", "frameworks", "python" ]
stackoverflow_0004708482_c++_frameworks_python.txt
Q: python socket.connect timeout error in mulithread or multiprocess Like the following, I'd like to communicate with many PC's in a specific IP range. My PC ---+------> Client A PC +------> Client B PC +------> Client C PC ................. +------> Client Z PC Because there are ...
python socket.connect timeout error in mulithread or multiprocess
Like the following, I'd like to communicate with many PC's in a specific IP range. My PC ---+------> Client A PC +------> Client B PC +------> Client C PC ................. +------> Client Z PC Because there are too many clients to communicate, I tried it by mulit-threading. socket....
[ "David Beazley has done some great research around the Python GIL and how that affects IO and multithreading. You can find information about his research here, here.\n" ]
[ 5 ]
[]
[]
[ "multiprocessing", "multithreading", "python", "sockets", "timeout" ]
stackoverflow_0004205423_multiprocessing_multithreading_python_sockets_timeout.txt
Q: How to serialize and deserialize User profile info in Datastore? For a User Entity, I want to create a property that is a dictionary of serialized data. The data is: time = time_value name = name_value id = id_value Are there existing libraries to support serializing data, including DateTime values, and then des...
How to serialize and deserialize User profile info in Datastore?
For a User Entity, I want to create a property that is a dictionary of serialized data. The data is: time = time_value name = name_value id = id_value Are there existing libraries to support serializing data, including DateTime values, and then deserializing them into their types (like DateTime, String, Integer) when...
[ "The built-in Python library pickle can be used to serialize and deserialize your data (while maintaining type information). You can store the \"pickled\" data in a db.BlobProperty. \nUnfortunately, Google App Engine's uses a Python-only implementation for the pickle library, and does not have support for the muc...
[ 2 ]
[]
[]
[ "google_app_engine", "json", "python", "serialization" ]
stackoverflow_0004708720_google_app_engine_json_python_serialization.txt
Q: Construct Numpy index given list of starting and ending positions I have two identically-sized numpy.array objects (both one-dimensional), one of which contains a list of starting index positions, and the other of which contains a list of ending index positions (alternatively you could say I have a list of startin...
Construct Numpy index given list of starting and ending positions
I have two identically-sized numpy.array objects (both one-dimensional), one of which contains a list of starting index positions, and the other of which contains a list of ending index positions (alternatively you could say I have a list of starting positions and window lengths). In case it matters, the slices formed ...
[ "I would use\nnp.r_[tuple(slice(s, e) for s, e in zip(start, end))]\n\nEDIT: Here is a solution that does not use a Python loop:\ndef indices(start, end):\n lens = end - start\n np.cumsum(lens, out=lens)\n i = np.ones(lens[-1], dtype=int)\n i[0] = start[0]\n i[lens[:-1]] += start[1:]\n i[lens[:-1]...
[ 7, 2, 0 ]
[ "You stated \"alternatively you could say I have a list of starting positions and window lengths\" which does not match your example array. \nIf start indicates the start and end is the length, you can get your elements this way:\n>>> [i for iter in [range(s,s+e) for s,e in zip(start,end)] for i in iter]\n[1, 2, 3,...
[ -1 ]
[ "numpy", "python" ]
stackoverflow_0004707623_numpy_python.txt
Q: PermanentTaskFailure on deferred : permanent failure attempting to execute task I'm reading a lot of this kind error in my application's log lately: Permanent failure attempting to execute task Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/deferred/defer...
PermanentTaskFailure on deferred : permanent failure attempting to execute task
I'm reading a lot of this kind error in my application's log lately: Permanent failure attempting to execute task Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/deferred/deferred.py", line 258, in post run(self.request.body) File "/base/python_runtime/py...
[ "The particular case in which this exception is being raised indicates that you deferred a task with a payload that was too big to fit on the task queue, so deferred stored the extra data to the datastore. When it attempted to execute the task, however, the entity it stored the extra data in no longer existed, lead...
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004700024_google_app_engine_python.txt
Q: Using python 2.7, why does my unicode filename raise an IOError when calling file() on it? Python 2.7: I am trying to open an mp3 to read its ID3 tag using mutagen (so I'd rather not have to change the method), which calls: file(filename, "rb") For files with no special characters this works fine, but otherwise, ...
Using python 2.7, why does my unicode filename raise an IOError when calling file() on it?
Python 2.7: I am trying to open an mp3 to read its ID3 tag using mutagen (so I'd rather not have to change the method), which calls: file(filename, "rb") For files with no special characters this works fine, but otherwise, I sometimes seem to get IOError: [Errno 2] No such file or directory: u"somepath\\08 - Muse - I ...
[ "Use os.listdir() on the directory to see what the filename is, encoded. Then compare that to what you get when you do filename.encode('cp1252'). There should be a difference, and that should tell you what is wrong.\nThe only real problem I can think of is that something gets decoded twice. You could have normaliza...
[ 1, 1 ]
[]
[]
[ "file", "file_io", "ioerror", "python", "unicode" ]
stackoverflow_0004671575_file_file_io_ioerror_python_unicode.txt
Q: Python string formatting: reference one argument multiple times If I have a string like: "{0} {1} {1}" % ("foo", "bar") and I want: "foo bar bar" What do the replacement tokens have to be? (I know that my example above is incorrect; I'm just trying to express my goal.) A: "{0} {1} {1}".format("foo", "bar") A:...
Python string formatting: reference one argument multiple times
If I have a string like: "{0} {1} {1}" % ("foo", "bar") and I want: "foo bar bar" What do the replacement tokens have to be? (I know that my example above is incorrect; I'm just trying to express my goal.)
[ "\"{0} {1} {1}\".format(\"foo\", \"bar\")\n\n", "\"%(foo)s %(foo)s %(bar)s\" % { \"foo\" : \"foo\", \"bar\":\"bar\"}\n\nis another true but long answer. Just to show you another viewpoint about the issue ;)\n", "Python 3 has exactly that syntax, except the % operator is now the format method. str.format has als...
[ 73, 16, 8 ]
[]
[]
[ "python", "string_formatting" ]
stackoverflow_0004709310_python_string_formatting.txt
Q: GAE formpreview I'm trying to enable form preview with Google App Engine. Getting the following error message I suspect being mistaken somewhere: ... handler = handler_class() TypeError: __call__() takes at least 2 arguments (1 given) Can you tell what's wrong with my attempt? Here is some of the code. from dj...
GAE formpreview
I'm trying to enable form preview with Google App Engine. Getting the following error message I suspect being mistaken somewhere: ... handler = handler_class() TypeError: __call__() takes at least 2 arguments (1 given) Can you tell what's wrong with my attempt? Here is some of the code. from django.contrib.formtool...
[ "You're attempting to pass an instance of your 'AFormPreview' class as the handler class for your webapp app. You can't do this - the handler class needs to be a subclass of webapp.RequestHandler.\n" ]
[ 1 ]
[]
[]
[ "django", "django_forms", "google_app_engine", "python" ]
stackoverflow_0004698955_django_django_forms_google_app_engine_python.txt
Q: wireless adaper using python I am trying to find the network adapter id( a guid) of a computer using python. Any idea? Thanks Sudhanshu A: Have you tried this (manually)? http://forum.notebookreview.com/windows-os-software/302638-how-find-network-adapter-guid.html If it works, you can then try coding it in Pytho...
wireless adaper using python
I am trying to find the network adapter id( a guid) of a computer using python. Any idea? Thanks Sudhanshu
[ "Have you tried this (manually)?\nhttp://forum.notebookreview.com/windows-os-software/302638-how-find-network-adapter-guid.html\nIf it works, you can then try coding it in Python via pywin32\n" ]
[ 0 ]
[]
[]
[ "adapter", "networking", "python" ]
stackoverflow_0004708947_adapter_networking_python.txt
Q: Cython float division PyExc_ZeroDivisionError checking I'm doing some loop-intensive calculations and converted the code into Cython. I did profiling with cython -a option, and inspected the .html file, and it seems whenever I do the float division, there is somewhat yellow line and it does something like the foll...
Cython float division PyExc_ZeroDivisionError checking
I'm doing some loop-intensive calculations and converted the code into Cython. I did profiling with cython -a option, and inspected the .html file, and it seems whenever I do the float division, there is somewhat yellow line and it does something like the following: if (unlikely(__pyx_t_37 == 0)) { PyErr_Format...
[ "You need to add @cython.cdivision(True) to avoid the exception checking. \nimport cython\n\ncdef double pydivision():\n cdef int i\n cdef double k, j\n k = 2.0\n j = 0.0\n for i in range(10):\n j += i/k\n # Generated code: Python exception checking\n # /* \"checksum.pyx\":9\n # * j = 0.0\n # * for ...
[ 20, 1 ]
[]
[]
[ "cython", "python" ]
stackoverflow_0004709285_cython_python.txt
Q: running python from another directory Hallo, if i try to run a python script from another directory, it tells me everytime that he cannot find all the ressource files: pygame.error: Couldn't open ../data/icon.png etc.. I think this is because of the relative paths and the now changed working directory? Am I righ...
running python from another directory
Hallo, if i try to run a python script from another directory, it tells me everytime that he cannot find all the ressource files: pygame.error: Couldn't open ../data/icon.png etc.. I think this is because of the relative paths and the now changed working directory? Am I right? and how can i avoid this? greetings Edit...
[ "You are correct. This can be avoided in the script by using __file__ to get the location of the current module and the various functions in os.path to generate absolute paths based on the value.\n", "Assume that your project is a directory in your file system and if you are referencing the modules and scripts wi...
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004709533_python.txt
Q: What does this Perl XML filter look like in Python? curl -u $1:$2 --silent "https://mail.google.com/mail/feed/atom" | perl -ne 'print "\t" if /<name>/; print "$2\n" if /<(title|name)>(.*)<\/\1>/;' I have this shell script which gets the Atom feed with command-line arguments for the username and password. I was wo...
What does this Perl XML filter look like in Python?
curl -u $1:$2 --silent "https://mail.google.com/mail/feed/atom" | perl -ne 'print "\t" if /<name>/; print "$2\n" if /<(title|name)>(.*)<\/\1>/;' I have this shell script which gets the Atom feed with command-line arguments for the username and password. I was wondering if this type of thing was possible in Python, and...
[ "Python does not lend itself to compact one liners quite as well as Perl. This is primarily for three reasons:\n\nWith Perl, whitespace is insignificant in almost all cases. In Python, whitespace is very significant.\nPerl has some helpful shortcuts for one liners, such as perl -ne or perl -pe that put an implicit ...
[ 3, 1 ]
[]
[]
[ "curl", "email", "perl", "python", "regex" ]
stackoverflow_0004709312_curl_email_perl_python_regex.txt
Q: How can I create a list in Python? http://diveintopython3.ep.io/native-datatypes.html I've found that link but it seems to rely on the fact that I first have to hard create the list. How can I create a list in Python if it's empty at first. I'm coming from a C# background so this is kind of weird so far. For examp...
How can I create a list in Python?
http://diveintopython3.ep.io/native-datatypes.html I've found that link but it seems to rely on the fact that I first have to hard create the list. How can I create a list in Python if it's empty at first. I'm coming from a C# background so this is kind of weird so far. For example the .append() method is what I'm look...
[ "You can create an empty list like this\nL=list()\n\nor\nL=[]\n\n", "As noted by others, you can create an empty list with the list literal operator [].\nIts worth noting that you can initialise the list with values if you always need to start with a few values already in place:\na = 5\nL = [42, -12, a]\n\n" ]
[ 4, 1 ]
[]
[]
[ "collections", "list", "python" ]
stackoverflow_0004709654_collections_list_python.txt