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: What template systems exist suitable for writing service creation recipies I have a requirement to build a bulk service creation daemon that can be fed a table of data and then go off and create a set of pre-canned services. However the type of services are potentially many and varied and potentially later steps w...
What template systems exist suitable for writing service creation recipies
I have a requirement to build a bulk service creation daemon that can be fed a table of data and then go off and create a set of pre-canned services. However the type of services are potentially many and varied and potentially later steps will require the output of previous steps. It seems what I need to implement in s...
[ "I think Mako or Jinja2 both can fit the bill.\n\nBoth are not html/xml templates but are text based.\nBoth are popular and well documented.\nMako has more pythonic syntax where as BIG advantage with Jinja is, it supports sandboxing which might be useful for you.\n\n" ]
[ 2 ]
[]
[]
[ "python", "recipe", "templates" ]
stackoverflow_0005802897_python_recipe_templates.txt
Q: Python Package For Multi-Threaded Spider w/ Proxy Support? Instead of just using urllib does anyone know of the most efficient package for fast, multithreaded downloading of URLs that can operate through http proxies? I know of a few such as Twisted, Scrapy, libcurl etc. but I don't know enough about them to make ...
Python Package For Multi-Threaded Spider w/ Proxy Support?
Instead of just using urllib does anyone know of the most efficient package for fast, multithreaded downloading of URLs that can operate through http proxies? I know of a few such as Twisted, Scrapy, libcurl etc. but I don't know enough about them to make a decision or even if they can use proxies.. Anyone know of the ...
[ "is's simple to implement this in python.\n\nThe urlopen() function works\n transparently with proxies which do\n not require authentication. In a Unix\n or Windows environment, set the\n http_proxy, ftp_proxy or gopher_proxy\n environment variables to a URL that\n identifies the proxy server before\n starti...
[ 17, 1 ]
[]
[]
[ "multithreading", "pool", "proxy", "python", "web_crawler" ]
stackoverflow_0001628766_multithreading_pool_proxy_python_web_crawler.txt
Q: Raw_input to subprocess Is there a way to take a raw_input, record it to memory, then call it in a subprocess? x = raw_input("what is your fav. Color??") Subprocess.Popen("C://Windows/system32/cmd.exe") os.system('echo your favorite color is "x"') My main need for this is so that I can take a user's raw_input a...
Raw_input to subprocess
Is there a way to take a raw_input, record it to memory, then call it in a subprocess? x = raw_input("what is your fav. Color??") Subprocess.Popen("C://Windows/system32/cmd.exe") os.system('echo your favorite color is "x"') My main need for this is so that I can take a user's raw_input and incorporate that into a co...
[ "Okay, you get your input using raw_input\nx = raw_input('Input:')\n\nAnd then send it to subprocess command which is invoking your friend's binary like this\nfrom subprocess import Popen, PIPE, STDOUT\n\np = Popen(['yourfriendsbinary'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)\n\nout,err = p.communicate(input=x)\np...
[ 5, 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0005803215_python_subprocess.txt
Q: How to run Python code coverage tests for Google App Engine in Eclipse or from command line I want to run Python code coverage tests for Google App Engine in Eclipse or from command line. Normally Python program required such command line: coverage run program arguments I trying to run it for Google App Engine but...
How to run Python code coverage tests for Google App Engine in Eclipse or from command line
I want to run Python code coverage tests for Google App Engine in Eclipse or from command line. Normally Python program required such command line: coverage run program arguments I trying to run it for Google App Engine but no data is collected from following command line: coverage run [path_to_google_app_engine]/dev_a...
[ "I don't know much about GAE, but I know a lot about coverage.py. If the dev_appserver.py command runs the server in the same process, then the command you have should work. If the server actually runs in a subprocess, then see Measuring subprocesses in the coverage.py docs for how to get subprocesses measured.\n...
[ 2 ]
[]
[]
[ "code_coverage", "google_app_engine", "python", "unit_testing" ]
stackoverflow_0005800674_code_coverage_google_app_engine_python_unit_testing.txt
Q: Django Admin Customizing I am designing an admin interface where invite mails will be sent to users. My Invitation model is ready & in my invitation admin interface I am able to see my added users for which the admin can send email invites. now I want to customize this a bit. I want to add for each row a SEND but...
Django Admin Customizing
I am designing an admin interface where invite mails will be sent to users. My Invitation model is ready & in my invitation admin interface I am able to see my added users for which the admin can send email invites. now I want to customize this a bit. I want to add for each row a SEND button which will actually send a...
[ "My solution below is for adding the \"send invite\" action in admin interface\n\"Send Invite\" action\nYou can refer to the django admin-actions documentation here.\nHere is what your admin.py should look like:\nfrom django.contrib import admin\nfrom myapp.models import MyModel\nfrom django.core.mail import send_m...
[ 4, 4 ]
[]
[]
[ "customization", "django", "django_admin", "django_templates", "python" ]
stackoverflow_0005803547_customization_django_django_admin_django_templates_python.txt
Q: Can I specify another class's instance-method as a variable for my method? I'm still relatively new to python, 1-2 years of solo-learning, and am trying to improve my code structure so I'm refactoring some old programs I wrote. In one program, I defined a couple of methods for writing files. The first uses, "wri...
Can I specify another class's instance-method as a variable for my method?
I'm still relatively new to python, 1-2 years of solo-learning, and am trying to improve my code structure so I'm refactoring some old programs I wrote. In one program, I defined a couple of methods for writing files. The first uses, "write" to dump a huge http-response. The second uses "writelines" to dump various ...
[ "You can get a \"bound method\" from an object, which is then callable as a function without having a reference to the object.\nf = obj.method\nf(args)\n# is equivalent to\nobj.method(args)\n\nHowever, that's not useful for you, as you create the object you want to use only in the method - you can't pass it in ther...
[ 2, 1 ]
[]
[]
[ "instance_methods", "python", "refactoring" ]
stackoverflow_0005803634_instance_methods_python_refactoring.txt
Q: In boost.python; how do I expose a class that is contained in another class (via composition)? I'd like to do something really simple with boost::python. I can find documentation for class member functions, and documention for inherited classes but nowhere can I find the syntax for exposing class hierarchies creat...
In boost.python; how do I expose a class that is contained in another class (via composition)?
I'd like to do something really simple with boost::python. I can find documentation for class member functions, and documention for inherited classes but nowhere can I find the syntax for exposing class hierarchies created via composition. So I have some C++ code that goes something like this: struct A{ double x,y;...
[ "Documentation for dir says: \n\nIf the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.\n\nIn your example, your class member are exported as instance attributes and not class attributes which is what you want when exporting non static...
[ 0 ]
[]
[]
[ "boost", "c++", "class", "member", "python" ]
stackoverflow_0005792508_boost_c++_class_member_python.txt
Q: python - remote hosts timezone vs local I'm building a web frontend for remote logs monitoring, having to manage about 10 different geographic locations I've bumped into the 3 headed hellhound some of you already have. Is there any way to get from a remote HPUX shell variable the following remote info: zoneinfo (...
python - remote hosts timezone vs local
I'm building a web frontend for remote logs monitoring, having to manage about 10 different geographic locations I've bumped into the 3 headed hellhound some of you already have. Is there any way to get from a remote HPUX shell variable the following remote info: zoneinfo (Country/City) UTC + offset (I can easily get ...
[ "You should be able to find your GMT offset like this...\nAs a GMT offset, disregarding DST\n(time.localtime()[3] - time.localtime()[8]) - time.gmtime()[3]\nI am in Central time (GMT - 6) so, this yields -6 on my system.\nAs a GMT offset, including DST compensation\n(time.localtime()[3]) - time.gmtime()[3]\nThis yi...
[ 3 ]
[]
[]
[ "hp_ux", "python", "pytz", "zoneinfo" ]
stackoverflow_0005803290_hp_ux_python_pytz_zoneinfo.txt
Q: Filtering the drop down list of ReferenceModels created by appengine using django I have some classes in my app engine project class First(db.Model): count = db.IntegerProperty() class Second(db.Model): first = db.ReferenceProperty(First) class SecondForm(djangoforms.ModelForm) class Meta: model = Seco...
Filtering the drop down list of ReferenceModels created by appengine using django
I have some classes in my app engine project class First(db.Model): count = db.IntegerProperty() class Second(db.Model): first = db.ReferenceProperty(First) class SecondForm(djangoforms.ModelForm) class Meta: model = Second The SecondForm model generates a really nice drop down menu in the template when re...
[ "Add the following init method to the SecondForm class:\ndef __init__(self, *args, **kwargs):\n super(SecondForm, self).__init__(*args, **kwargs)\n self.fields['first'].query = db.Query(First).fetch(10)\n\nAdd filters etc to the query to control the dropdown list contents!!\n", "I don't have experience usin...
[ 2, 1, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0005795367_django_google_app_engine_python.txt
Q: Regex is causing an error that I can't seem to find The code below worked fine until I added the regex line. When I comment it out, the code works again ... I'm stumped. I'm only using a regex to search a file for three different type of strings concurrently(ascii, hex, string). Any help is appreciated, thanks! e...
Regex is causing an error that I can't seem to find
The code below worked fine until I added the regex line. When I comment it out, the code works again ... I'm stumped. I'm only using a regex to search a file for three different type of strings concurrently(ascii, hex, string). Any help is appreciated, thanks! elif searchType =='2': print " Directory to be ...
[ "When I ran this code, I got an error like\nFile \"search.py\", line 7\n for root,dirname, files in os.walk(directory):\n ^\nSyntaxError: invalid syntax\n\nThis is because the previous line, which contains the compiled regular expression, is missing a closing parentheses:\nregex = re.compile( \"(%s|%s|%s)\"...
[ 4 ]
[]
[]
[ "python", "regex", "search" ]
stackoverflow_0005805293_python_regex_search.txt
Q: Overloading + to support tuples I'd like to be able to write something like this in python: a = (1, 2) b = (3, 4) c = a + b # c would be (4, 6) d = 3 * b # d would be (9, 12) I realize that you can overload operators to work with custom classes, but is there a way to overload operators to work with pairs? Of cour...
Overloading + to support tuples
I'd like to be able to write something like this in python: a = (1, 2) b = (3, 4) c = a + b # c would be (4, 6) d = 3 * b # d would be (9, 12) I realize that you can overload operators to work with custom classes, but is there a way to overload operators to work with pairs? Of course, such solutions as c = tuple([x+y ...
[ "In contrast to Ruby, you can't change the behaviour of built-in types in Python. All you can do is create a new type derived from a built-in type. Literals will still create the built-in type, though.\nProbably the best you can get is\nclass T(tuple):\n def __add__(self, other):\n return T(x + y for x,...
[ 7, 3, 2, 2, 2, 1, 1 ]
[]
[]
[ "operator_overloading", "python", "tuples" ]
stackoverflow_0005802020_operator_overloading_python_tuples.txt
Q: Can I print what string format was matched from a multiple-string, Regex search In the code below, I'm searching for string, hex, and ascii .... If the string is matched, the file where the string was matched is printed. Is there a way to print what string type was matched (hex, ascii, or string)? Additionally, I ...
Can I print what string format was matched from a multiple-string, Regex search
In the code below, I'm searching for string, hex, and ascii .... If the string is matched, the file where the string was matched is printed. Is there a way to print what string type was matched (hex, ascii, or string)? Additionally, I would like to consider upper and lower case, and numbers [0-9]+. I'm not sure if I ca...
[ "How about this?\nfor line in f.readlines():\n if userstring in line:\n print 'User input in file: ' + os.path.join(root, file)\n break\n elif userStrHEX in line:\n print 'HEX string in file: ' + os.path.join(root, file)\n break\n elif userStrASCII in line:\n print 'ASCII...
[ 4, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005805854_python_regex.txt
Q: Python infinite loop after aborting I have this code: class LogDigger: @staticmethod def RunInfiniteLoopSyslog(): while True: line = LogDigger.syslog_p.stdout.readline() Utils.log("New line in syslog: %s" % line.rstrip('\n')) @staticmethod def RunInfiniteLoopXlog()...
Python infinite loop after aborting
I have this code: class LogDigger: @staticmethod def RunInfiniteLoopSyslog(): while True: line = LogDigger.syslog_p.stdout.readline() Utils.log("New line in syslog: %s" % line.rstrip('\n')) @staticmethod def RunInfiniteLoopXlog(): while True: line = ...
[ "Expanding on what Fantasizer has said, try the code below:\nwhile True:\n try:\n print('running')\n except KeyboardInterrupt:\n print('stop')\n exit(0)\n\n", "You may be interested in signal module to handle SIGINT and others in a more graceful way\n", "With a ctrl+c, python raises a...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005803676_python.txt
Q: Displaying an inverted vertical date axis The chart I'm trying to make is a 2D-array with date as its vertical dimension. By convention, the dates should increase from the top down. Displaying the date the other way around works fine with this code: import numpy as np import matplotlib as mpl import matplotlib.col...
Displaying an inverted vertical date axis
The chart I'm trying to make is a 2D-array with date as its vertical dimension. By convention, the dates should increase from the top down. Displaying the date the other way around works fine with this code: import numpy as np import matplotlib as mpl import matplotlib.colorbar as cb import matplotlib.pyplot as plt fro...
[ "It's too bad that inverting a datetime axis obliterates the ticklocator and formatting settings. The easiest thing I can figure is to manually re-set them. Here's a link to the format table. Here's a link to DateFormatter. You could also probably use AutoDateFormatter.\nHere's the code:\nimport numpy as np\nim...
[ 1 ]
[]
[]
[ "axis", "matplotlib", "python" ]
stackoverflow_0005804969_axis_matplotlib_python.txt
Q: Elegant setup of Python logging in Django I have yet to find a way of setting up Python logging with Django that I'm happy with. My requirements are fairly simple: Different log handlers for different events - that is, I want to be able to log to different files Easy access to loggers in my modules. The module sh...
Elegant setup of Python logging in Django
I have yet to find a way of setting up Python logging with Django that I'm happy with. My requirements are fairly simple: Different log handlers for different events - that is, I want to be able to log to different files Easy access to loggers in my modules. The module should be able to find its logger with little eff...
[ "I know this is a solved answer already, but as per django >= 1.3 there's a new logging setting.\nMoving from old to new is not automatic, so I thought i'll write it down here.\nAnd of course checkout the django doc for some more.\nThis is the basic conf, created by default with django-admin createproject v1.3 - mi...
[ 129, 58, 9, 6 ]
[]
[]
[ "django", "logging", "python" ]
stackoverflow_0001598823_django_logging_python.txt
Q: How to create a legend for 3D bar in matplotlib? Given ax = plt.subplot(): ax.bar()[0] can be passed to plt.legend(). However, ax.bar3d() returns None. How do I create legend for displayed bars? UPDATE: Passing legend="stuff" to ax.bar3d() and than calling ax.legend() raises /usr/lib/python2.6/site-packages/matplo...
How to create a legend for 3D bar in matplotlib?
Given ax = plt.subplot(): ax.bar()[0] can be passed to plt.legend(). However, ax.bar3d() returns None. How do I create legend for displayed bars? UPDATE: Passing legend="stuff" to ax.bar3d() and than calling ax.legend() raises /usr/lib/python2.6/site-packages/matplotlib/axes.py:4368: UserWarning: No labeled objects fou...
[ "You need to use a proxy artist where legends are not supported.\nThis code:\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nx, y = np.random.rand(2, 100) * 4\nhist, xedges, yedges = np.histogram2d(x, y,...
[ 23 ]
[]
[]
[ "graph", "matplotlib", "numpy", "python" ]
stackoverflow_0005803015_graph_matplotlib_numpy_python.txt
Q: I'm trying to implement a valid Regex pattern I'm using the regex below to match three different type of strings. I'm having difficulty in determining where to add a case-insensitive pattern, as to match upper or lower case (eg. re.IGNORECASE or ([A-Za-z0-9]+)). Should I just try something different? regex = re.co...
I'm trying to implement a valid Regex pattern
I'm using the regex below to match three different type of strings. I'm having difficulty in determining where to add a case-insensitive pattern, as to match upper or lower case (eg. re.IGNORECASE or ([A-Za-z0-9]+)). Should I just try something different? regex = re.compile( "(%s|%s|%s)" % ( re.escape( userstring ), re...
[ "Just add it as the second argument to re.compile():\nx = re.compile(\"(%s|%s|%s)\" % (re.escape(userstring), re.escape(userStrHEX), re.escape(userStrASCII)), re.IGNORECASE)\n\nTo make it a bit easier to read, we can extract the formatting arguments into a separate tuple:\nargs = (re.escape(userstring), re.escape(u...
[ 5 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005807152_python_regex.txt
Q: Python: how to convert from Windows 1251 to Unicode? I'm trying to convert file content from Windows-1251 (Cyrillic) to Unicode with Python. I found this function, but it doesn't work. #!/usr/bin/env python import os import sys import shutil def convert_to_utf8(filename): # gather the encodings you think that th...
Python: how to convert from Windows 1251 to Unicode?
I'm trying to convert file content from Windows-1251 (Cyrillic) to Unicode with Python. I found this function, but it doesn't work. #!/usr/bin/env python import os import sys import shutil def convert_to_utf8(filename): # gather the encodings you think that the file may be # encoded inside a tuple encodings = ('windo...
[ "import codecs\n\nf = codecs.open(filename, 'r', 'cp1251')\nu = f.read() # now the contents have been transformed to a Unicode string\nout = codecs.open(output, 'w', 'utf-8')\nout.write(u) # and now the contents have been output as UTF-8\n\nIs this what you intend to do?\n", "If you use the codecs module to o...
[ 21, 0, 0 ]
[]
[]
[ "encoding", "python", "unicode" ]
stackoverflow_0005806980_encoding_python_unicode.txt
Q: Preserve XML Tags - Python DOM Implementation I have just finished skiming through the python DOM API and can't seem to find what I am looking for. I basically want to preserve the XML tags when traversing through the DOM tree. The idea is to print the tag name and corresponding attributes which I later want to co...
Preserve XML Tags - Python DOM Implementation
I have just finished skiming through the python DOM API and can't seem to find what I am looking for. I basically want to preserve the XML tags when traversing through the DOM tree. The idea is to print the tag name and corresponding attributes which I later want to convert into an xml file. <book name="bookname" sourc...
[ "A simple way to get the output you posted from the input is to override the XSLT identity transform. It looks like you want to eliminate all text nodes and all elements that have more than two ancestors, so you'd just add empty templates for those:\n<xsl:template match=\"text()\"/>\n\n<xsl:template match=\"*[coun...
[ 0 ]
[]
[]
[ "dom", "python", "xml" ]
stackoverflow_0005805198_dom_python_xml.txt
Q: Python: parse an XML in Windows-1251 encoding When I try to parse XML with lxml like this: tree = etree.parse('xml.xml') I get the following error: lxml.etree.XMLSyntaxError: Unsupported encoding windows-1251 How can I read data from an XML with this encoding? Thank you A: I think you use a Python 2.x version....
Python: parse an XML in Windows-1251 encoding
When I try to parse XML with lxml like this: tree = etree.parse('xml.xml') I get the following error: lxml.etree.XMLSyntaxError: Unsupported encoding windows-1251 How can I read data from an XML with this encoding? Thank you
[ "I think you use a Python 2.x version.\nIf so, I believe that you must use the open() function of codecs module, and to do:\nimport codecs\nwith codecs.open(filename,'rb','cp1251') as f:\n content = f.read()\n tree = etree.parse(content)\n\nI think that the obtained content has been decoded from cp1251 to Uni...
[ 5 ]
[]
[]
[ "encoding", "parsing", "python", "xml" ]
stackoverflow_0005807103_encoding_parsing_python_xml.txt
Q: is this python code with urllib2 with cookies thread safe? I'm trying to run multiple threads with urllib2 w/ cookies. I have a function like the one below which is run in about 5 threads simultaneously. I'm not installing the opener just running as is in each thread. def myfunction(inputvar): opener = urllib2...
is this python code with urllib2 with cookies thread safe?
I'm trying to run multiple threads with urllib2 w/ cookies. I have a function like the one below which is run in about 5 threads simultaneously. I'm not installing the opener just running as is in each thread. def myfunction(inputvar): opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) Is this thread saf...
[ "That should be thread-safe. If you look at the source code for urllib2.py neither the _build_opener_ function nor the HTTPCookieProcessor() use any global state. The _build_opener_ function returns a new OpenerDirector object which is also self-contained. So each thread will have its own set of objects that won't ...
[ 2 ]
[]
[]
[ "cookies", "python", "thread_safety", "urllib2" ]
stackoverflow_0004321985_cookies_python_thread_safety_urllib2.txt
Q: Python: Combining a list of lists Suppose I have a list of lists, like [[1, 2], [3, 4], [5, 6], [7, 8]]. What is the most elegant way in python to get [1, 2, 3, 4, 5, 6, 7, 8]? A: myCombinedList = [] [myCombinedList.extend(inner) for inner in mylistOfLists] Or: import itertools myCombinedIterable = itertools.ch...
Python: Combining a list of lists
Suppose I have a list of lists, like [[1, 2], [3, 4], [5, 6], [7, 8]]. What is the most elegant way in python to get [1, 2, 3, 4, 5, 6, 7, 8]?
[ "myCombinedList = []\n[myCombinedList.extend(inner) for inner in mylistOfLists]\n\nOr:\nimport itertools\nmyCombinedIterable = itertools.chain.from_iterable(mylistOfLists)\nmyCombinedList = list(myCombinedIterable)\n\n", "res=[] \nfor item in mylistOfList:\n res+=item\n\n" ]
[ 2, 0 ]
[]
[]
[ "list", "nested_lists", "python" ]
stackoverflow_0005807293_list_nested_lists_python.txt
Q: updating on a csv file using python I am working on a small project,where one of the step is to write on a csv file a list of data. I am looping through a list,and fetching specific data and writing it to a csv. The problem is when the write operation is being processed it removes previous entries of the csv file...
updating on a csv file using python
I am working on a small project,where one of the step is to write on a csv file a list of data. I am looping through a list,and fetching specific data and writing it to a csv. The problem is when the write operation is being processed it removes previous entries of the csv file.My csv writing method is as follows: and...
[ "Maybe open the file in append mode?\nfile_p = open(file_path, \"ab\")\n\n", "When you open the file, try opening it for appending, like this.\ndef csv_writer(data_list,file_path):\n import csv\n file_p = open(file_path, \"a\")\n write_pattern = csv.writer(file_p, delimiter=\",\", quotechar=\",\")\n w...
[ 5, 0, 0 ]
[]
[]
[ "csv", "io", "python" ]
stackoverflow_0005807881_csv_io_python.txt
Q: Pattern for lazy loading with Python I have data in form of a dict (coming from a MongoDB database via PyMongo), like: car = {_id: "1", "color": "silver", "steering_wheel":"2"} where the value of "steering_wheel" is the id of another document in my database which represents an instance of a class SteeringWheel. L...
Pattern for lazy loading with Python
I have data in form of a dict (coming from a MongoDB database via PyMongo), like: car = {_id: "1", "color": "silver", "steering_wheel":"2"} where the value of "steering_wheel" is the id of another document in my database which represents an instance of a class SteeringWheel. Loaded from the DB to Python would result i...
[ "How about this?\nclass Car(object):\n def __init__(self, _id, color, steering_wheel_ref_id, session):\n self._id = _id\n self.color = color\n self.steering_wheel_ref_id = steering_wheel_ref_id\n self.session = session\n self._steering_wheel = None\n\n @property\n def ste...
[ 4, 1, 1, 0 ]
[]
[]
[ "database", "python" ]
stackoverflow_0005807711_database_python.txt
Q: Git Python Cannot find Commit I am not able to find a commit that a tag points to by navigating the commit tree. For this specific example, I am using the Tornado Web repository cloned directly from Github. import sys import git if len(sys.argv) < 2: print 'python git_test.py <repo path>' sys.exit(0) rep...
Git Python Cannot find Commit
I am not able to find a commit that a tag points to by navigating the commit tree. For this specific example, I am using the Tornado Web repository cloned directly from Github. import sys import git if len(sys.argv) < 2: print 'python git_test.py <repo path>' sys.exit(0) repo = git.Repo(sys.argv[1]) commits =...
[ "I had not used gitpython before, so I was curious and tried your script on a dummy repo. I did not get any error and the tags printed properly. But I had a suspicion though:\nI added a branch, added a commit, and tagged it. Then it gave the error you were getting, and things became obvious.\nrepo.iter_commits() on...
[ 5 ]
[]
[]
[ "git", "gitpython", "python" ]
stackoverflow_0005807143_git_gitpython_python.txt
Q: python google appengine db.Model add a parent after instance has been constructed I have some models in my datastore and I wanted to add in a parent relationship as described by the parent keyword in the constructor on this page: http://code.google.com/appengine/docs/python/datastore/modelclass.html Is this possib...
python google appengine db.Model add a parent after instance has been constructed
I have some models in my datastore and I wanted to add in a parent relationship as described by the parent keyword in the constructor on this page: http://code.google.com/appengine/docs/python/datastore/modelclass.html Is this possible and if so, what would be the cleanest way to do it? Thanks
[ "You can't; the parent's key path is part of the entity's key, which can't be changed after the entity is in the datastore. You'll need to create a new entity with the same data and the new parent and delete the original entity.\n" ]
[ 6 ]
[ "Your parent class:\nclass Parent(db.Model):\n\nYour child class:\nclass Child(Parent):\n\nedit\nIf you're looking to update existing data then Wooble is correct.\n" ]
[ -2 ]
[ "google_app_engine", "python" ]
stackoverflow_0005807623_google_app_engine_python.txt
Q: Downloading Source Code from Google App Engine I am trying to download app from the google app engine using the following command: appcfg.py download_app -A <application-id> -V <application-version> <output-dir> follow this link http://code.google.com/intl/th-TH/appengine/docs/python/tools/uploadinganapp.html#Dow...
Downloading Source Code from Google App Engine
I am trying to download app from the google app engine using the following command: appcfg.py download_app -A <application-id> -V <application-version> <output-dir> follow this link http://code.google.com/intl/th-TH/appengine/docs/python/tools/uploadinganapp.html#Downloading_Source_Code i got error. Host: appengine.go...
[ "Application downloading can be disabled for an application from the App Engine dashboard. Once it's been disabled, the application's code can never be downloaded.\n", "Only the owner of an application can download it. Do you own it? If so, make sure you log in with the account that created the application. Ot...
[ 4, 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005807961_google_app_engine_python.txt
Q: new class instance not being initialized I'm writing a package, and doing my testing like a good little programmer, but here's what happens: class TestOne(unittest.TestCase): def setUp(self): self.finder = Finder() def test_default_search_parts(self): self.assertEqual(self.finder.search_pa...
new class instance not being initialized
I'm writing a package, and doing my testing like a good little programmer, but here's what happens: class TestOne(unittest.TestCase): def setUp(self): self.finder = Finder() def test_default_search_parts(self): self.assertEqual(self.finder.search_parts, []) class TestTwo(unittest.TestCase): ...
[ "As @samplebias mentioned, shared state, in this case with class-level attributes, can cause problems. Here is a possible situation you have:\nimport unittest\n\n# bad implementation of Finder, class-level attribute\nclass Finder(object):\n search_parts = []\n\n def add(self, letter):\n self.search_par...
[ 4 ]
[]
[]
[ "nose", "python", "tdd" ]
stackoverflow_0005808300_nose_python_tdd.txt
Q: Remove ppc from compilation flags in python setup scripts I'm trying to install PIL on an Intel Mac OS X Leopard machine. Unfortunately, "setup.py build" thinks it should be compiling for ppc. gcc -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -Wno-long-double -no-cpp-precomp ...
Remove ppc from compilation flags in python setup scripts
I'm trying to install PIL on an Intel Mac OS X Leopard machine. Unfortunately, "setup.py build" thinks it should be compiling for ppc. gcc -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -O3 -DHAVE_LIB...
[ "The solution that worked for me was:\nARCHFLAGS=\"-arch i386 -arch x86_64\" python setup.py build\nJust pass the values for the flag right in the command line.\n", "The easiest solution (for a single or a few C files) is to copy the compiler line, edit it, and invoke it manually, then run setup.py again - it sho...
[ 19, 2 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0001214133_python_python_imaging_library.txt
Q: Catch gaierror in Django / Python? How do I properly catch a gaierror in Django or Python? This error is brought up when a request to a 3rd party API is made and no connection can be made. I tried a try with an empty except but the gaierror was not caught. Advice? Thanks! A: I've seen some rumbling in some webs...
Catch gaierror in Django / Python?
How do I properly catch a gaierror in Django or Python? This error is brought up when a request to a 3rd party API is made and no connection can be made. I tried a try with an empty except but the gaierror was not caught. Advice? Thanks!
[ "I've seen some rumbling in some websearches about using urllib and urllib2 to catch these errors. Maybe something in this question may help you.\n" ]
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005807717_django_python.txt
Q: deleting tabs one space at a time How do I configure vim so that I can delete a tab one space at a time rather than the entire tab? I often want to do this when I'm trying to align multiple tests for an if statement. In the below example, condition3 is aligned as I want and condition2 is off by one space due to ...
deleting tabs one space at a time
How do I configure vim so that I can delete a tab one space at a time rather than the entire tab? I often want to do this when I'm trying to align multiple tests for an if statement. In the below example, condition3 is aligned as I want and condition2 is off by one space due to the tab. if condition1 or \ condi...
[ "I would say put this in your .vimrc file:\nset expandtab\n\nWhich basically turns tabs into spaces when you hit the tab key. \n", "I would just hit x in normal mode to delete a single character. I'll also point out the great indent/python.vim script by Eric McSween. It doesn't really change the backspace behavio...
[ 4, 1, 0 ]
[]
[]
[ "python", "tabs", "vim" ]
stackoverflow_0005808089_python_tabs_vim.txt
Q: How to send the text pasted in a textbox of a html webpage to the application written in python in the harddisk? I have a application running in python, i want to send the input taken from the text box of the webpage and send it as input to the application and once again the output of the application which is in t...
How to send the text pasted in a textbox of a html webpage to the application written in python in the harddisk?
I have a application running in python, i want to send the input taken from the text box of the webpage and send it as input to the application and once again the output of the application which is in text format back to the result page on web. thanks a lot for your time :) :)
[ "Here's my suggestion: modify your program to include a button for doing the transformation. When you click it, it should take the contents of the clipboard, do whatever transformation you want, and put the result back on the clipboard.\nOnce you do that, to use it you select the text from the widget, use the keybo...
[ 1, 0 ]
[]
[]
[ "html", "python", "web_hosting" ]
stackoverflow_0005807715_html_python_web_hosting.txt
Q: NoReverseMatch for get_absolute_url() newbie question Just started playing around with django and was confused with the get_absolute_url functionality. When I try to access the url for an object I get a NoReverseMatch error. Here is the stack trace $ python manage.py shell Python 2.6.6 (r266:84292, Sep 15 2010, 15...
NoReverseMatch for get_absolute_url() newbie question
Just started playing around with django and was confused with the get_absolute_url functionality. When I try to access the url for an object I get a NoReverseMatch error. Here is the stack trace $ python manage.py shell Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39) [GCC 4.4.5] on linux2 Type "help", "copyright", "c...
[ "(r'^restaurants/(\\d+)/$', 'food.views.restaurant_details'),\n\nYour URL pattern is capturing the restaurant_id as non-named group, so you need to either supply restaurant_id as positional argument, or change the url pattern to capture restaurant_id as named group\nChange URL pattern to this\n(r'^restaurants/(?P<r...
[ 3, 3 ]
[]
[]
[ "django", "python", "url" ]
stackoverflow_0005808840_django_python_url.txt
Q: saving the file content in the memory I have a fairly large pickled (dict) file in binary format that takes few seconds to load every time I look up a score from it. I was wondering if it's possible to load the file just once in the memory and look up from it until I'm logged out of the program. Also, if there's a...
saving the file content in the memory
I have a fairly large pickled (dict) file in binary format that takes few seconds to load every time I look up a score from it. I was wondering if it's possible to load the file just once in the memory and look up from it until I'm logged out of the program. Also, if there's any other way around to speed up my search. ...
[ "Load the data and then pass that reference around, instead of loading it again every time you look up your score. Now I have no idea what your code looks like, but a simple example:\ndef lookup(data):\n // do stuff with data\n\ndata = Pickle.load(\"file\")\nlookup(data)\n\n", "When I have this kind of issue I...
[ 2, 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005807346_python.txt
Q: Custom dictionary lookup in Python if I have a dictionary like this >>> d = {10: 3, 100: 2, 1000: 1} I can type something like: >>> d.get(10), d.get(100), d.get(1000) (3, 2, 1) Though I want that if the given key is not found, the value corresponding to the nearest key respect the given key is returned: >>> d.ge...
Custom dictionary lookup in Python
if I have a dictionary like this >>> d = {10: 3, 100: 2, 1000: 1} I can type something like: >>> d.get(10), d.get(100), d.get(1000) (3, 2, 1) Though I want that if the given key is not found, the value corresponding to the nearest key respect the given key is returned: >>> d.get(20), d.get(60), d.get(200) (3, 2, 2) ...
[ "You can derive from dict to change the behaviour of the get() method:\nclass ClosestDict(dict):\n def get(self, key):\n key = min(self.iterkeys(), key=lambda x: abs(x - key))\n return dict.get(self, key)\n\nd = ClosestDict({10: 3, 100: 2, 1000: 1})\nprint (d.get(20), d.get(60), d.get(200))\n\nprin...
[ 17, 6, 2 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0005808970_dictionary_python.txt
Q: Issue with connecting django signals I am trying to set up a History table that uses django signals in it in order to build a dashboard. Inside my history models.py I have: from django.dispatch import dispatcher from django.db.models import signals from project.models import Project ... dispatcher.connect(update...
Issue with connecting django signals
I am trying to set up a History table that uses django signals in it in order to build a dashboard. Inside my history models.py I have: from django.dispatch import dispatcher from django.db.models import signals from project.models import Project ... dispatcher.connect(update_dash, signal=signals.post_save, sender=Pr...
[ "That article is ancient as far as Django is concerned. Consult the latest documentation to see how we do things today.\n" ]
[ 3 ]
[]
[]
[ "django", "django_models", "django_signals", "python" ]
stackoverflow_0005809377_django_django_models_django_signals_python.txt
Q: Trouble searching User model using django-ajax-selects I´m using django-ajax-selects in my project, and I can´t make it to work with django.contrib.auth.models.User. All I want to do is search the username field and I don´t know how to put it in my settings.py. What I have now is: AJAX_LOOKUP_CHANNELS = { 'to'...
Trouble searching User model using django-ajax-selects
I´m using django-ajax-selects in my project, and I can´t make it to work with django.contrib.auth.models.User. All I want to do is search the username field and I don´t know how to put it in my settings.py. What I have now is: AJAX_LOOKUP_CHANNELS = { 'to' : dict(model='django.contrib.auth.User', search_field='user...
[ "Ok, after trying many combinations, mysteriously, this worked:\nAJAX_LOOKUP_CHANNELS = {\n 'to' : dict(model='auth.User', search_field='username'),\n}\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_ajax_selects", "django_forms", "python" ]
stackoverflow_0005808933_django_django_ajax_selects_django_forms_python.txt
Q: Segfault occurs when my shared library is optimized by icc -O3 or -O2 and used via Python ctypes This behavior is strange because I could not get the segfault if the shared library was compiled without or with weaker optimization (-O0 or -O1) if the shared library was compiled with gcc, even with optimization fla...
Segfault occurs when my shared library is optimized by icc -O3 or -O2 and used via Python ctypes
This behavior is strange because I could not get the segfault if the shared library was compiled without or with weaker optimization (-O0 or -O1) if the shared library was compiled with gcc, even with optimization flag (-O3) if I ran the code from pure C program (not via ctypes) Furthermore, I could not get the segfa...
[ "It is usually not possible to mix binaries compiled with gcc and icc (and in this case the python is built with gcc). You could try using the icc \"gcc compatibility\" mode, which is set by the -gcc-version flag. That might get it to work, but it is still possible you will have problems.\n" ]
[ 3 ]
[]
[]
[ "ctypes", "icc", "numpy", "python", "segmentation_fault" ]
stackoverflow_0005809337_ctypes_icc_numpy_python_segmentation_fault.txt
Q: Foursquare user check in V2 I am using Foursquare's v2 to allow a user to sign in to a given venue. I am trying to sign the request, but so far I am getting the following u'meta': { u'errorType': u'param_error', u'code': 400, u'errorDetail': u'Invalid checkin id' }, u'response': { } } The way I am doing it...
Foursquare user check in V2
I am using Foursquare's v2 to allow a user to sign in to a given venue. I am trying to sign the request, but so far I am getting the following u'meta': { u'errorType': u'param_error', u'code': 400, u'errorDetail': u'Invalid checkin id' }, u'response': { } } The way I am doing it is as follows, the mobile user s...
[ "You seem to be using the wrong API method.\nThe method you're using takes a checkin ID and returns details of the existing checkin.\nThis one takes a venue ID and creates a new checkin.\n" ]
[ 2 ]
[]
[]
[ "android", "foursquare", "google_app_engine", "python", "signature" ]
stackoverflow_0005801195_android_foursquare_google_app_engine_python_signature.txt
Q: Delete rest of HTML file after some text I am scraping HTML file using BeautifulSoup in python. I want to delete text after find a word. Ex: <div class="content"> <p> Page 1 </p> <p> Page 2 </p> <p> Page 3 </p> <p> Page 4 </p> <p> Page 5 </p> </div> I want to delete from Page 3. <div class="content"> <p> Page ...
Delete rest of HTML file after some text
I am scraping HTML file using BeautifulSoup in python. I want to delete text after find a word. Ex: <div class="content"> <p> Page 1 </p> <p> Page 2 </p> <p> Page 3 </p> <p> Page 4 </p> <p> Page 5 </p> </div> I want to delete from Page 3. <div class="content"> <p> Page 1 </p> <p> Page 2 </p> <p> Page 3 </p> </div>...
[ "Try this:\n\np = soup.findAll('p') \nwhile len(p) > 3:\n last_p = p.pop()\n last_p.extract()\n\n\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "html", "python" ]
stackoverflow_0005809564_beautifulsoup_html_python.txt
Q: Python: Change default application for specified mime type on Linux I tried changing default application used to open specified file types using gnomevfs.mime_set_default_application(mime_type, application_id) What I received was this warning: libgnomevfs-WARNING **: Deprecated function. User modifications to th...
Python: Change default application for specified mime type on Linux
I tried changing default application used to open specified file types using gnomevfs.mime_set_default_application(mime_type, application_id) What I received was this warning: libgnomevfs-WARNING **: Deprecated function. User modifications to the MIME database are no longer supported. Since I am making a file manager...
[ "You probably should just invoke xdg-mime from the xdg-utils package. Syntax:\nxdg-mime query default mimetype\n\nxdg-mime default application.desktop mimetype\n\n" ]
[ 2 ]
[]
[]
[ "linux", "mime_types", "python" ]
stackoverflow_0005809568_linux_mime_types_python.txt
Q: Make a pygtk stock icon "unavailable" I have a toolbar that has the typical buttons: new, save, save as, etc. Is there a way to gray out/disable/make unavailable icons that are not useful? For instance, if nothing has been changed, disable and gray out the save button, then re-enabled it when something has changed...
Make a pygtk stock icon "unavailable"
I have a toolbar that has the typical buttons: new, save, save as, etc. Is there a way to gray out/disable/make unavailable icons that are not useful? For instance, if nothing has been changed, disable and gray out the save button, then re-enabled it when something has changed that requires a save. Thanks for the help!...
[ "myButton.set_sensitive(True) # make button available\nmyButton.set_sensitive(False) # make button unavailable\n" ]
[ 0 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0005808881_pygtk_python.txt
Q: Python raising _ExpectedFailure for unittests with @unittest.expectedFailure I have two systems running the same set of Django unittests. Some of the tests use the @unittest.expectedFailure decorator. On one system, these are running fine and reporting at the end of the test run OK (expected failures=10, unexpect...
Python raising _ExpectedFailure for unittests with @unittest.expectedFailure
I have two systems running the same set of Django unittests. Some of the tests use the @unittest.expectedFailure decorator. On one system, these are running fine and reporting at the end of the test run OK (expected failures=10, unexpected successes=2). On the other system, the same tests error, but raise _ExpectedFa...
[ "I have the problem and I got it to work by deleting the /usr/local/lib/python2.7 and then reinstalling everything from scratch.\nThe reason for this I believe is that python may not have cleared it's python object and cache files(*.pyc, *.pyo) from it's working directory. That is, not YOUR project's directory but ...
[ 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0005809333_python_unit_testing.txt
Q: New to Python programming, could somebody please explain the fault with this program? I am very new to Python programming, I am writing a simple fighting game at the moment (text based) that is extremely simple as I'm just learning the basics at the moment. I have placed the code for my game below (it is not finis...
New to Python programming, could somebody please explain the fault with this program?
I am very new to Python programming, I am writing a simple fighting game at the moment (text based) that is extremely simple as I'm just learning the basics at the moment. I have placed the code for my game below (it is not finished), my problem is that every time I run the program, when you enter which character you'd...
[ "first_player.attack is a number because of self.attack = random.randint(30,40). I suspect that you want that named differently so that it doesn't overwrite your attack method.\n", "__init__() shadows the attack() method on the object. Use a different name.\n", "The variable for each players attack-strength has...
[ 9, 8, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005810235_python.txt
Q: Write a SSO application on GAE I'm looking for a solution to implement a SSO (single-sign on) application, and this app need to be in python and run on GAE (Google App Engine). This applications needs to be implemented using the SAML protocol, because Google Apps offers Single-Sign On based on SAML. In my case I c...
Write a SSO application on GAE
I'm looking for a solution to implement a SSO (single-sign on) application, and this app need to be in python and run on GAE (Google App Engine). This applications needs to be implemented using the SAML protocol, because Google Apps offers Single-Sign On based on SAML. In my case I couldn't use OpenId because allow acc...
[ "Have a look at PySAML2, it should work with App Engine:\n\nPySAML2 is a pure python\n implementation of a SAML2 service\n provider and to some extend also the\n identity provider. Originally written\n to work in a WSGI environment there\n are extensions that allow you to use\n it with other frameworks.\n\n" ...
[ 2 ]
[]
[]
[ "google_app_engine", "python", "saml", "single_sign_on" ]
stackoverflow_0005795711_google_app_engine_python_saml_single_sign_on.txt
Q: Cannot output dict key & value in Google App Engine HTML template I can't seem to get a Python dict to output its value in my HTML template. The following code simply prints an empty select element. main.py: feeds = {'feed1' : 'http://test1.xml', 'feed2' : 'http://test2.xml'} template_values = {'movieFee...
Cannot output dict key & value in Google App Engine HTML template
I can't seem to get a Python dict to output its value in my HTML template. The following code simply prints an empty select element. main.py: feeds = {'feed1' : 'http://test1.xml', 'feed2' : 'http://test2.xml'} template_values = {'movieFeeds': feeds} self.response.out.write(template.render(temp, temp...
[ "You can't do {% for key, value in data.items %} with Django 0.96.\nTry with this instead:\n{% for item in movieFeeds.items %}\n <option value=\"{{ item.0 }}\">{{ item.1 }}</option> \n{% endfor %}\n\n", "As @systempuntoout indicated, this isn't supported in Django 0.96. You can tell App Engine to use Django...
[ 2, 1 ]
[]
[]
[ "dictionary", "google_app_engine", "python" ]
stackoverflow_0005809647_dictionary_google_app_engine_python.txt
Q: Assign variables to random elements from list? Python I wan an array which is going to have about 30 things in it. Each thing in the array is going to be a set of variables, and depending on which thing in the array is chosen, different variables will be set. e.g. foo = ['fish', 'mammal', 'bird'] ranfoo = random...
Assign variables to random elements from list? Python
I wan an array which is going to have about 30 things in it. Each thing in the array is going to be a set of variables, and depending on which thing in the array is chosen, different variables will be set. e.g. foo = ['fish', 'mammal', 'bird'] ranfoo = random.randint(0,2) animal = foo[ranfoo] this works fine for ret...
[ "How about making a thing class?\nclass thing:\n def __init__(self, type = ''):\n self.type = type\n\n self.flight = (self.type in ['bird'])\n self.swim = (self.type in ['fish', 'mammal'])\n\nNow, it's quite simple to choose a random \"thing\":\nimport random\n\nthings = ['fish', 'mammal', 'bird']\nrandom...
[ 5, 0, 0, 0 ]
[]
[]
[ "arrays", "list", "python" ]
stackoverflow_0005810574_arrays_list_python.txt
Q: PyCUDA; how to distribute workload to multiple devices dynamically PyCUDA, for all its faults, usually has very good examples provided with it / downloadable from the wiki. But I couldn't find anything in the examples or in the documentation (or a cursory google search) demonstrating the PyCUDA way of dyanmically ...
PyCUDA; how to distribute workload to multiple devices dynamically
PyCUDA, for all its faults, usually has very good examples provided with it / downloadable from the wiki. But I couldn't find anything in the examples or in the documentation (or a cursory google search) demonstrating the PyCUDA way of dyanmically allocating workloads to multiple devices. Can anyone either hint me tow...
[ "Pycuda hasn't had any intrinsic multiple-GPU support because CUDA also hasn't had any intrinsic multiple-GPU support. This will change in CUDA 4.0 because the API has been changed to be thread safe and multi-GPU aware. But Pycuda doesn't yet have that support AFAIK. Even when it comes, each device has to be explic...
[ 2 ]
[]
[]
[ "cuda", "gpgpu", "multi_gpu", "pycuda", "python" ]
stackoverflow_0005810401_cuda_gpgpu_multi_gpu_pycuda_python.txt
Q: name not defined errors I continue to try nd run this program but keep getting this error: Traceback (most recent call last): File "C:\Users\bwhite3500\Documents\School\Spring 2011\CITP 110 - Intro to Computer Programming\pet_list.py", line 57, in <module> main() File "C:\Users\bwhite3500\Documents\School\...
name not defined errors
I continue to try nd run this program but keep getting this error: Traceback (most recent call last): File "C:\Users\bwhite3500\Documents\School\Spring 2011\CITP 110 - Intro to Computer Programming\pet_list.py", line 57, in <module> main() File "C:\Users\bwhite3500\Documents\School\Spring 2011\CITP 110 - Intro ...
[ "Check your spelling:\ndef diplay_list(pet_list):\n\n", "You're calling your function diplay_list, not display_list.\n" ]
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005810824_python.txt
Q: Modifying Exchange ACL for folders with python while try to read the ACL Table of a folder, I ran into this problem: In a C++ tool (MFCMAPI) this method is used to get the Property PR_ACL_TABLE in a usable data type: // Open the table in an IExchangeModifyTable interface EC_H(lpMAPIProp->OpenProperty( ulPropTag...
Modifying Exchange ACL for folders with python
while try to read the ACL Table of a folder, I ran into this problem: In a C++ tool (MFCMAPI) this method is used to get the Property PR_ACL_TABLE in a usable data type: // Open the table in an IExchangeModifyTable interface EC_H(lpMAPIProp->OpenProperty( ulPropTag, (LPGUID)&IID_IExchangeModifyTable, 0, MAPI_D...
[ "According to the docs, you need a PyIID object. \n\nHowever, in almost all cases,\n functions that expect a CLSID/IID as a\n param will accept either a string\n object, or a native PyIID object.\n\nThat said, I've seen mapi.IID_IMessage used with the OpenProperty method.\n", "IExchangeModifyTable is declared...
[ 1, 1, 0 ]
[]
[]
[ "exchange_server", "mapi", "python", "pywin32" ]
stackoverflow_0003626911_exchange_server_mapi_python_pywin32.txt
Q: string parsing in python I want to parse a string in python. Example string is four numeric values separated by white spaces. I want to parse and turn into them floating point values. The code I'm dealing is below. When I debug the code. It never enters into the else block? what's the missing point? def stringToQu...
string parsing in python
I want to parse a string in python. Example string is four numeric values separated by white spaces. I want to parse and turn into them floating point values. The code I'm dealing is below. When I debug the code. It never enters into the else block? what's the missing point? def stringToQuaternion(self, str): s...
[ "\"If it's hard, you're doing it wrong.\" ­—me\nQuadro(*[float(x) for x in S.split()])\n\n", "You are comparing str[i], which is a single character, to string.whitespace, which consists of several characters. This means str[i] and string.whitespace can never be equal.\nYou could use str[i] in string.whitespace o...
[ 7, 2, 0 ]
[]
[]
[ "parsing", "python", "string" ]
stackoverflow_0005811014_parsing_python_string.txt
Q: How to document and test interfaces required of formal parameters in Python 2? To ask my very specific question I find I need quite a long introduction to motivate and explain it -- I promise there's a proper question at the end! While reading part of a large Python codebase, sometimes one comes across code where ...
How to document and test interfaces required of formal parameters in Python 2?
To ask my very specific question I find I need quite a long introduction to motivate and explain it -- I promise there's a proper question at the end! While reading part of a large Python codebase, sometimes one comes across code where the interface required of an argument is not obvious from "nearby" code in the same ...
[ "Take a look at plac that uses annotations to define a command-line interface for a script. On Python 2.x it uses plac.annotations() decorator.\n", "The closest thing is, I believe, an annotation library called PyAnno.\nFrom the project webpage:\n\"The Pyanno annotations have two functions:\n\nProvide a structure...
[ 1, 0 ]
[]
[]
[ "annotations", "interface", "python" ]
stackoverflow_0005810063_annotations_interface_python.txt
Q: Fatal Errors and Deferreds in Twisted, stop a deferred I have a problem, with normal try except blocks in python you can just return if there is a fatal error, ex... try: logon() except 404_Error: retry_logon(try = 2) except AuthenticationProblem: error_label.SetText( "You password or username was wro...
Fatal Errors and Deferreds in Twisted, stop a deferred
I have a problem, with normal try except blocks in python you can just return if there is a fatal error, ex... try: logon() except 404_Error: retry_logon(try = 2) except AuthenticationProblem: error_label.SetText( "You password or username was wrong. Make sure that CAPS LOCK key is not on." ) return#no...
[ "Ok, a whole new answer to explain better how deferreds work. You should think, at least I do, the flow of the program as a state machine. A success or a failure is like an input of that machine that, potentially, change the state. In your case you have two states, logged and non logged, and three inputs: successfu...
[ 2 ]
[]
[]
[ "error_handling", "python", "twisted" ]
stackoverflow_0005809900_error_handling_python_twisted.txt
Q: When to use absolute imports I'm changing a bunch of old python code that is occasionally running into name collisions between packages. I have a question about when absolute imports should be used and whether it would be proper to import same-level modules by name only. /package/ /package/__init__.py /package/su...
When to use absolute imports
I'm changing a bunch of old python code that is occasionally running into name collisions between packages. I have a question about when absolute imports should be used and whether it would be proper to import same-level modules by name only. /package/ /package/__init__.py /package/subA /package/subA/__init__.py /pack...
[ "Relative imports turned out to be a very bad idea, even though they were the default behavior for long. You can find quite a few questions on this site where someone simply named their file after a builtin module and broke their application with weird error messages. \nThat's why it's always a good to do absolute ...
[ 25 ]
[]
[]
[ "import", "python" ]
stackoverflow_0005811463_import_python.txt
Q: ocr'ing application text (not scanned, NOT captchas) I'd like to interface an application by reading the text it displays. I've had success in some applications when windows isn't doing any font smoothing by typing in a phrase manually, rendering it in all windows fonts, and finding a match - from there I can map ...
ocr'ing application text (not scanned, NOT captchas)
I'd like to interface an application by reading the text it displays. I've had success in some applications when windows isn't doing any font smoothing by typing in a phrase manually, rendering it in all windows fonts, and finding a match - from there I can map each letter image to a letter by generating all letters in...
[ "I'm not exactly sure what you mean, but I think just reading the text with an OCR program would work well.\nTesseract is amazingly accurate for scanned documents, so a specific font would be a breeze for it to read. Here's my Python OCR solution: Python OCR Module in Linux?.\nBut you could generate each character ...
[ 1 ]
[]
[]
[ "fonts", "ocr", "python", "text" ]
stackoverflow_0005811550_fonts_ocr_python_text.txt
Q: Why does my notification area icon not show up when I launch my program on startup? I'm writing a small pyGTK application that displays and updates a notification area icon. The code is as follows: #!/usr/bin/env python2 from __future__ import division import pygtk pygtk.require('2.0') import gtk from time import...
Why does my notification area icon not show up when I launch my program on startup?
I'm writing a small pyGTK application that displays and updates a notification area icon. The code is as follows: #!/usr/bin/env python2 from __future__ import division import pygtk pygtk.require('2.0') import gtk from time import time from math import floor gtk.gdk.threads_init() import gobject #Parameters MIN_WORK_...
[ "Are you trying to start the app from a subdirectory of your /home/username directory? I'm wondering if you need to include the full path to the image files in your code\n", "Maybe \"at the start of [your] graphical session\" the notification area hasn't finished initializing. What happens if your program sleeps ...
[ 2, 1 ]
[]
[]
[ "gtk", "linux", "notifications", "pygtk", "python" ]
stackoverflow_0005770663_gtk_linux_notifications_pygtk_python.txt
Q: PyQt QWebKit frame bug? I'm using Python, PyQt4, and QtWebKit to load a web page into a bare-bones browser to examine the data. However, there is a small issue. I'm trying to get the contents and src of every iframe on the loaded page. I'm using webView.page().mainFrame().childFrames() to get the frames. To probl...
PyQt QWebKit frame bug?
I'm using Python, PyQt4, and QtWebKit to load a web page into a bare-bones browser to examine the data. However, there is a small issue. I'm trying to get the contents and src of every iframe on the loaded page. I'm using webView.page().mainFrame().childFrames() to get the frames. To problem is, childFrames() loads th...
[ "Not sure why you're doing what you're doing, but if it's only loading what's visible, you can set the page viewport size to the content size and that should load everything:\ndef Load(self):\n self.webView.page().setViewportSize(\n self.webView.page().mainFrame().contentsSize())\n\nHowever, this has a we...
[ 0 ]
[]
[]
[ "frame", "pyqt4", "python", "qtwebkit", "webkit" ]
stackoverflow_0004766124_frame_pyqt4_python_qtwebkit_webkit.txt
Q: open shelve file I'm trying to lookup for a "key" in "my.db". I did the following: import shelve db_file = os.path.join(self.path_data, 'my_directory', 'my.db') s = shelve.open(db_file) val = s["key"] and I get this error: /opt/Python-2.4.3/lib/python2.4/shelve.py in open(filename='/path_here/dir/netmhcpan.db', ...
open shelve file
I'm trying to lookup for a "key" in "my.db". I did the following: import shelve db_file = os.path.join(self.path_data, 'my_directory', 'my.db') s = shelve.open(db_file) val = s["key"] and I get this error: /opt/Python-2.4.3/lib/python2.4/shelve.py in open(filename='/path_here/dir/netmhcpan.db', flag='c', protocol=Non...
[ "Install db4-devel or the like, then rebuild Python.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0005812159_python.txt
Q: twisted trial unittest gets ImportError I'm trying to write some unittests using trial for my twisted application, I wrote my first 'empty' trial unittest class but when I try to run it I get ImportError for importing my app module. This is as I suspect because trial changes the current working directory and when...
twisted trial unittest gets ImportError
I'm trying to write some unittests using trial for my twisted application, I wrote my first 'empty' trial unittest class but when I try to run it I get ImportError for importing my app module. This is as I suspect because trial changes the current working directory and when I try to import my module with the object cl...
[ "How are your modules / packages organised? Perhaps try a structure like the following, then you won't need to do any path hackery: \n$ ls -R mypackage\nmypackage:\n__init__.py __init__.pyc mymodule.py mymodule.pyc test\n\nmypackage/test:\n__init__.py __init__.pyc test_mymodule.py test_mymodule.pyc\n\nrun te...
[ 0 ]
[]
[]
[ "python", "trial", "twisted" ]
stackoverflow_0005809417_python_trial_twisted.txt
Q: Circle Distance Question This is my homework question: Expand on your Circle class by adding a method called exactly dist() which takes the x and y values of a point, and returns the distance of the point in coordinate space from the outside of the circle (or zero if the point is on or inside the circle). The f...
Circle Distance Question
This is my homework question: Expand on your Circle class by adding a method called exactly dist() which takes the x and y values of a point, and returns the distance of the point in coordinate space from the outside of the circle (or zero if the point is on or inside the circle). The following code: myCircle = Circ...
[ "Find the distance between the center of the circle and the given point. Subtract the radius from the distance. Negative values are inside the circle.\n", "You can easily check if the point is inside the circle on not. Once you've done that, and determined it is outside, you need to find a line normal to the circ...
[ 4, 2, 0, 0 ]
[]
[]
[ "math", "python" ]
stackoverflow_0005812181_math_python.txt
Q: Draw text inside pylab figure window I want to add some more details about the calculations used to create a plot (histogram). How can I add some text that I can position anywhere I want in the figure window? A: Lots of ways to do this: text figtext annotate
Draw text inside pylab figure window
I want to add some more details about the calculations used to create a plot (histogram). How can I add some text that I can position anywhere I want in the figure window?
[ "Lots of ways to do this:\n\ntext \nfigtext \nannotate\n\n" ]
[ 10 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005812169_matplotlib_python.txt
Q: Python: has_key , I want to print the value of the key with if statement could you please help me with this. I want to print the value of the key with if statement. it is have one OR other value if it is not , but not for one , for all. my try: wp = {'tomatos': , 'patotoes': , 'milk':0.5'cheese':, 'eggs':0.25,'mea...
Python: has_key , I want to print the value of the key with if statement
could you please help me with this. I want to print the value of the key with if statement. it is have one OR other value if it is not , but not for one , for all. my try: wp = {'tomatos': , 'patotoes': , 'milk':0.5'cheese':, 'eggs':0.25,'meat':2} x= ' item is not available in this store' how I can make my output like...
[ "There are tons of ways to do what you are asking but the below would work:\nwp = { 'tomatos': None,\n 'patotoes': None ,\n 'milk':0.5,\n 'cheese': None, \n 'eggs':0.25,\n 'meat':2}\nx= ' item is not available in this store'\n\nfor k,v in wp.items():\n print \"%s%s\" % (k, (v if v is...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005812318_python.txt
Q: Google appengine rewrite question How can I rewrite url for python: http://localhost:8081/?page=1 to http://localhost:8081/1 here is my code, but it's not working: class MainPage(webapp.RequestHandler): def get(self, page): mypage = self.request.get('page') self.response.headers['Content-Type']...
Google appengine rewrite question
How can I rewrite url for python: http://localhost:8081/?page=1 to http://localhost:8081/1 here is my code, but it's not working: class MainPage(webapp.RequestHandler): def get(self, page): mypage = self.request.get('page') self.response.headers['Content-Type'] = 'text/plain' if mypage == ""...
[ "You can use regular expressions in your controller. It's not Apache-style URL rewriting per se, but it gets the job done. The rewritten parameter is passed as an argument to the handler.\nclass MyRequestHandler(webapp.RequestHandler):\n def get(self, page):\n self.response.headers['Content-Type'] = 'te...
[ 4, 1, 1 ]
[]
[]
[ "google_app_engine", "python", "rewrite" ]
stackoverflow_0005779879_google_app_engine_python_rewrite.txt
Q: Is there something like bpython for Ruby? IRb is pretty plain compared to bpython, even when using wirble. Is there any ruby equivalent of bpython? A: You can extend irb to achieve all of bpython's functionality and more with the right gems: wirble: for syntax highlightning (as you already know) bond: for more ...
Is there something like bpython for Ruby?
IRb is pretty plain compared to bpython, even when using wirble. Is there any ruby equivalent of bpython?
[ "You can extend irb to achieve all of bpython's functionality and more with the right gems:\n\nwirble: for syntax highlightning (as you already know)\nbond: for more advanced autocompletion\nutilitybelt: for pastebin-like commands\nsketches: for editing and evaluating code easily\nboson: command framework for creat...
[ 13, 12 ]
[]
[]
[ "bpython", "ide", "irb", "python", "ruby" ]
stackoverflow_0002952793_bpython_ide_irb_python_ruby.txt
Q: Why does pip install matplotlib version 0.91.1 when PyPi shows version 1.0.0? Update Oct 15, 2012 PyPi is now showing matplotlib at 1.1.0 so this issue is resolved. Install matplotlib via: pip install matplotlib Outdated Information Below PyPi shows matplotlib 1.0.0. However, when I install matplotlib via pip in...
Why does pip install matplotlib version 0.91.1 when PyPi shows version 1.0.0?
Update Oct 15, 2012 PyPi is now showing matplotlib at 1.1.0 so this issue is resolved. Install matplotlib via: pip install matplotlib Outdated Information Below PyPi shows matplotlib 1.0.0. However, when I install matplotlib via pip into a virtualenv, version 0.91.1 is installed. Why the difference in versions? Is t...
[ "I've experienced the same problem. I have no idea why it happens, but I do have a fix; use the -f option in pip to tell it where to find the matplotlib sources. (This works in requirements.txt as well).\npip install -f http://downloads.sourceforge.net/project/matplotlib/matplotlib/matplotlib-1.0/matplotlib-1.0.0.t...
[ 18, 11, 8, 3 ]
[]
[]
[ "matplotlib", "pip", "pypi", "python" ]
stackoverflow_0003555551_matplotlib_pip_pypi_python.txt
Q: Regexp matching equal number of the same character on each side of a string How do you match only equal numbers of the same character (up to 3) on each side of a string in python? For example, let's say I am trying to match equal signs =abc= or ==abc== or ===abc=== but not =abc== or ==abc= etc. I figured out how t...
Regexp matching equal number of the same character on each side of a string
How do you match only equal numbers of the same character (up to 3) on each side of a string in python? For example, let's say I am trying to match equal signs =abc= or ==abc== or ===abc=== but not =abc== or ==abc= etc. I figured out how to do each individual case, but can't seem to get all of them. (={1}(?=abc={1}))ab...
[ "Use the following regex:\n^(=+)abc\\1$\n\nEdit:\nIf you are talking about only max three =\n^(={1,3})abc\\1$\n\n", "This is not a regular language. However, you can do it with backreferences:\n(=+)[^=]+\\1\n\n", "consider that sample is a single string, here's a non-regex approach (out of many others)\n>>> str...
[ 4, 2, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005812942_python_regex.txt
Q: Can a method be used as either a staticmethod or instance method? I'd like to be able to do this: class A(object): @staticandinstancemethod def B(self=None, x, y): print self is None and "static" or "instance" A.B(1,2) A().B(1,2) This seems like a problem that should have a simple solution, but I...
Can a method be used as either a staticmethod or instance method?
I'd like to be able to do this: class A(object): @staticandinstancemethod def B(self=None, x, y): print self is None and "static" or "instance" A.B(1,2) A().B(1,2) This seems like a problem that should have a simple solution, but I can't think of or find one.
[ "It is possible, but please don't. I couldn't help but implement it though:\nclass staticandinstancemethod(object):\n def __init__(self, f):\n self.f = f\n\n def __get__(self, obj, klass=None):\n def newfunc(*args, **kw):\n return self.f(obj, *args, **kw)\n return ne...
[ 9, 0, 0 ]
[ "The answer to your question is no, you can't do that.\nWhat I would do, since Python also supports regular functions, is define a function outside that class, then call that function from a normal method. The caller can decide what which one is needed.\n" ]
[ -3 ]
[ "descriptor", "instance_methods", "python", "static_methods" ]
stackoverflow_0005812537_descriptor_instance_methods_python_static_methods.txt
Q: How to display the redirected stdin in Python? I'm starting on a Python project in which stdin redirection is necessary, using code similar to below: import sys import StringIO s = StringIO.StringIO("Hello") sys.stdin = s a = raw_input("Type something: ") sys.stdin = sys.__stdin__ print("You typed in: "+a) The p...
How to display the redirected stdin in Python?
I'm starting on a Python project in which stdin redirection is necessary, using code similar to below: import sys import StringIO s = StringIO.StringIO("Hello") sys.stdin = s a = raw_input("Type something: ") sys.stdin = sys.__stdin__ print("You typed in: "+a) The problem is, after the code runs, the following is dis...
[ "I'm not sure why you would need to, but you could always do this:\na = raw_input(\"Type something: \")\nif sys.stdin is not sys.__stdin__:\n print(a)\nprint(\"You typed in: \"+a)\n\nThen again, swapping raw_input for your own implementation as needed would probably make more sense.\nEdit: okay, based on your, c...
[ 3, 3, 1 ]
[]
[]
[ "python", "redirect", "stdin" ]
stackoverflow_0005812333_python_redirect_stdin.txt
Q: Access socket options for twisted.web.client.Agent How can i access underlying socket from twisted.web.client.Agent? I need to enable TCP_NODELAY on this socket. A: Unfortunately Agent doesn't make it as easy as it would be if you were working directly with a Protocol instance, but it's not impossible either. Th...
Access socket options for twisted.web.client.Agent
How can i access underlying socket from twisted.web.client.Agent? I need to enable TCP_NODELAY on this socket.
[ "Unfortunately Agent doesn't make it as easy as it would be if you were working directly with a Protocol instance, but it's not impossible either.\nThe key lies here, in the class definition of Agent:\n_protocol = HTTP11ClientProtocol\n\nIn order to get access to the transport you could override connectionMade on H...
[ 4 ]
[]
[]
[ "python", "twisted", "twisted.client", "twisted.web" ]
stackoverflow_0005811921_python_twisted_twisted.client_twisted.web.txt
Q: How can I authenticate users from Google Apps on internal web application? I was wondering what is the best way to authenticate a Google Apps user in an internal web application? I do not need to access their data like the two-legged authorization seam to do. I just want a user to use an internal application using...
How can I authenticate users from Google Apps on internal web application?
I was wondering what is the best way to authenticate a Google Apps user in an internal web application? I do not need to access their data like the two-legged authorization seam to do. I just want a user to use an internal application using their Google Apps credential.
[ "You can use Google Apps as an OpenID provider and the hosted accounts for identity by using OpenID API. This is also known as federated login. Your internal application then becomes an OpenID relying party.\nYou need to first enable OpenID from your Google Apps control panel -\nhttp://www.google.com/a/cpanel/your...
[ 0 ]
[]
[]
[ "authentication", "google_apps", "python" ]
stackoverflow_0005316606_authentication_google_apps_python.txt
Q: Is that possible to restore a text given unified diff and the original text with python What I want is to calculate the diff delta of two texts(original and new), store the original text the delta, then expect to restore the new text. So that I can store different versions of one text with minimum space. With Pyt...
Is that possible to restore a text given unified diff and the original text with python
What I want is to calculate the diff delta of two texts(original and new), store the original text the delta, then expect to restore the new text. So that I can store different versions of one text with minimum space. With Python's difflib, this could be done with ndiff and restore; however the delta of ndiff contains...
[ "I've found google-diff-match-patch which does exactly what I want.\n" ]
[ 3 ]
[]
[]
[ "diff", "python", "restore" ]
stackoverflow_0005807297_diff_python_restore.txt
Q: subprocess.Popen() stdin problems import subprocess import threading import StringIO class terminal(threading.Thread): def run(self): self.prompt() def prompt(self): x = True while x: command = raw_input(':') x = self.interpret(command) def interpret(s...
subprocess.Popen() stdin problems
import subprocess import threading import StringIO class terminal(threading.Thread): def run(self): self.prompt() def prompt(self): x = True while x: command = raw_input(':') x = self.interpret(command) def interpret(self,command): if command == 'ex...
[ "Here is a similar question:\nPython and subprocess input piping\nThe OP in this case is also running a jvm and expecting user input. I think you'd replace your while loop with a call to select((sys.stdin,),(),()). When select() returns you should have input to read from its return value and then pipe to your Pop...
[ 0, 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0005761315_python_subprocess.txt
Q: Can we shed some definitive light on how python packaging and import works? I had my fair chance of getting through the python management of modules, and every time is a challenge: packaging is not what people do every day, and it becomes a burden to learn, and a burden to remember, even when you actually do it, s...
Can we shed some definitive light on how python packaging and import works?
I had my fair chance of getting through the python management of modules, and every time is a challenge: packaging is not what people do every day, and it becomes a burden to learn, and a burden to remember, even when you actually do it, since this happens normally once. I would like to collect here the definitive over...
[ "For the most part, this is an attempt to look at the packaging/distribution side, not the mechanics of import. Unfortunately, packaging is the place where Python provides way more than one way to do it. I'm just trying to get the ball rolling, hopefully others will help fill what I miss or point out mistakes. \...
[ 11, 3, 2, 0 ]
[]
[]
[ "packaging", "python" ]
stackoverflow_0005714916_packaging_python.txt
Q: how to deal with my code error using python this is my code : a=[1,0,None,3] def b(my_list): for i in range(len(my_list)): if not my_list[i]: a.remove(my_list[i]) else: do_something() return my_list a = b(a) print a and the error is : Traceback (most recent call l...
how to deal with my code error using python
this is my code : a=[1,0,None,3] def b(my_list): for i in range(len(my_list)): if not my_list[i]: a.remove(my_list[i]) else: do_something() return my_list a = b(a) print a and the error is : Traceback (most recent call last): File "c.py", line 18, in <module> a =...
[ "You are modifying the same list that you're iterating over, inside your loop. You can fix this by making a copy of the list and returning that:\ndef b(my_list):\n new_list = my_list[:]\n for i in range(len(my_list)):\n if not my_list[i]:\n new_list.remove(my_list[i])\n else:\n ...
[ 3, 3, 1, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005812817_list_python.txt
Q: Filter a ValuesQuerySet by a string? I'm trying to achieve something like this by dynamically specifying the fields: my_model.objects.values('id', 'name') So I tried, my_string = 'id', 'name' my_model.objects.values(my_string) but it doesn't work. But, this works : my_string = 'name' my_model.objects.values(my_s...
Filter a ValuesQuerySet by a string?
I'm trying to achieve something like this by dynamically specifying the fields: my_model.objects.values('id', 'name') So I tried, my_string = 'id', 'name' my_model.objects.values(my_string) but it doesn't work. But, this works : my_string = 'name' my_model.objects.values(my_string) What am I doing wrong here ? Is th...
[ "Same as always.\nmy_string = 'id', 'name'\nmy_model.objects.values(*my_string)\n\n" ]
[ 4 ]
[]
[]
[ "django", "django_queryset", "filter", "python" ]
stackoverflow_0005814062_django_django_queryset_filter_python.txt
Q: Undefined boost python symbol: boost::python::detail::init_module I get an undefined symbol error when trying to import an extension compiled with boost python, and the symbol is one that should be included in the boost library. I am using Boost 1.46.1, Python 3.1.2, and GCC 4.4.5. I've built boost using: $ ./boot...
Undefined boost python symbol: boost::python::detail::init_module
I get an undefined symbol error when trying to import an extension compiled with boost python, and the symbol is one that should be included in the boost library. I am using Boost 1.46.1, Python 3.1.2, and GCC 4.4.5. I've built boost using: $ ./bootstrap.sh --with-python-version=3.1 $ sudo ./bjam -j4 install I then co...
[ "The undefined symbol is\nboost::python::detail::init_module(char const*, void (*)())\n\nnot \nboost::python::detail::init_module(PyModuleDef&, void (*)())\n\non http://www.boost.org/doc/libs/1_46_1/boost/python/module_init.hpp I see that the method signature has changed to the latter one in Python 3. \nYou should ...
[ 6 ]
[]
[]
[ "boost_python", "python", "python_3.x" ]
stackoverflow_0005810101_boost_python_python_python_3.x.txt
Q: How to designate where pygame creates the game window Is there any way to control where pygame creates the game screen? It seems to always create it in the same general area but not in a consistent location. A: import os os.environ['SDL_VIDEO_WINDOW_POS'] = str(position[0]) + "," + str(position[1]) as per ht...
How to designate where pygame creates the game window
Is there any way to control where pygame creates the game screen? It seems to always create it in the same general area but not in a consistent location.
[ "import os \n\nos.environ['SDL_VIDEO_WINDOW_POS'] = str(position[0]) + \",\" + str(position[1])\n\nas per http://pygame.org/wiki/FrequentlyAskedQuestions\nYou can also just center the screen with \nimport pygame, os \n\nos.environ['SDL_VIDEO_CENTERED'] = '1'\n\nNote that these should be done before you initialize ...
[ 24, 8 ]
[]
[]
[ "pygame", "python", "screen" ]
stackoverflow_0005814125_pygame_python_screen.txt
Q: Install Ming on WebFaction I'm trying to install the Ming SWF creation library from source on WebFaction. After untarring it, I ran ./configure --prefix=$HOME -enable--python and then ran make install. It seemed to install fine, but when I do a import ming from within Python it gives me an import error. These step...
Install Ming on WebFaction
I'm trying to install the Ming SWF creation library from source on WebFaction. After untarring it, I ran ./configure --prefix=$HOME -enable--python and then ran make install. It seemed to install fine, but when I do a import ming from within Python it gives me an import error. These steps worked for me on my local mach...
[ "Is the folder containing the library on Python's search path?\n" ]
[ 0 ]
[]
[]
[ "python", "webfaction" ]
stackoverflow_0005814290_python_webfaction.txt
Q: Python: Need to extract tag content from html page using regex, but not BeautifulSoup I have a requirement wherein I have to extract content inside <raw> tag. For example I need to extract abcd and efgh from this html snippet: <html><body><raw somestuff>abcd</raw><raw somesuff>efgh</raw></body></html> I used this...
Python: Need to extract tag content from html page using regex, but not BeautifulSoup
I have a requirement wherein I have to extract content inside <raw> tag. For example I need to extract abcd and efgh from this html snippet: <html><body><raw somestuff>abcd</raw><raw somesuff>efgh</raw></body></html> I used this code in my python re.match(r'.*raw.*(.*)/raw.*', DATA) But this is not returning any subst...
[ "Your company really needs to rethink their policy. Rewriting an XML parser is a complete waste of time, there are already several for Python. Some are included in the stdlib, so if you can import re you should also be allowed to import xml.etree.ElementTree or anything else listed at http://docs.python.org/library...
[ 5, 0 ]
[]
[]
[ "html", "python", "regex", "substring", "tags" ]
stackoverflow_0005814493_html_python_regex_substring_tags.txt
Q: returning additional context variables in Django I have a page that users can search for other users on and once they search, a list of users is displayed that match their search criteria. Next to each user in the search results, I have a link to "Add as friend'. Each link is linked to a python function in the url...
returning additional context variables in Django
I have a page that users can search for other users on and once they search, a list of users is displayed that match their search criteria. Next to each user in the search results, I have a link to "Add as friend'. Each link is linked to a python function in the urls.py file that will add the request to the database et...
[ "I didn't fully understand what variable you were missing in your code but to add variables to a context\nyou have render_to_response that is very handy. Either manually add what you need in the context dictionnary or use context_processors if you need the variables on you whole site.\n", "following code do the w...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005813314_django_python.txt
Q: How to get icon/icon's path of running app in linux/windows? I'd like to have a list of open windows and its icons and process it with python. I thought I was close with xprop and wmctrl, but I can't use it for my purpose. I can get a list of open windows with wmctrl -l, but no idea how get an icon/icon path for a...
How to get icon/icon's path of running app in linux/windows?
I'd like to have a list of open windows and its icons and process it with python. I thought I was close with xprop and wmctrl, but I can't use it for my purpose. I can get a list of open windows with wmctrl -l, but no idea how get an icon/icon path for any of the listed controls. Please, help :)
[ "You can use the module wnck and gtk.\nFor instance: \nimport pygtk \npygtk.require('2.0') \nimport gtk \nimport wnck \n\nscreen = wnck.screen_get_default() \n\nwhile gtk.events_pending(): \n gtk.main_iteration(False) \n\nfor w in screen.get_windows(): \n name = w.get_name() \n icon = w.get_icon(...
[ 2 ]
[]
[]
[ "icons", "python" ]
stackoverflow_0005810399_icons_python.txt
Q: multiprocessing + psycopg2 zombie children I am trying to insert and update a few million rows using psycopg and multiprocessing. Going by the documentation found in http://initd.org/psycopg/docs/usage.html#thread-and-process-safety, each child has its own connection to the DB. But during the course of execution, ...
multiprocessing + psycopg2 zombie children
I am trying to insert and update a few million rows using psycopg and multiprocessing. Going by the documentation found in http://initd.org/psycopg/docs/usage.html#thread-and-process-safety, each child has its own connection to the DB. But during the course of execution, only one child runs while the others become zomb...
[ "your processes become zombies because there jobs are finished but the processes are not joined.\nI reproduced your problem with this single test (I added sleep to simulate long jobs) : \nimport os\nimport time\nfrom multiprocessing import Process\n\ndef _target(args):\n print os.getpid(), os.getppid()\n time...
[ 0 ]
[]
[]
[ "multiprocessing", "psycopg2", "python", "zombie_process" ]
stackoverflow_0005794359_multiprocessing_psycopg2_python_zombie_process.txt
Q: How do I access user information with django with django-social-auth? My guess is that I am still able to use the user object to get the default information like email or user name. Is this correct? What if I would like to access some more information not specified on django default user object? A: If I remember...
How do I access user information with django with django-social-auth?
My guess is that I am still able to use the user object to get the default information like email or user name. Is this correct? What if I would like to access some more information not specified on django default user object?
[ "If I remember correctly they just use the default user model. So just like with the default user object you can create a profile model to store additional information. \n" ]
[ 1 ]
[]
[]
[ "django", "oauth", "python" ]
stackoverflow_0005814042_django_oauth_python.txt
Q: How are arguments in a configuration file parsed regardless of position? e.g. A configuration file can have CFLAGS = "xyz" CXXFLAGS = "xyz" OR CXXFLAGS = "xyz" CFLAGS = "xyz" Best implementation I could think of would be to just split the argument and feed the left side into a switch for line in file x = lin...
How are arguments in a configuration file parsed regardless of position?
e.g. A configuration file can have CFLAGS = "xyz" CXXFLAGS = "xyz" OR CXXFLAGS = "xyz" CFLAGS = "xyz" Best implementation I could think of would be to just split the argument and feed the left side into a switch for line in file x = line.split("=") switch(x[0]) case CFLAGS do cflags ...
[ "In Python just use the ConfigParser module which will parse .ini-like configuration files for you.\nRe implementing this yourself, I find it convenient to view configuration data as a kind of dictionary. This naturally translates to Python's dicts, so if I split the line to <key> = <value> I just go on and update:...
[ 4, 0 ]
[]
[]
[ "c", "python" ]
stackoverflow_0005815408_c_python.txt
Q: importing a module and altering the module behavior at import I want to import a module, but the import may behave differently depending on some external condition I want to impose. What are the strategies available to achieve this result ? example. I want a module foo.py. If I import foo I get a print of "hello" ...
importing a module and altering the module behavior at import
I want to import a module, but the import may behave differently depending on some external condition I want to impose. What are the strategies available to achieve this result ? example. I want a module foo.py. If I import foo I get a print of "hello" or "goodbye" depending on some external condition which is independ...
[ "You actually can access global variables of the main script from inside a module.\nIn the main script:\na = 42\nimport foo\n\nIn foo.py:\nimport __main__\nprint __main__.a\n\nNote that I only stated that this is possible :)\n", "A standard means of passing around data about the environment is to (naturally) use ...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005807062_python.txt
Q: BeautifulSoup getting href I have the following soup: <a href="some_url">next</a> <span class="class">...</span> From this I want to extract the href, "some_url" I can do it if I only have one tag, but here there are two tags. I can also get the text 'next' but that's not what I want. Also, is there a good descri...
BeautifulSoup getting href
I have the following soup: <a href="some_url">next</a> <span class="class">...</span> From this I want to extract the href, "some_url" I can do it if I only have one tag, but here there are two tags. I can also get the text 'next' but that's not what I want. Also, is there a good description of the API somewhere with ...
[ "You can use find_all in the following way to find every a element that has an href attribute, and print each one:\n# Python2\nfrom BeautifulSoup import BeautifulSoup\n \nhtml = '''<a href=\"some_url\">next</a>\n<span class=\"class\"><a href=\"another_url\">later</a></span>'''\n \nsoup = BeautifulSoup(html)\n...
[ 496 ]
[]
[]
[ "beautifulsoup", "python", "tags" ]
stackoverflow_0005815747_beautifulsoup_python_tags.txt
Q: Odd Column returns when scraping with lxml I am learning python and trying to build a scraper to glean parts data from a suppliers site. My issue now is that I am getting different column counts from my parsed table rows where I know that each row has the same column count. The issue has to be something I am overl...
Odd Column returns when scraping with lxml
I am learning python and trying to build a scraper to glean parts data from a suppliers site. My issue now is that I am getting different column counts from my parsed table rows where I know that each row has the same column count. The issue has to be something I am overlooking and after two days of trying different th...
[ "Usually when I run into a problem like this, I do two things:\n\nBreak the problem down into smaller chunks. Use python functions or classes to perform subsets of functionality so that you can test the functions individually for correctness.\nUse the Python Debugger to inspect the code as it runs to understand whe...
[ 0, 0, 0, 0 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0005789479_lxml_python.txt
Q: Python implementation of BLAST alignment algorithm? Is anyone aware of a pure python implementation of BLAST alignment? I am trying to study this algorithm... A: In fact a complete implementation of the BLAST algorithm is a quite hard. It has a lot of steps and optimizations. What could you do is: take a look o...
Python implementation of BLAST alignment algorithm?
Is anyone aware of a pure python implementation of BLAST alignment? I am trying to study this algorithm...
[ "In fact a complete implementation of the BLAST algorithm is a quite hard. It has a lot of steps and optimizations. What could you do is: take a look of the BLAST Book from O'Reilly, for a very good explanation, take a look of the NCBI Blast code base, that it is big and hard to understand at the first glace, or, I...
[ 3 ]
[ "Try looking into BioPython:\nhttp://biopython.org/\nhttp://github.com/JoaoRodrigues/biopython/tree/GSOC2010\n" ]
[ -1 ]
[ "alignment", "blast", "python" ]
stackoverflow_0003479569_alignment_blast_python.txt
Q: Django development - Accessing results from a model Once i have loaded my model and filtered it if i need to, how do i then access the results? I can find loads of examples on querying and filtering the model but none on how to work with the object thats returned? My model looks like this... class Ratecard(models....
Django development - Accessing results from a model
Once i have loaded my model and filtered it if i need to, how do i then access the results? I can find loads of examples on querying and filtering the model but none on how to work with the object thats returned? My model looks like this... class Ratecard(models.Model): region = models.CharField(max_length=32) ...
[ "If you wish to use instance, something like:\nreportSuite = Ratecard.objects.get(id=??)\nreportSuite.region\n\nreportSuite = Ratecard.objects.all()\nfor reportSuite in reportSuites:\n reportSuite.region\n\nBut if you wish to use the instance(es) in your page directly, you must do it in the template\nreturn rend...
[ 1 ]
[]
[]
[ "django", "django_models", "django_views", "php", "python" ]
stackoverflow_0005816142_django_django_models_django_views_php_python.txt
Q: Reusing SQLAlchemy models across projects I have some standard SQLAlchemy models that I reuse across projects. Something like this: from sqlalchemy import Column, Integer, String, Unicode from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Category(Base): __tablename__ = '...
Reusing SQLAlchemy models across projects
I have some standard SQLAlchemy models that I reuse across projects. Something like this: from sqlalchemy import Column, Integer, String, Unicode from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class Category(Base): __tablename__ = 'category' id = Column(Integer, primary_key...
[ "When you call\nBase = declarative_base()\nSA create new metadata for this Base.\nTo reuse your models you must bind metadata of main models to reusable models, but before any import of your reusable models by:\nBase.metadata = my_main_app.db.metadata\nMixIn classes useful for repeating column declarations, and ext...
[ 5 ]
[]
[]
[ "code_reuse", "python", "sqlalchemy" ]
stackoverflow_0005807694_code_reuse_python_sqlalchemy.txt
Q: Python: Error Freezing ctypes I get the following error trying to freeze a python script that imports ctypes: Warning: unknown modules remain: _bisect _ctypes _hashlib _heapq _locale _random _socket _ssl _struct _tkinter _weakref array binascii cStringIO collections datetime fcntl itertools math operator pyexpat ...
Python: Error Freezing ctypes
I get the following error trying to freeze a python script that imports ctypes: Warning: unknown modules remain: _bisect _ctypes _hashlib _heapq _locale _random _socket _ssl _struct _tkinter _weakref array binascii cStringIO collections datetime fcntl itertools math operator pyexpat readline select strop syslog termio...
[ "I suggest you use py2exe or something similar instead of freeze.\n" ]
[ 0 ]
[]
[]
[ "ctypes", "freeze", "python" ]
stackoverflow_0005794728_ctypes_freeze_python.txt
Q: Python a = a.reverse makes the list empty? At the interpreter, a = [1,2,3,4] a = a.reverse() Next when I type a at the interpreter, I get nothing. So it seems a = a.reverse() generates an empty list. Is this by design? I am using python 2.5 on windows xp. A: list.reverse() modifies the list in-place, returns No...
Python a = a.reverse makes the list empty?
At the interpreter, a = [1,2,3,4] a = a.reverse() Next when I type a at the interpreter, I get nothing. So it seems a = a.reverse() generates an empty list. Is this by design? I am using python 2.5 on windows xp.
[ "list.reverse() modifies the list in-place, returns None. But if you want to protect old list, you can use reversed() function for that, it returns an iterator.\nIn [1]: a=[1,2,3,4]\n\nIn [2]: print(a.reverse())\nNone\n\nIn [3]: a\nOut[3]: [4, 3, 2, 1]\n\nIn [4]: a=[1,2,3,4]\n\nIn [5]: print(reversed(a))\n<listreve...
[ 18, 6, 1, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005817067_python.txt
Q: Importing Python with extensions in C++ SOLVED: turns out I had a messed up path var in link script I have a problem concerning executing embedded python code in C++. I have a C++ program that dynamically executes a regular Python file using: ... PyObject_CallObject(func, args); ... Everything works as expected w...
Importing Python with extensions in C++
SOLVED: turns out I had a messed up path var in link script I have a problem concerning executing embedded python code in C++. I have a C++ program that dynamically executes a regular Python file using: ... PyObject_CallObject(func, args); ... Everything works as expected when I use plain function in the injected pyth...
[ "Imports in Python don't use quotes around the name.\nimport libraryname\n\nAlso, inject the module into sys.modules first.\n" ]
[ 4 ]
[]
[]
[ "c++", "linux", "python" ]
stackoverflow_0005817299_c++_linux_python.txt
Q: What is the pip equivalent to easy_install/ez_setup's --install-dir and --script-dir? We're using easy_install to install to a local build environment directory on windows. (This helps with having several checked out versions using different third-party packages simultaneously, etc. Sort of like virtualenv but fo...
What is the pip equivalent to easy_install/ez_setup's --install-dir and --script-dir?
We're using easy_install to install to a local build environment directory on windows. (This helps with having several checked out versions using different third-party packages simultaneously, etc. Sort of like virtualenv but for C/C++/Java/.NET too. :) By using --install-dir I can get the python packages into a path ...
[ "--install-dir is possible to emulate using --install-purelib and --install-platlib:\nLike this:\n--install-option=--install-purelib=<installdir>\n--install-option=--install-platlib=<installdir>\n\nNote that specifying double-quotes (\") around the install option as SteveMc did in the comment does not work when ca...
[ 0 ]
[]
[]
[ "easy_install", "pip", "python" ]
stackoverflow_0005650035_easy_install_pip_python.txt
Q: wingide feature Does wingide have an eclipse-like open resource feature (ctrl+shift+r)? A: Found the solution: ctrl+shift+o.
wingide feature
Does wingide have an eclipse-like open resource feature (ctrl+shift+r)?
[ "Found the solution: ctrl+shift+o. \n" ]
[ 1 ]
[]
[]
[ "eclipse", "python", "wing_ide" ]
stackoverflow_0005817519_eclipse_python_wing_ide.txt
Q: confidence interval with leastsq fit in scipy python How to calculate confidence interval for the least square fit (scipy.optimize.leastsq) in python? A: I would use bootstrapping method. See here: http://phe.rockefeller.edu/LogletLab/whitepaper/node17.html Simple example for noisy gaussian: x = arange(-10, 10, ...
confidence interval with leastsq fit in scipy python
How to calculate confidence interval for the least square fit (scipy.optimize.leastsq) in python?
[ "I would use bootstrapping method.\nSee here: http://phe.rockefeller.edu/LogletLab/whitepaper/node17.html\nSimple example for noisy gaussian:\nx = arange(-10, 10, 0.01)\n\n# model function\ndef f(p):\n mu, s = p\n return exp(-(x-mu)**2/(2*s**2))\n\n# create error function for dataset \ndef fff(d):\n def...
[ 8, 4, 2 ]
[]
[]
[ "confidence_interval", "least_squares", "python", "scipy" ]
stackoverflow_0005811043_confidence_interval_least_squares_python_scipy.txt
Q: Executing a script in windows and locking down a script I have two brief question: Is there a way that I can click on my script and get the cmd prompt to start (I'm using Python cmd; a command line in dos)? Can I lock down my script so no one can look at it, or at least change anything? Cheers! A: It seems you...
Executing a script in windows and locking down a script
I have two brief question: Is there a way that I can click on my script and get the cmd prompt to start (I'm using Python cmd; a command line in dos)? Can I lock down my script so no one can look at it, or at least change anything? Cheers!
[ "It seems you are shipping your code to third parties. If you don't want them to look at your code you can create a frozen binary. This creates a .exe that can't be just opened with notepad and edited.\nNote that this isn't a very secure way, they can still extract the code out of it, if they are skilled.\n" ]
[ 1 ]
[]
[]
[ "python", "security", "windows" ]
stackoverflow_0005817977_python_security_windows.txt
Q: Pattern for associating pyparsing results with a linked-list of nodes I have defined a pyparsing rule to parse this text into a syntax-tree... TEXT COMMANDS: add Iteration name = "Cisco 10M/half" append Observation name = "packet loss 1" assign Observation results_text = 0.0 assign Observation ...
Pattern for associating pyparsing results with a linked-list of nodes
I have defined a pyparsing rule to parse this text into a syntax-tree... TEXT COMMANDS: add Iteration name = "Cisco 10M/half" append Observation name = "packet loss 1" assign Observation results_text = 0.0 assign Observation results_bool = True append DataPoint assign DataPoint m...
[ "I am not aware of an actual design pattern for what you're looking for, but I have a great passion for the issue at hand. I work heavily with network devices and parsing and organizing the data is a large ongoing challenge for me.\nIt's clear that the problem is not parsing the data, but what you do with it afterw...
[ 1, 1 ]
[]
[]
[ "design_patterns", "linked_list", "parsing", "pyparsing", "python" ]
stackoverflow_0005627234_design_patterns_linked_list_parsing_pyparsing_python.txt
Q: Python CGI - GET form, typing in an address in browser giving the correct page I'm trying to make a website using python with CGI. This website is very basic, all it has is login, logout and display data from a database using sqlite. I was wondering how would I create a hyperlink to a page displaying a message ret...
Python CGI - GET form, typing in an address in browser giving the correct page
I'm trying to make a website using python with CGI. This website is very basic, all it has is login, logout and display data from a database using sqlite. I was wondering how would I create a hyperlink to a page displaying a message returned from the database using a GET form with no submit button? The hyperlink would ...
[ "A URL is a URL. It doesn't matter if you generate it by typing it in, clicking a link, or submitting a form (with method=GET).\n<a href=\"http://www.test.com/cgi-bin/test.py?message=22\">…</a>\n\n\nUpdate based on the understanding that the question is actually:\n\nHow do I read the query string in a CGI script wr...
[ 2 ]
[]
[]
[ "cgi", "html", "python", "sqlite" ]
stackoverflow_0005818444_cgi_html_python_sqlite.txt
Q: magic function %hist not found Mac OSX I'm using ipython on Mac OS X Snow leopard and for some reason I get an error when I use the hist magic function, even when giving it as %hist. When I give hist I get a python NameError and when I give %hist I get an ipython error ERROR: Magic function 'hist' not found. I c...
magic function %hist not found Mac OSX
I'm using ipython on Mac OS X Snow leopard and for some reason I get an error when I use the hist magic function, even when giving it as %hist. When I give hist I get a python NameError and when I give %hist I get an ipython error ERROR: Magic function 'hist' not found. I can see the history file in the .ipython fold...
[ "Which version of IPython are you using?\nAccording to the interactive manual, \"As of the 0.11 version of IPython, some of the features and APIs described in this section have been deprecated or are broken. Our plan is to continue to support these features, but they need to be updated to take advantage of recent A...
[ 2 ]
[]
[]
[ "ipython", "ipython_magic", "python" ]
stackoverflow_0005817589_ipython_ipython_magic_python.txt