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: SQLAlchemy autocommiting? I have an issue with SQLAlchemy apparently committing. A rough sketch of my code: trans = self.conn.begin() try: assert not self.conn.execute(my_obj.__table__.select(my_obj.id == id)).first() self.conn.execute(my_obj.__table__.insert().values(id=id)) assert not se...
SQLAlchemy autocommiting?
I have an issue with SQLAlchemy apparently committing. A rough sketch of my code: trans = self.conn.begin() try: assert not self.conn.execute(my_obj.__table__.select(my_obj.id == id)).first() self.conn.execute(my_obj.__table__.insert().values(id=id)) assert not self.conn.execute(my_obj.__table_...
[ "You're right in that changes aren't get commited to DB. But they are auto-flushed by SQLAlchemy when you perform query, in your case flush is performed on lines with asserts. So if you will not explicitly call commit you will never see these changes in DB, within real data. However, you will get them back as long ...
[ 1 ]
[]
[]
[ "python", "sqlalchemy", "transactions" ]
stackoverflow_0002432527_python_sqlalchemy_transactions.txt
Q: Google OAuth and local dev i am trying to use Google OAuth to import a user 's contacts. In order to get a consumer and secret key for you app you have to verify your domain at https://www.google.com/accounts/ManageDomains Google allows you to use only domains without ports. I want to test and build the app locall...
Google OAuth and local dev
i am trying to use Google OAuth to import a user 's contacts. In order to get a consumer and secret key for you app you have to verify your domain at https://www.google.com/accounts/ManageDomains Google allows you to use only domains without ports. I want to test and build the app locally so usually (Facebook, Linkedin...
[ "well after trial and error i found out that the request 's domain is irrelevant\n", "i just use the official gdata google auth library http://code.google.com/p/gdata-python-client\nHere is some code\n google_auth_url = None\n if not current_user.gmail_authorized:\n google = gdata.contacts.service.Co...
[ 4, 3 ]
[]
[]
[ "google_contacts_api", "oauth", "python" ]
stackoverflow_0002410559_google_contacts_api_oauth_python.txt
Q: Getting values from Multiple Text Entry using Pygtk and Python On a click of a button named "Add Textbox" it calls a function which creates a single textbox using (gtk.Entry) function. So each time i click that button it creates a textbox. I have a submit button which should fetches all the values of the text boxe...
Getting values from Multiple Text Entry using Pygtk and Python
On a click of a button named "Add Textbox" it calls a function which creates a single textbox using (gtk.Entry) function. So each time i click that button it creates a textbox. I have a submit button which should fetches all the values of the text boxes(say 10 textboxes) generated with the name of "entry". It works for...
[ "You could be a bit clearer, it's not obvious what you do with your GtkEntry after creating it. The easiest thing would be to just add it to a Python list, so you can iterate over all created GtkEntry widgets later.\nOr, you could \"tag\" the widgets with something to make them identifiable, and iterate over the co...
[ 1 ]
[]
[]
[ "glade", "gtk", "pygtk", "python" ]
stackoverflow_0002432468_glade_gtk_pygtk_python.txt
Q: can we display glass bar chart in python with google app engine i am using bar chat and i want to use glass bar chart instead of that tutorials are given for PHP only. A: Disclaimer: I don't know, what is "glass bar chart". You cannot (or at least it is not effective to) generate graphics (charts) on the AppEngi...
can we display glass bar chart in python with google app engine
i am using bar chat and i want to use glass bar chart instead of that tutorials are given for PHP only.
[ "Disclaimer: I don't know, what is \"glass bar chart\".\nYou cannot (or at least it is not effective to) generate graphics (charts) on the AppEngine servers. However, if you want to display bar charts or any other kind of plots and charts in your AppEngine applications, you have two other solutions:\nA) Use an exte...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0002430748_python.txt
Q: What is a faster way of merging the values of this Python structure into a single dictionary? I've refactored how the merged-dictionary (all_classes) below is created, but I'm wondering if it can be more efficient. I have a dictionary of dictionaries, like this: groups_and_classes = {'group_1': {'class_A': [1, 2, ...
What is a faster way of merging the values of this Python structure into a single dictionary?
I've refactored how the merged-dictionary (all_classes) below is created, but I'm wondering if it can be more efficient. I have a dictionary of dictionaries, like this: groups_and_classes = {'group_1': {'class_A': [1, 2, 3], 'class_B': [1, 3, 5, 7], '...
[ "Here's a tweak for conciseness, though I'm not sure about performance:\nfrom collections import defaultdict\nall_classes = defaultdict(set)\nfor group in groups_and_classes.values():\n for c, vals in group.iteritems():\n all_classes[c].update(set(vals))\n\nDefaultdicts are not quite the greatest thing si...
[ 4, 2, 2 ]
[]
[]
[ "data_structures", "performance", "python", "refactoring" ]
stackoverflow_0002433027_data_structures_performance_python_refactoring.txt
Q: how to read url data from google.appengine.ext import webapp from google.appengine.ext.webapp import util from google.appengine.ext import db from google.appengine.api import urlfetch class TrakHtml(db.Model): hawb = db.StringProperty(required=False) htmlData = db.TextProperty() class MainHandler(webapp.Requ...
how to read url data
from google.appengine.ext import webapp from google.appengine.ext.webapp import util from google.appengine.ext import db from google.appengine.api import urlfetch class TrakHtml(db.Model): hawb = db.StringProperty(required=False) htmlData = db.TextProperty() class MainHandler(webapp.RequestHandler): def get(sel...
[ "You have read the result twice (once in self.responce.out.write and once a line below).\nStore the value as a string first:\nhtmlData = result.read()\nself.response.out.write(htmlData)\ntrak.htmlData = htmlData\n\nI would expect result.read() to move to the end of the result stream - think of it like a book: Readi...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0002433216_python.txt
Q: Any downsides to UPX-ing my 32-bit Python 2.6.4 development environment EXE/PYD/DLL files? Are there any downsides to UPX-ing my 32-bit Python 2.6.4 development environment EXE/PYD/DLL files? The reason I'm asking is that I frequently use a custom PY2EXE script that UPX's copies of these files on every build. Yes,...
Any downsides to UPX-ing my 32-bit Python 2.6.4 development environment EXE/PYD/DLL files?
Are there any downsides to UPX-ing my 32-bit Python 2.6.4 development environment EXE/PYD/DLL files? The reason I'm asking is that I frequently use a custom PY2EXE script that UPX's copies of these files on every build. Yes, I could get fancy and try to cache UPXed files, but I think a simpler, safer, and higher perfor...
[ "I have experienced significant increases in start up time when UPX compressed executables are run on systems with certain virus scanners. I was only compressing single executables, but I expect that each compressed dll would add to the start time.\nIs it really necessary to use UPX? I can't imagine the space sav...
[ 2 ]
[]
[]
[ "py2exe", "python", "upx" ]
stackoverflow_0002431236_py2exe_python_upx.txt
Q: Many producer, single consumer with python/mod_wsgi I have a Pylons web application served by Apache (mod_wsgi, prefork). Because of Apache, there are multiple separate processes running my application code concurrently. Some of the non-critical tasks that the application does I want to defer for processing in bac...
Many producer, single consumer with python/mod_wsgi
I have a Pylons web application served by Apache (mod_wsgi, prefork). Because of Apache, there are multiple separate processes running my application code concurrently. Some of the non-critical tasks that the application does I want to defer for processing in background to improve "live" response times. So I'm thinking...
[ "A message broker like Apache's ActiveMQ is an ideal solution here.\nThe pipeline could be following:\n\nApplication process that is responsible for handling HTTP requests generates replies quickly and sends low-priority, heavy tasks to AMQ queue.\nOne or more another processes are subscribed to consume AMQ queue a...
[ 1, 0 ]
[]
[]
[ "apache", "concurrency", "producer", "python", "synchronization" ]
stackoverflow_0002432956_apache_concurrency_producer_python_synchronization.txt
Q: vectorize is indeterminate I'm trying to vectorize a simple function in numpy and getting inconsistent behavior. I expect my code to return 0 for values < 0.5 and the unchanged value otherwise. Strangely, different runs of the script from the command line yield varying results: sometimes it works correctly, and...
vectorize is indeterminate
I'm trying to vectorize a simple function in numpy and getting inconsistent behavior. I expect my code to return 0 for values < 0.5 and the unchanged value otherwise. Strangely, different runs of the script from the command line yield varying results: sometimes it works correctly, and sometimes I get all 0's. It do...
[ "If this really is the problem you want to solve, then there's a much better solution:\nA[A<=0.5] = 0.0\n\nThe problem with your code, however, is that if the condition passes, you are returning the integer 0, not the float 0.0. From the documentation:\n\nThe data type of the output of vectorized is determined by c...
[ 7 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002433587_numpy_python.txt
Q: Python Libraries and drivers I have no knowledge of Python. I started with .NET and than learned PHP. Someone later asked me to learn Ruby as well. I started learning it. Since last few months I am seeing many libraries and drivers written in Python. I want to know what are the advantages of Python over PHP/Ruby? ...
Python Libraries and drivers
I have no knowledge of Python. I started with .NET and than learned PHP. Someone later asked me to learn Ruby as well. I started learning it. Since last few months I am seeing many libraries and drivers written in Python. I want to know what are the advantages of Python over PHP/Ruby? What type of language it is and is...
[ "Nobody can tell you the exact answer because everybody has their own \"holy grail\". You will just have to find out for yourself which one suits you best for the task you want to perform. Case closed.\n", "If you're just getting started in python, chances are the standard python distribution will work just fine....
[ 1, 1 ]
[]
[]
[ "php", "python", "ruby" ]
stackoverflow_0002395157_php_python_ruby.txt
Q: SQLAlchemy - full load instance before detach is there a way how to fully load some SQLAlchemy ORM mapped instance (together with its related objects) before detaching it from the Session? I want to send it via pipe into another processs and I don't want to merge it into session in this new process. Thank you Jan ...
SQLAlchemy - full load instance before detach
is there a way how to fully load some SQLAlchemy ORM mapped instance (together with its related objects) before detaching it from the Session? I want to send it via pipe into another processs and I don't want to merge it into session in this new process. Thank you Jan
[ "I believe you'll want to use the options() method on the Query, with eagerload() or eagerload_all().\nHere's an example of use from one of our apps, where the class Controlled has a relation called changes which brings in a bunch of DocumentChange records, which themselves have a relation dco that brings in one Dc...
[ 2 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002432941_python_sqlalchemy.txt
Q: Python ImportError when executing 'import.py', but not when executing 'python import.py' I am running Cygwin Python version 2.5.2. I have a three-line source file, called import.py: #!/usr/bin/python import xml.etree.ElementTree as ET print "Success!" When I execute "python import.py", it works: C:\Temp>python im...
Python ImportError when executing 'import.py', but not when executing 'python import.py'
I am running Cygwin Python version 2.5.2. I have a three-line source file, called import.py: #!/usr/bin/python import xml.etree.ElementTree as ET print "Success!" When I execute "python import.py", it works: C:\Temp>python import.py Success! When I run the python interpreter and type the commands, it works: C:\Temp>p...
[ "I have the feeling that \nC:\\Temp>import.py\n\nuses a different interpreter. Can you try with the following scripts:\n#!/usr/bin/env python\nimport sys\nprint sys.executable\nimport xml.etree.ElementTree as ET\nprint \"Success!\"\n\n", "Probably py extension is connected to some other python interpreter than th...
[ 4, 1, 0, 0 ]
[]
[]
[ "import", "python" ]
stackoverflow_0002433703_import_python.txt
Q: Hide filter items that produce zero results in django-filter I have an issue with the django-filter application: how to hide the items that will produce zero results. I think that there is a simple method to do this, but idk how. I'm using the LinkWidget on a ModelChoiceFilter, like this: provider = django_filters...
Hide filter items that produce zero results in django-filter
I have an issue with the django-filter application: how to hide the items that will produce zero results. I think that there is a simple method to do this, but idk how. I'm using the LinkWidget on a ModelChoiceFilter, like this: provider = django_filters.ModelChoiceFilter(queryset=Provider.objects.all(), widget=dj...
[ "Basically, you need to apply filters, and then apply them again, but on newly-generated queryset. Something like this:\nf = SomeFilter(request.GET) \nf = SomeFilter(request.GET, queryset=f.qs)\n\nNow when you have correct queryset, you can override providers dynamically in init:\ndef __init__(self, **kw):\n supe...
[ 3, 0, 0 ]
[]
[]
[ "django", "django_filter", "filter", "python" ]
stackoverflow_0002183008_django_django_filter_filter_python.txt
Q: How do constructors and destructors work? I'm trying to understand this code: class Person: '''Represents a person ''' population = 0 def __init__(self,name): //some statements and population += 1 def __del__(self): //some statements and population -= 1 def sayHi(self): ...
How do constructors and destructors work?
I'm trying to understand this code: class Person: '''Represents a person ''' population = 0 def __init__(self,name): //some statements and population += 1 def __del__(self): //some statements and population -= 1 def sayHi(self): '''grettings from person''' print...
[ "Here is a slightly opinionated answer.\nDon't use __del__. This is not C++ or a language built for destructors. The __del__ method really should be gone in Python 3.x, though I'm sure someone will find a use case that makes sense. If you need to use __del __, be aware of the basic limitations per http://docs.pyt...
[ 22, 1 ]
[]
[]
[ "class", "destructor", "python" ]
stackoverflow_0002433130_class_destructor_python.txt
Q: Match multiline regex in file object How can I extract the groups from this regex from a file object (data.txt)? import numpy as np import re import os ifile = open("data.txt",'r') # Regex pattern pattern = re.compile(r""" ^Time:(\d{2}:\d{2}:\d{2}) # Time: 12:34:56 at beginning of line ...
Match multiline regex in file object
How can I extract the groups from this regex from a file object (data.txt)? import numpy as np import re import os ifile = open("data.txt",'r') # Regex pattern pattern = re.compile(r""" ^Time:(\d{2}:\d{2}:\d{2}) # Time: 12:34:56 at beginning of line \r{2} # Two c...
[ "You can read the data from the file object into a string with ifile.read()\n", "times = [match.group(1) for match in pattern.finditer(ifile.read())]\n\nfinditer yield MatchObjects. If the regex doesn't match anything times will be an empty list.\nYou can also modify your regex to use non-capturing groups for sto...
[ 5, 2, 1 ]
[]
[]
[ "multiline", "python", "regex" ]
stackoverflow_0002433648_multiline_python_regex.txt
Q: What is the difference between trapping and handling an exception? I'm looking into exception handling in python and a blog post I read differentiated between trapping and handling an exception. Can someone explain the core difference between these two, both in python specifically and the overall conceptual differ...
What is the difference between trapping and handling an exception?
I'm looking into exception handling in python and a blog post I read differentiated between trapping and handling an exception. Can someone explain the core difference between these two, both in python specifically and the overall conceptual difference? A google search for 'exception trapping handling' isn't super-usef...
[ "I would say that \"trapping\" and \"catching\" an exception are the same thing: you have to trap/catch it to be able to handle it, but the act of trapping it is not the same as handling it. \nTrapping-but-not-handling = supressing, in other words. Handling implies that you actually do something with the informatio...
[ 3, 0 ]
[]
[]
[ "exception_handling", "python" ]
stackoverflow_0002433816_exception_handling_python.txt
Q: Trying to write to binary plist format from Python (w/PyObjC) to be fetch and read in by Cocoa Touch I'm trying to serve a property list of search results to my iPhone app. The server is a prototype, written in Python. First I found Python's built-in plistlib, which is awesome. I want to give search-as-you-type a ...
Trying to write to binary plist format from Python (w/PyObjC) to be fetch and read in by Cocoa Touch
I'm trying to serve a property list of search results to my iPhone app. The server is a prototype, written in Python. First I found Python's built-in plistlib, which is awesome. I want to give search-as-you-type a shot, so I need it to be as small as possible, and xml was too big. The binary plist format seems like a g...
[ "I believe the correct function name is\nNSPropertyListSerialization.dataWithPropertyList_format_options_error_\n\nbecause of the ending :. \n(BTW, if the object is always an array or dictionary, -writeToFile:atomically: will write the plist (as XML format) already.)\n", "As KennyTM said, you're missing the trail...
[ 4, 2 ]
[]
[]
[ "cocoa_touch", "pyobjc", "python", "search" ]
stackoverflow_0002346463_cocoa_touch_pyobjc_python_search.txt
Q: Odd nested dictionary behavior in python Im new two python and am trying to grow a dictionary of dictionaries. I have done this in php and perl but python is behaving very differently. Im sure it makes sense to those more familiar with python. Here is my code: colnames = ['name','dob','id']; tablehashcopy = {}; ta...
Odd nested dictionary behavior in python
Im new two python and am trying to grow a dictionary of dictionaries. I have done this in php and perl but python is behaving very differently. Im sure it makes sense to those more familiar with python. Here is my code: colnames = ['name','dob','id']; tablehashcopy = {}; tablehashcopy = dict.fromkeys(colnames,{}); tab...
[ "The issue is with your fromkeys call. You passed it an empty dictionary, and it used that exact same empty dictionary as the value for all of the keys. Since the exact same dictionary is being used as the value, adding an element to it means you'll see that same element for all the keys' dictionaries.\n", "As ms...
[ 3, 2, 1, 1 ]
[]
[]
[ "dictionary", "nested", "python" ]
stackoverflow_0002433805_dictionary_nested_python.txt
Q: EOL character in Linux and Windows I'm writing a simple script, that just connects to telnet port, listens everything on it, staying connected and when some string, for example '123' appears, script do something. I use tn.read_until("123", 2), but when '123' appears, script just disconnects. How to make it stay o...
EOL character in Linux and Windows
I'm writing a simple script, that just connects to telnet port, listens everything on it, staying connected and when some string, for example '123' appears, script do something. I use tn.read_until("123", 2), but when '123' appears, script just disconnects. How to make it stay online?
[ "Put tn.read_until(\"123\", 2) in a loop.\n", "You can try this:\nimport socket\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind(('', 21))\ns.listen(1)\nconn = s.accept()\nrun = True\nwhile run==True:\n data = conn.recv(1000)\n if data == '123':\n #do something\n else:\n #do...
[ 1, 0 ]
[]
[]
[ "python", "telnet" ]
stackoverflow_0002433293_python_telnet.txt
Q: Object for storing strings in Python class MyWriter: def __init__(self, stdout): self.stdout = stdout self.dumps = [] def write(self, text): self.stdout.write(smart_unicode(text).encode('cp1251')) self.dumps.append(text) def close(self): self.stdout.close() ...
Object for storing strings in Python
class MyWriter: def __init__(self, stdout): self.stdout = stdout self.dumps = [] def write(self, text): self.stdout.write(smart_unicode(text).encode('cp1251')) self.dumps.append(text) def close(self): self.stdout.close() writer = MyWriter(sys.stdout) save = sys...
[ "A list of strings to be joined with ''.join is just fine. However, if you prefer a more direct solution:\nimport cStringIO\n\nclass MyWriter(object):\n\n def __init__(self, stdout):\n self.stdout = stdout\n self.dumps = cStringIO.StringIO()\n self.final = None\n\n def write(self, text):...
[ 2, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0002433194_python_string.txt
Q: error in fetching url data from google.appengine.ext import webapp from google.appengine.ext.webapp import util from google.appengine.ext import db from google.appengine.api import urlfetch class TrakHtml(db.Model): hawb = db.StringProperty(required=False) htmlData = db.TextProperty() class MainHandler(webap...
error in fetching url data
from google.appengine.ext import webapp from google.appengine.ext.webapp import util from google.appengine.ext import db from google.appengine.api import urlfetch class TrakHtml(db.Model): hawb = db.StringProperty(required=False) htmlData = db.TextProperty() class MainHandler(webapp.RequestHandler): def get(sel...
[ "you call result.read() twice. That's probably why it's fragmented.\n", "This link has info on the return value of urlfetch.fetch(url)\nhttp://code.google.com/appengine/docs/python/urlfetch/responseobjects.html\nIt looks like you want to do result.content.read()\n", "I note that you are calling read() twice, wh...
[ 1, 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002434119_google_app_engine_python.txt
Q: How can I set controls for a web page? I have this login page with https, and i reach to this approach:: import ClientForm import urllib2 request = urllib2.Request("http://ritaj.birzeit.edu") response = urllib2.urlopen(request) forms = ClientForms.ParseResponseEx(response) response.close() f = forms[0] username ...
How can I set controls for a web page?
I have this login page with https, and i reach to this approach:: import ClientForm import urllib2 request = urllib2.Request("http://ritaj.birzeit.edu") response = urllib2.urlopen(request) forms = ClientForms.ParseResponseEx(response) response.close() f = forms[0] username = str(raw_input("Username: ")) password = st...
[ "You set f['username'] = username and f['password'] = password, and when you f.click() you'll get a response that you'll need to examine in order to determine whether those strings were the ones the site you're visiting expected -- how the site communicates that depends on the site, it should use an HTTP status for...
[ 1 ]
[]
[]
[ "browser", "python" ]
stackoverflow_0002434126_browser_python.txt
Q: Python to MATLAB: exporting list of strings using scipy.io I am trying to export a list of text strings from Python to MATLAB using scipy.io. I would like to use scipy.io because my desired .mat file should include both numerical matrices (which I learned to do here) and text cell arrays. I tried: import scipy.io ...
Python to MATLAB: exporting list of strings using scipy.io
I am trying to export a list of text strings from Python to MATLAB using scipy.io. I would like to use scipy.io because my desired .mat file should include both numerical matrices (which I learned to do here) and text cell arrays. I tried: import scipy.io my_list = ['abc', 'def', 'ghi'] scipy.io.savemat('test.mat', mdi...
[ "You need to make my_list an array of numpy objects:\nimport scipy.io\nimport numpy as np\nmy_list = np.zeros((3,), dtype=np.object)\nmy_list[:] = ['abc', 'def', 'ghi']\nscipy.io.savemat('test.mat', mdict={'my_list': my_list})\n\nThen it will be saved in a cell format. There might be a better way of putting it into...
[ 13, 1 ]
[]
[]
[ "mat_file", "matlab", "python", "scipy", "string" ]
stackoverflow_0002433924_mat_file_matlab_python_scipy_string.txt
Q: A RAM error of big array I need to get the numbers of one line randomly, and put each line in other array, then get the numbers of one col. I have a big file, more than 400M. In that file, there are 13496*13496 number, means 13496 rows and 13496 cols. I want to read them to a array. This is my code: _L1 = [[0 for ...
A RAM error of big array
I need to get the numbers of one line randomly, and put each line in other array, then get the numbers of one col. I have a big file, more than 400M. In that file, there are 13496*13496 number, means 13496 rows and 13496 cols. I want to read them to a array. This is my code: _L1 = [[0 for col in range(13496)] for row i...
[ "you might want to approach your problem in another way. Process the file line by line. I don't see a need to store the whole big file into array. Otherwise, you might want to tell us what you are actually trying to do.\nfor line in open(\"400MB_file\"):\n # do something with line.\n\nOr \nf=open(\"file\")\nfor...
[ 7, 3, 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002432521_python.txt
Q: Finding unique maximum values in a list using python I have a list of points as shown below points=[ [x0,y0,v0], [x1,y1,v1], [x2,y2,v2].......... [xn,yn,vn]] Some of the points have duplicate x,y values. What I want to do is to extract the unique maximum value x,y points For example, if I have points [1,2,5] ...
Finding unique maximum values in a list using python
I have a list of points as shown below points=[ [x0,y0,v0], [x1,y1,v1], [x2,y2,v2].......... [xn,yn,vn]] Some of the points have duplicate x,y values. What I want to do is to extract the unique maximum value x,y points For example, if I have points [1,2,5] [1,1,3] [1,2,7] [1,7,3] I would like to obtain the list [1...
[ "For example:\nimport itertools\n\ndef getxy(point): return point[:2]\n\nsortedpoints = sorted(points, key=getxy)\n\nresults = []\n\nfor xy, g in itertools.groupby(sortedpoints, key=getxy):\n results.append(max(g, key=operator.itemgetter(2)))\n\nthat is: sort and group the points by xy, for every group with fixed ...
[ 9, 0, 0 ]
[]
[]
[ "python", "set", "unique" ]
stackoverflow_0002434251_python_set_unique.txt
Q: Last matching symbol in Regex I couldn't find a more descriptive title, but here there is an example: import re m = re.search(r"\((?P<remixer>.+) (Remix)\)", "Title (Menda Remix)") m.group("remixer") # returns 'Menda' OK m = re.search(r"\((?P<remixer>.+) (Remix)\)", "Title (Blabla) (Menda Remix)") m.group("remixer...
Last matching symbol in Regex
I couldn't find a more descriptive title, but here there is an example: import re m = re.search(r"\((?P<remixer>.+) (Remix)\)", "Title (Menda Remix)") m.group("remixer") # returns 'Menda' OK m = re.search(r"\((?P<remixer>.+) (Remix)\)", "Title (Blabla) (Menda Remix)") m.group("remixer") # returns 'Blabla) (Menda' FAIL ...
[ "re.search(r\"\\((?P<remixer>[^)]+) (Remix)\\)\", \"Title (Blabla) (Menda Remix)\")\n\n", "Use [^()]+ instead of .+ to not to match the parenthesis.\n", "I would probably do this:\nm = re.search(r\".*\\((?P<remixer>.+) (Remix)\\)\", \"Title (Blabla) (Menda Remix)\")\n\n", "Just add a $ to the end of the patte...
[ 3, 1, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002434749_python_regex.txt
Q: How to get path to the installed GIT in Python? I need to get a path to the GIT on Max OS X 10.6 using Python 2.6.1 into script variables. I use this code for that: r = subprocess.Popen(shlex.split("which git"), stdout=subprocess.PIPE) print r.stdout.read() but the problem is that output is empty (I tried stderr ...
How to get path to the installed GIT in Python?
I need to get a path to the GIT on Max OS X 10.6 using Python 2.6.1 into script variables. I use this code for that: r = subprocess.Popen(shlex.split("which git"), stdout=subprocess.PIPE) print r.stdout.read() but the problem is that output is empty (I tried stderr too). It works fine with another commands such as pwd...
[ "All which does is iterate over the directories in $PATH, checking to see if the file is there. Just write a small method to do likewise.\n" ]
[ 2 ]
[]
[]
[ "osx_snow_leopard", "python", "subprocess" ]
stackoverflow_0002435015_osx_snow_leopard_python_subprocess.txt
Q: Passing a Python list using JSON and Django I'm trying to send a Python list in to client side (encoded as JSON). This is the code snippet which I have written: array_to_js = [vld_id, vld_error, False] array_to_js[2] = True jsonValidateReturn = simplejson.dumps(array_to_js) return HttpResponse(jsonValidateReturn,...
Passing a Python list using JSON and Django
I'm trying to send a Python list in to client side (encoded as JSON). This is the code snippet which I have written: array_to_js = [vld_id, vld_error, False] array_to_js[2] = True jsonValidateReturn = simplejson.dumps(array_to_js) return HttpResponse(jsonValidateReturn, mimetype='application/json') How do I access it ...
[ "The JSON array will be dumped without a name / assignment.\nThat is, in order to give it a name, in your JavaScript code you would do something like this:\nvar my_json_data_dump = function_that_gets_json_data();\n\nIf you want to visualize it, for example, substitute:\nvar my_json_data_dump = { 'first_name' : Bob,...
[ 1, 0 ]
[]
[]
[ "django", "json", "python" ]
stackoverflow_0002435261_django_json_python.txt
Q: Database: storing data from user registration form Let's say I have an user registration form. In this form, I have the option for the user to upload a photo. I have an User table and Photo table. My User table has a "PathToPhoto" column. My question is how do I fill in the "PathToPhoto" column if the photo is ...
Database: storing data from user registration form
Let's say I have an user registration form. In this form, I have the option for the user to upload a photo. I have an User table and Photo table. My User table has a "PathToPhoto" column. My question is how do I fill in the "PathToPhoto" column if the photo is uploaded and inserted into Photo table before the user i...
[ "To make sure we're on the same page, is the following correct?\n\nYou're inserting the photo information into the Photo table immediately after the user uploads the photo but before he/she submits the form;\nWhen the user submits the form, you're inserting a row into the User table;\nOne of the items in that row i...
[ 0 ]
[]
[]
[ "database", "postgresql", "python" ]
stackoverflow_0002435281_database_postgresql_python.txt
Q: File size in Python server We have server on Python and client + web service on Ruby. That works only if file from URL is less than 800 k. It seems like "socket.puts data" in a client works, but "output = socket.gets" - not. I think problem is in a Python part. For big files tests run "Connection reset by peer". I...
File size in Python server
We have server on Python and client + web service on Ruby. That works only if file from URL is less than 800 k. It seems like "socket.puts data" in a client works, but "output = socket.gets" - not. I think problem is in a Python part. For big files tests run "Connection reset by peer". Is it buffer size variable by def...
[ "Could you add a little more information and code to your example?\nAre you thinking about sock.recv_into() which takes a buffer and buffer size as arguments? Alternately, are you hitting a timeout issue by failing to have a keepalive on the Ruby side?\nGuessing in advance of knowledge.\n" ]
[ 0 ]
[]
[]
[ "client", "python", "ruby", "size" ]
stackoverflow_0002435294_client_python_ruby_size.txt
Q: How i can convert integer in to 'binary' in python In Ruby i do so asd = 123 asd = '%b' % asd # => "1111011" A: in Python >= 2.6 with bin(): asd = bin(123) # => '0b1111011' To remove the leading 0b you can just take the substring bin(123)[2:]. bin(x) Convert an integer number to a binary string. The result is ...
How i can convert integer in to 'binary' in python
In Ruby i do so asd = 123 asd = '%b' % asd # => "1111011"
[ "in Python >= 2.6 with bin():\nasd = bin(123) # => '0b1111011'\n\nTo remove the leading 0b you can just take the substring bin(123)[2:].\n\nbin(x)\nConvert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that retu...
[ 7, 7, 0 ]
[]
[]
[ "python", "ruby" ]
stackoverflow_0002434806_python_ruby.txt
Q: Django : proper way to use model, duplicates! I have a question about the proper, best way to manage the model. I am relative newbie to django, so I think I need to read more docs, tutorials,etc (suggestions for this would be cool!). Anyway, this is my question : I have a python web crawler, that is "connected" wi...
Django : proper way to use model, duplicates!
I have a question about the proper, best way to manage the model. I am relative newbie to django, so I think I need to read more docs, tutorials,etc (suggestions for this would be cool!). Anyway, this is my question : I have a python web crawler, that is "connected" with django model. Crawling is done once a day, so it...
[ "Use the get_or_create() method of the manager, then modify the returned instance as needed.\n" ]
[ 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002435825_django_python.txt
Q: Python library for creating stubs/fake objects I am looking for python stubbing library. Something that could be used to create fake classes/methods in my unit tests.. Is there a simple way to achieve it in python.. Thanks PS: I am not looking for mocking library where you would record and replay expectation. Diff...
Python library for creating stubs/fake objects
I am looking for python stubbing library. Something that could be used to create fake classes/methods in my unit tests.. Is there a simple way to achieve it in python.. Thanks PS: I am not looking for mocking library where you would record and replay expectation. Difference between mock and stubs
[ "We do this.\nclass FakeSomethingOrOther( object ):\n def __init__( self ):\n self._count_me= 0\n def method_required_by_test( self ):\n return self.special_answer_required_by_test\n def count_this_method( self, *args, *kw ):\n self._count_me += 1\n\nIt doesn't take much to set them up\nclas...
[ 9, 0 ]
[]
[]
[ "mocking", "python", "stub", "testing" ]
stackoverflow_0002436220_mocking_python_stub_testing.txt
Q: Trying to get django app to work with mod_wsgi on CentOS 5 I'm running CentOS 5, and am trying to get a django application working with mod_wsgi. I'm using .wsgi settings I got working on Ubuntu. I'm also using an alternate installation of python (/opt/python2.6/) since my django application needs >2.5 and the OS ...
Trying to get django app to work with mod_wsgi on CentOS 5
I'm running CentOS 5, and am trying to get a django application working with mod_wsgi. I'm using .wsgi settings I got working on Ubuntu. I'm also using an alternate installation of python (/opt/python2.6/) since my django application needs >2.5 and the OS uses 2.3 Here is the error: [Thu Mar 04 10:52:15 2010] [error] [...
[ "SystemError: dynamic module not initialized properly is the exception that is thrown when a dll (or .so) that is being loaded cannot be properly initialized. In function _PyImport_LoadDynamicModule of Python/importdl.c in case anyone is interested.\nNow, the dll/so in question (the dynamic module in Python parlian...
[ 7 ]
[]
[]
[ "centos5", "django", "mod_wsgi", "python" ]
stackoverflow_0002435125_centos5_django_mod_wsgi_python.txt
Q: resolving overloads in boost.python I have a C++ class like this: class ConnectionBase { public: ConnectionBase(); template <class T> Publish(const T&); private: virtual void OnEvent(const Overload_a&) {} virtual void OnEvent(const Overload_b&) {} }; My templates & overloads are a known fixed se...
resolving overloads in boost.python
I have a C++ class like this: class ConnectionBase { public: ConnectionBase(); template <class T> Publish(const T&); private: virtual void OnEvent(const Overload_a&) {} virtual void OnEvent(const Overload_b&) {} }; My templates & overloads are a known fixed set of types at compile time. The applicati...
[ "Creating C++ virtual functions that can be overridden in Python requires some work - see here. You will need to create a wrapper function in a derived class that calls the Python method. Here is how it can work:\nstruct ConnectionBaseWrap : ConnectionBase, wrapper<ConnectionBase>\n{\n void OnEvent(const Overloa...
[ 2 ]
[]
[]
[ "boost", "boost_python", "c++", "python" ]
stackoverflow_0002436067_boost_boost_python_c++_python.txt
Q: Reverse Search Best Practices? I'm making an app that has a need for reverse searches. By this, I mean that users of the app will enter search parameters and save them; then, when any new objects get entered onto the system, if they match the existing search parameters that a user has saved, a notification will b...
Reverse Search Best Practices?
I'm making an app that has a need for reverse searches. By this, I mean that users of the app will enter search parameters and save them; then, when any new objects get entered onto the system, if they match the existing search parameters that a user has saved, a notification will be sent, etc. I am having a hard ti...
[ "At the database level, many databases offer 'triggers'.\nAnother approach is to have timed jobs that periodically fetch all items from the database that have a last-modified date since the last run; then these get filtered and alerts issued. You can perhaps put some of the filtering into the query statement in th...
[ 4, 4, 1 ]
[]
[]
[ "django", "python", "reverse", "search" ]
stackoverflow_0002431276_django_python_reverse_search.txt
Q: Python decoding issue with hashlib.digest() method Hello StackOverflow community, Using Google App Engine, I wrote a keyToSha256() method within a model class (extending db.Model) : class Car(db.Model): def keyToSha256(self): keyhash = hashlib.sha256(str(self.key())).digest() return keyhash Wh...
Python decoding issue with hashlib.digest() method
Hello StackOverflow community, Using Google App Engine, I wrote a keyToSha256() method within a model class (extending db.Model) : class Car(db.Model): def keyToSha256(self): keyhash = hashlib.sha256(str(self.key())).digest() return keyhash When displaying the output (ultimately within a Django tem...
[ "Use .hexdigest() instead.\n" ]
[ 5 ]
[]
[]
[ "decode", "google_app_engine", "python" ]
stackoverflow_0002436621_decode_google_app_engine_python.txt
Q: Why do we have callable objects in python? What is the purpose of a callable object? What problems do they solve? A: Many kinds of objects are callable in Python, and they can serve many purposes: functions are callable, and they may carry along a "closure" from an outer function classes are callable, and calli...
Why do we have callable objects in python?
What is the purpose of a callable object? What problems do they solve?
[ "Many kinds of objects are callable in Python, and they can serve many purposes:\n\nfunctions are callable, and they may carry along a \"closure\" from an outer function\nclasses are callable, and calling a class gets you an instance of that class\nmethods are callable, for function-like behavior specifically perta...
[ 13, 9, 2 ]
[]
[]
[ "callable", "python" ]
stackoverflow_0002436578_callable_python.txt
Q: Python API for VirtualBox I have made a command-line interface for virtualbox such that the virtualbox can be controlled from a remote machine. now I am trying to implement the commmand-line interface using python virtualbox api. For that I have downloaded the pyvb package (python api documentation shows functions...
Python API for VirtualBox
I have made a command-line interface for virtualbox such that the virtualbox can be controlled from a remote machine. now I am trying to implement the commmand-line interface using python virtualbox api. For that I have downloaded the pyvb package (python api documentation shows functions that can be used for implement...
[ "You might want to check the official Python API from Virtualbox. pyvb seems like a wrapper written by a third party.\nThe virtualbox sdk contains Python examples and full API documentation. \n" ]
[ 3 ]
[]
[]
[ "api", "python", "virtualbox" ]
stackoverflow_0002301534_api_python_virtualbox.txt
Q: Name some non-trivial sites written using IronPython & Silverlight Just what the title says. It'd be nice to know a few non-trivial sites out there using Silverlight in Python. A: My current job is writing business apps for a German / Swiss media media consortium using IronPython and Silverlight. We're gradually...
Name some non-trivial sites written using IronPython & Silverlight
Just what the title says. It'd be nice to know a few non-trivial sites out there using Silverlight in Python.
[ "My current job is writing business apps for a German / Swiss media media consortium using IronPython and Silverlight. We're gradually moving all our web apps over to IronPython / Silverlight as they are faster to build, look nicer and perform better than the Javascript equivalents.\nDefinitely not trivial, but not...
[ 2 ]
[]
[]
[ "ironpython", "python", "silverlight", "web" ]
stackoverflow_0002436714_ironpython_python_silverlight_web.txt
Q: What is the best, python or bash for selectively concatenating lots of files? I have around 20000 files coming from the output of some program, and their names follow the format: data1.txt data2.txt ... data99.txt data100.txt ... data999.txt data1000.txt ... data20000.txt I would like to write a script that gets ...
What is the best, python or bash for selectively concatenating lots of files?
I have around 20000 files coming from the output of some program, and their names follow the format: data1.txt data2.txt ... data99.txt data100.txt ... data999.txt data1000.txt ... data20000.txt I would like to write a script that gets as input argument the number N. Then it makes blocks of N concatenated files, so if...
[ "Here's a Python (2.6) version (if you have Python 2.5, add a first line that says\nfrom __future__ import with_statement\n\nand the script will also work)...:\nimport sys\n\ndef main(N):\n rN = range(N)\n for iout, iin in enumerate(xrange(1, 99999, N)):\n with open('data_new_%s.txt' % (iout+1), 'w') as o...
[ 4, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0002434689_bash_python.txt
Q: Special Character Meanings Defined In Python's module named string, there is a line that says whitespace = ' \t\n\r\v\f'. ' ' is a space character. '\t' is a tab character. '\n' is a newline character. '\r' is a carriage-return character. '\v' maps to '\x0b' (11). What does it mean and how might it be typed on a...
Special Character Meanings Defined
In Python's module named string, there is a line that says whitespace = ' \t\n\r\v\f'. ' ' is a space character. '\t' is a tab character. '\n' is a newline character. '\r' is a carriage-return character. '\v' maps to '\x0b' (11). What does it mean and how might it be typed on a keyboard (any OS)? '\f' maps to '\x0c...
[ "\\v is a vertical tab\n\\f is a formfeed\nSee: Escape Sequences\n", "\\v is a vertical tab. It was used in line printers to advance about 6 lines or so. It can be typed in *nix by pressing Ctrl-V Ctrl-K.\n\\f is a formfeed. It was used in line printers to advance to the next page. It can be typed in *nix by pres...
[ 2, 2, 2 ]
[]
[]
[ "character_codes", "python" ]
stackoverflow_0002437196_character_codes_python.txt
Q: How do you position a wx.MessageDialog (wxPython)? Is there any reason why the position, pos, flag doesn't seem to work in the following example? dlg = wx.MessageDialog( parent=self, message='You must enter a URL', caption='Error', style=wx.OK | wx.ICON_ERROR | wx.STAY_ON_TOP, pos=(200,200) ) ...
How do you position a wx.MessageDialog (wxPython)?
Is there any reason why the position, pos, flag doesn't seem to work in the following example? dlg = wx.MessageDialog( parent=self, message='You must enter a URL', caption='Error', style=wx.OK | wx.ICON_ERROR | wx.STAY_ON_TOP, pos=(200,200) ) dlg.ShowModal() dlg.Destroy() The documentation is here...
[ "It seems to be a bug and i think you should file the same. for time being you can user your own dervied dialog class to center it as you wish. Also instead of wx.MessageDialog you can use wx.MessageBox, it will save you few lines.\n" ]
[ 0 ]
[]
[]
[ "python", "windows", "wxpython" ]
stackoverflow_0002419619_python_windows_wxpython.txt
Q: Python | How to send a JSON response with name assign to it How can I return an response (lets say an array) to the client with a name assign to it form a python script. echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}'; in this scenario it returns an array with the name(jsonValidateReturn) assign to it a...
Python | How to send a JSON response with name assign to it
How can I return an response (lets say an array) to the client with a name assign to it form a python script. echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}'; in this scenario it returns an array with the name(jsonValidateReturn) assign to it also this can be accessed by jsonValidateReturn[1],so I want to do...
[ "Try this for the last two lines:\njsonValidateReturn = simplejson.dumps({'jsonValidateReturn': array_to_js})\nreturn HttpResponse(jsonValidateReturn, mimetype='application/json') \n\n" ]
[ 1 ]
[]
[]
[ "json", "python" ]
stackoverflow_0002437473_json_python.txt
Q: Use Google AppEngine datastore outside of AppEngine project For my little framework Pyxer I would like to to be able to use the Google AppEngine datastores also outside of AppEngine projects, because I'm now used to this ORM pattern and for little quick hacks this is nice. I can not use Google AppEngine for all of...
Use Google AppEngine datastore outside of AppEngine project
For my little framework Pyxer I would like to to be able to use the Google AppEngine datastores also outside of AppEngine projects, because I'm now used to this ORM pattern and for little quick hacks this is nice. I can not use Google AppEngine for all of my projects because of its's limitations in file size and number...
[ "Nick Johnson, from the app engine team himself, has a blog posting listing some of the alternatives, including his BDBdatastore.\nHowever, that assumes you want to use exactly the same ORM that you use now in app engine. There are tons of ORM options in general out there, though I am not familiar with the state o...
[ 5, 4, 0 ]
[]
[]
[ "google_app_engine", "orm", "python", "sql" ]
stackoverflow_0001149639_google_app_engine_orm_python_sql.txt
Q: Python optimization f = open('wl4.txt', 'w') hh = 0 ###################################### for n in range(1,5): for l in range(33,127): if n==1: b = chr(l) + '\n' f.write(b) hh += 1 elif n==2: for s0 in range(33, 127): ...
Python optimization
f = open('wl4.txt', 'w') hh = 0 ###################################### for n in range(1,5): for l in range(33,127): if n==1: b = chr(l) + '\n' f.write(b) hh += 1 elif n==2: for s0 in range(33, 127): b = chr(l) + chr(s0) + '\...
[ "Further significant improvements are possible.\nThe following script file demonstrates these, using (for brevity) only the size 4 loop (which takes up well over 90% of the time).\nmethod 0: the OP's original code\nmethod 1: John Kugleman's solution\nmethod 2: (1) and move some string concatenation out of inner loo...
[ 8, 7, 2, 2, 1, 0, 0 ]
[]
[]
[ "optimization", "python" ]
stackoverflow_0002433167_optimization_python.txt
Q: Would this hack for per-object permissions in django work? According to the documentation, a class can have the meta option permissions, described as such: Options.permissions Extra permissions to enter into the permissions table when creating this object. Add, delete and change permissions are automatically crea...
Would this hack for per-object permissions in django work?
According to the documentation, a class can have the meta option permissions, described as such: Options.permissions Extra permissions to enter into the permissions table when creating this object. Add, delete and change permissions are automatically created for each object that has admin set. This example specifies a...
[ "I think in the context of the Meta class, you don't have access to self.\nIf you look for a solution for the admin application, read this about row level permissions.\nThere is also says:\n\nFor public-facing (i.e., non-admin) views, you are of course free to implement whatever form of permission-checking logic yo...
[ 0, 0 ]
[]
[]
[ "database_permissions", "django", "permissions", "python" ]
stackoverflow_0002437621_database_permissions_django_permissions_python.txt
Q: Django admin site auto populate combo box based on input hi i have to following model class Match(models.Model): Team_one = models.ForeignKey('Team', related_name='Team_one') Team_two = models.ForeignKey('Team', related_name='Team_two') Stadium = models.CharField(max_length=255, blank=True) ...
Django admin site auto populate combo box based on input
hi i have to following model class Match(models.Model): Team_one = models.ForeignKey('Team', related_name='Team_one') Team_two = models.ForeignKey('Team', related_name='Team_two') Stadium = models.CharField(max_length=255, blank=True) Start_time = models.DateTimeField(auto_now_add=False, auto_now...
[ "Theres no real easy way to do that with the django admin. It's possible, but it would require you to replace the admin form, and subclass the widget with some javascript that copys the Team into the box. Way more effort than it's worth.\nIf I were you, I'd just have winner_team and loser_team fields\nalso read thi...
[ 1, 0 ]
[]
[]
[ "django", "django_admin", "django_models", "django_templates", "python" ]
stackoverflow_0002437264_django_django_admin_django_models_django_templates_python.txt
Q: Python Script to backup a directory #Filename:backup_ver1 import os import time #1 Using list to specify the files and directory to be backed up source = r'C:\Documents and Settings\rgolwalkar\Desktop\Desktop\Dr Py\Final_Py' #2 define backup directory destination = r'C:\Documents and Settings\rgolwalkar\Desktop...
Python Script to backup a directory
#Filename:backup_ver1 import os import time #1 Using list to specify the files and directory to be backed up source = r'C:\Documents and Settings\rgolwalkar\Desktop\Desktop\Dr Py\Final_Py' #2 define backup directory destination = r'C:\Documents and Settings\rgolwalkar\Desktop\Desktop\PyDevResourse' #3 Setting the b...
[ "Maybe instead of writing your own backup script you could use python tool called rdiff-backup, which can create incremental backups?\n", "The source directory contains spaces, but you don't have quotes around it in the command line. This might be a reason for the backup to fail.\nTo avoid problems like this, use...
[ 2, 0, 0 ]
[]
[]
[ "backup", "python", "rar", "windows_xp" ]
stackoverflow_0002438041_backup_python_rar_windows_xp.txt
Q: Python twisted Reactor class What is the significance of the decorators @reactor.callWhenRunning, @results_deferred.addCallback @results_deferred.addErrback. Also what are deferred strings, for example in the twisted.internet.utils.getProcessOutput() returns a deferred string what exactly is happening here?...
Python twisted Reactor class
What is the significance of the decorators @reactor.callWhenRunning, @results_deferred.addCallback @results_deferred.addErrback. Also what are deferred strings, for example in the twisted.internet.utils.getProcessOutput() returns a deferred string what exactly is happening here? I am new to twisted hence this mi...
[ "In the normal programming practice you'd do\ndb = Database.connect()\nresult = db.getResult()\nprocessResult(result)\n\nNow depending on your Database and network, these 3 statements can take anywhere from a millisecond to a few seconds.\nWe've all been programming this way for decades now, and for the most part w...
[ 4, 3, 1 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0002433616_python_twisted.txt
Q: Problem with Tk and Ping in Python I'm not being able to make this line work with Tk import os while(1): ping = os.popen('ping www.google.com -n 1') result = ping.readlines() msLine = result[-1].strip() print msLine.split(' = ')[-1] I'm trying to create a label and text = msLine.split... but every...
Problem with Tk and Ping in Python
I'm not being able to make this line work with Tk import os while(1): ping = os.popen('ping www.google.com -n 1') result = ping.readlines() msLine = result[-1].strip() print msLine.split(' = ')[-1] I'm trying to create a label and text = msLine.split... but everything freezes
[ "There can be other issues with Tk and popen(). First:\nThou shalt not continously ping or fetch from google.com.\nAdd a \"import time\" at the top and \"time.sleep(2)\" at the bottom of \nthe while loop.\nSecond:\nYou probably meant \"ping www.google.com -c 1\" instead of \"-n 1\". The \"-c 1\" asks for one\npin...
[ 0, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0002430653_python_tkinter.txt
Q: Differentiate gtk.Entry icons I'm adding two icons to a gtk.Entry in PyGTK. The icons signals are handled by the following method def entry_icon_event(self, widget, position, event) I'm trying to differentiate between the two of them: <enum GTK_ENTRY_ICON_PRIMARY of type GtkEntryIconPosition> <enum GTK_ENTRY_ICON...
Differentiate gtk.Entry icons
I'm adding two icons to a gtk.Entry in PyGTK. The icons signals are handled by the following method def entry_icon_event(self, widget, position, event) I'm trying to differentiate between the two of them: <enum GTK_ENTRY_ICON_PRIMARY of type GtkEntryIconPosition> <enum GTK_ENTRY_ICON_SECONDARY of type GtkEntryIconPosi...
[ "Alright, since no one gave an answer, I'll do with what I actually found. A method to use this icons would look like this:\ndef entry_icon_event(self, widget, icon, event):\n if icon.value_name == \"GTK_ENTRY_ICON_PRIMARY\":\n print \"First Button\"\n if event.button == 0:\n print \"Lef...
[ 2, 1 ]
[]
[]
[ "gtkentry", "icons", "pygtk", "python" ]
stackoverflow_0002191209_gtkentry_icons_pygtk_python.txt
Q: Batch select with SQLAlchemy I have a large set of values V, some of which are likely to exist in a table T. I would like to insert into the table those which are not yet inserted. So far I have the code: for value in values: s = self.conn.execute(mytable.__table__.select(mytable.value == value)).first()...
Batch select with SQLAlchemy
I have a large set of values V, some of which are likely to exist in a table T. I would like to insert into the table those which are not yet inserted. So far I have the code: for value in values: s = self.conn.execute(mytable.__table__.select(mytable.value == value)).first() if not s: ...
[ "For the first question, something like this if I understand your question correctly\nmytable.__table__.select(mytable.value.in_(values)\n\nFor the second question, querying this by 1 row at a time is overly expensive indeed, although you might not have a choice in the matter. As far as I know there is no tuple sel...
[ 3 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002438690_python_sqlalchemy.txt
Q: Using Nose & NoseXUnit on a Python package This is a previous post detailing a CI setup for Python. The asker and answerer detail the use of Nose and NoseXUnit with Hudson for their builds. However, NoseXUnit throws an error when run on any source folder where init.py is present: File "build/bdist.linux-x86_64/e...
Using Nose & NoseXUnit on a Python package
This is a previous post detailing a CI setup for Python. The asker and answerer detail the use of Nose and NoseXUnit with Hudson for their builds. However, NoseXUnit throws an error when run on any source folder where init.py is present: File "build/bdist.linux-x86_64/egg/nosexunit/tools.py", line 59, in package...
[ "You probably shouldn't use NoseXUnit - it's really out of date, and a similar feature exists in nose >= 0.11.\nFrom nose --help:\n --with-xunit Enable plugin Xunit: This plugin provides test results\n in the standard XUnit XML format. [NOSE_WITH_XUNIT]\n --xunit-file=FILE Path...
[ 5 ]
[]
[]
[ "nose", "nosetests", "package", "python", "web2py" ]
stackoverflow_0002083102_nose_nosetests_package_python_web2py.txt
Q: warnings emitted during 'easy_install' When I easy_install some python modules, warnings such as: <some module>: module references __file__ <some module>: module references __path__ <some module>: module MAY be using inspect.trace <some module>: module MAY be using inspect.getsourcefile sometimes get emitted. Wh...
warnings emitted during 'easy_install'
When I easy_install some python modules, warnings such as: <some module>: module references __file__ <some module>: module references __path__ <some module>: module MAY be using inspect.trace <some module>: module MAY be using inspect.getsourcefile sometimes get emitted. Where (what package / source file) do these me...
[ "easy_install doesn't like use of __file__ and __path__ not so much because they're dangerous, but because packages that use them almost always fail to run out of zipped eggs. \neasy_install is warning because it'll install \"less efficiently\" into an unzipped directory instead of a zipped egg. \nIn practice, I'm ...
[ 7, 2 ]
[]
[]
[ "easy_install", "python", "warnings" ]
stackoverflow_0002298403_easy_install_python_warnings.txt
Q: Python: inserting double or single quotes around a string Im using python to access a MySQL database and im getting a unknown column in field due to quotes not being around the variable. code below: cur = x.cnx.cursor() cur.execute('insert into tempPDBcode (PDBcode) values (%s);' % (s)) rows = cur.fetchall() How...
Python: inserting double or single quotes around a string
Im using python to access a MySQL database and im getting a unknown column in field due to quotes not being around the variable. code below: cur = x.cnx.cursor() cur.execute('insert into tempPDBcode (PDBcode) values (%s);' % (s)) rows = cur.fetchall() How do i manually insert double or single quotes around the value ...
[ "You shouldn't use Python's string functions to build the SQL statement. You run the risk of leaving an SQL injection vulnerability. You should do this instead:\ncur.execute('insert into tempPDBcode (PDBcode) values (%s);', s) \n\nNote the comma.\n", "Python will do this for you automatically, if you use the data...
[ 10, 5 ]
[ "If this were purely a string-handling question, the answer would be tojust put them in the string:\ncur.execute('insert into tempPDBcode (PDBcode) values (\"%s\");' % (s)) \n\nThat's the classic use case for why Python supports both kinds of quotes.\nHowever as other answers & comments have pointed out, there are ...
[ -5 ]
[ "python", "quotes", "sql" ]
stackoverflow_0002439027_python_quotes_sql.txt
Q: Reading Python Documentation for 3rd party modules I recently downloaded IMDbpy module.. When I do, import imdb help(imdb) i dont get the full documentation.. I have to do im = imdb.IMDb() help(im) to see the available methods. I dont like this console interface. Is there any better way of reading the doc. I m...
Reading Python Documentation for 3rd party modules
I recently downloaded IMDbpy module.. When I do, import imdb help(imdb) i dont get the full documentation.. I have to do im = imdb.IMDb() help(im) to see the available methods. I dont like this console interface. Is there any better way of reading the doc. I mean all the doc related to module imdb in one page..
[ "Use pydoc \npydoc -w imdb\n\nThis will generate imdb.html in the same directory.\n\npydoc -p 9090 will start a HTTP server on port 9090, and you will be able to browse all documentation at http://localhost:9090/\n", "in IPython you could do\n[1]: import os\n[2]: os?\n\n< get the full documentation here >\n\n# or...
[ 10, 1 ]
[]
[]
[ "documentation", "imdbpy", "pydoc", "python" ]
stackoverflow_0002437857_documentation_imdbpy_pydoc_python.txt
Q: How to teach beginners reversing a string in Python? I am teaching a course "Introduction to Computer Programming" to the first year math students. One has to assume that this is the first exposure of students to computer programming. Here are the main goals of my teaching: Students should learn and understand th...
How to teach beginners reversing a string in Python?
I am teaching a course "Introduction to Computer Programming" to the first year math students. One has to assume that this is the first exposure of students to computer programming. Here are the main goals of my teaching: Students should learn and understand the basics of Python. Eventually they need to master suffici...
[ "You could teach them about stride notation (::) first and then slicing and apply both.\ns = 'string'\ns = s[::-1]\nprint s # gnirts\n\nReferences and more information:\n\nExtended Slices\nAn Informal Introduction to Python\nPython string reversed explanation\n\nIn response to your comment, you can supply either a...
[ 7, 4, 3, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002439216_python.txt
Q: how to embed a webpage using wx? I need to show a webpage (a complex page with script and stuff, no static html) in a frame or something. It's for a desktop application, I'm using python 2.6 + wxPython 2.8.10.1. I need to catch some events too (mostly about changing page). I've found some samples using the webview...
how to embed a webpage using wx?
I need to show a webpage (a complex page with script and stuff, no static html) in a frame or something. It's for a desktop application, I'm using python 2.6 + wxPython 2.8.10.1. I need to catch some events too (mostly about changing page). I've found some samples using the webview module in a gtk application, but I co...
[ "You can embed IE, but I think that's about it. wxWebKit is working on a wx add-on to use WebKit as an embedded browser in wx, but I think it's still a work in progress.\n", "There is a commercial solution for this called wxWebConnect that uses Gecko (the Mozilla engine). I've never used it myself because i'm wai...
[ 1, 1 ]
[]
[]
[ "python", "wxwidgets" ]
stackoverflow_0002439039_python_wxwidgets.txt
Q: Install TurboGears on windows xp I've been trying to get TurboGears installed on Windows by following this site. I've installed virtualenv but when I execute the command "virtualenv --no-site-packages testproj", I get the following message: New python executable in testproj\Scripts\python.exe Traceback (most rece...
Install TurboGears on windows xp
I've been trying to get TurboGears installed on Windows by following this site. I've installed virtualenv but when I execute the command "virtualenv --no-site-packages testproj", I get the following message: New python executable in testproj\Scripts\python.exe Traceback (most recent call last): File "C:\Python26\Scr...
[ "I figured out the error. Apparently, virtualenv does not like it if folder names have spaces (eg Documents and Settings). It worked fine when my folder names had no spaces.\n" ]
[ 1 ]
[]
[]
[ "python", "turbogears", "windows_xp" ]
stackoverflow_0002426262_python_turbogears_windows_xp.txt
Q: Parsing/Tokenizing a String Containing a SQL Command Are there any open source libraries (any language, python/PHP preferred) that will tokenize/parse an ANSI SQL string into its various components? That is, if I had the following string SELECT a.foo, b.baz, a.bar FROM TABLE_A a LEFT JOIN TABLE_B b ON a.id =...
Parsing/Tokenizing a String Containing a SQL Command
Are there any open source libraries (any language, python/PHP preferred) that will tokenize/parse an ANSI SQL string into its various components? That is, if I had the following string SELECT a.foo, b.baz, a.bar FROM TABLE_A a LEFT JOIN TABLE_B b ON a.id = b.id WHERE baz = 'snafu'; I'd get back a data structure...
[ "SQLite source has a file named parse.y that contains grammar for SQL. You can pass that file to lemon parser generator to generate C code that executes the grammar. \n" ]
[ 2 ]
[]
[]
[ "parsing", "php", "python", "sql", "tokenize" ]
stackoverflow_0002439618_parsing_php_python_sql_tokenize.txt
Q: In what order should the Python concepts be explained to absolute beginners? I am teaching Python to undergraduate math majors. I am interested in the optimal order in which students should be introduced to various Python concepts. In my view, at each stage the students should be able to solve a non-trivial progra...
In what order should the Python concepts be explained to absolute beginners?
I am teaching Python to undergraduate math majors. I am interested in the optimal order in which students should be introduced to various Python concepts. In my view, at each stage the students should be able to solve a non-trivial programming problem using only the tools available at that time. Each new tool should en...
[ "After some try / except as a teacher, I chose to stick to something like:\n(starting from nothing, adjust to their level)\n\nShortly, what is Python and what you can do with it. Skip the speech on technical stuff and focus on what they want to do : music, GUI, Web site, renaming files, etc.\nInstalling Python, run...
[ 20, 2, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002439638_python.txt
Q: Passing in **kwargs from Flex over PyAMF Anyone know if it is easily possible to send **kwargs over PyAMF from NetConnection.call()? I would like it. I could write a wrapper around the actual function and expose that and perform some parsing manually to determine the kwargs to pass in, but I don't want to do that....
Passing in **kwargs from Flex over PyAMF
Anyone know if it is easily possible to send **kwargs over PyAMF from NetConnection.call()? I would like it. I could write a wrapper around the actual function and expose that and perform some parsing manually to determine the kwargs to pass in, but I don't want to do that. I will just use a normal argument list in tha...
[ "Whilst ActionScript has the *args construct (params ...) there is no equivalent to **kwargs, although if you do need to send arbitrary named arguments, then you can always send a dict as a positional argument to the service. E.g.\ndef some_service_function(kwargs): # <- note the lack of **\n foo = kwargs.get('f...
[ 1 ]
[]
[]
[ "keyword_argument", "pyamf", "python", "remoting" ]
stackoverflow_0002438235_keyword_argument_pyamf_python_remoting.txt
Q: As a newbie, where should I go if I want to create a small GUI program? I'm a newbie with a little experience writing in BASIC, Python and, of all things, a smidgeon of assembler (as part of a videogame ROM hack). I wanted to create small tool for modifying the hex values at particular points, in a particular file...
As a newbie, where should I go if I want to create a small GUI program?
I'm a newbie with a little experience writing in BASIC, Python and, of all things, a smidgeon of assembler (as part of a videogame ROM hack). I wanted to create small tool for modifying the hex values at particular points, in a particular file, that would have a GUI interface. What I'm looking for is the ability to cre...
[ "You'd be better off thinking/saying/googling wxPython (not wxWidgets), since wxPython is the python wrapper for the wxWidgets C++.\n1.) Python is a good language for this. If you are only targeting windows, I'd still do it in .NET/C# though. If you want cross-platform, Python/wxPython all the way.\n2.) Yes, the ...
[ 4, 3, 0, 0 ]
[]
[]
[ "py2exe", "python", "tkinter", "wxwidgets" ]
stackoverflow_0002439520_py2exe_python_tkinter_wxwidgets.txt
Q: Save memory in Python. How to iterate over the lines and save them efficiently with a 2million line file? I have a tab-separated data file with a little over 2 million lines and 19 columns. You can find it, in US.zip: http://download.geonames.org/export/dump/. I started to run the following but with for l in f.rea...
Save memory in Python. How to iterate over the lines and save them efficiently with a 2million line file?
I have a tab-separated data file with a little over 2 million lines and 19 columns. You can find it, in US.zip: http://download.geonames.org/export/dump/. I started to run the following but with for l in f.readlines(). I understand that just iterating over the file is supposed to be more efficient so I'm posting that ...
[ "Make sure that Django's DEBUG setting is set to False\n", "This looks perfectly fine to me. Iterating over the file like that or using xreadlines() will read each line as needed (with sane buffering behind the scenes). Memory usage should not grow as you read in more and more data.\nAs for performance, you shoul...
[ 5, 2, 2 ]
[]
[]
[ "django", "file", "memory_management", "python" ]
stackoverflow_0002440495_django_file_memory_management_python.txt
Q: Python 3: Most efficient way to create a [func(i) for i in range(N)] list comprehension Say I have a function func(i) that creates an object for an integer i, and N is some nonnegative integer. Then what's the fastest way to create a list (not a range) equal to this list mylist = [func(i) for i in range(N)] witho...
Python 3: Most efficient way to create a [func(i) for i in range(N)] list comprehension
Say I have a function func(i) that creates an object for an integer i, and N is some nonnegative integer. Then what's the fastest way to create a list (not a range) equal to this list mylist = [func(i) for i in range(N)] without resorting to advanced methods like creating a function in C? My main concern with the abov...
[ "Somebody wrote: \"\"\"Python is smart enough. As long as the object you're iterating over has a __len__ or __length_hint__ method, Python will call it to determine the size and preallocate the array.\"\"\"\nAs far as I can tell, there is no preallocation in a list comprehension. Python has no way of telling from t...
[ 7, 2, 2, 1, 1, 0 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0002439986_list_comprehension_python.txt
Q: How can I use Python with Mechanize for posting multipart/form-data? I am using http://pypi.python.org/pypi/mechanize/0.1.11 for programmatic web browsing, I want to be able to upload files to servers the same way the browser does (by sending the content as multipart/form-data, defined in RFC2388) Is this possible...
How can I use Python with Mechanize for posting multipart/form-data?
I am using http://pypi.python.org/pypi/mechanize/0.1.11 for programmatic web browsing, I want to be able to upload files to servers the same way the browser does (by sending the content as multipart/form-data, defined in RFC2388) Is this possible with mechanize, can you show me an example? Thanks!
[ "There's a couple of good answer on this SO question, one with bare mechanize and one with twill on top of it, and I believe they both end up sending multipart/form-data as you want.\n" ]
[ 2 ]
[]
[]
[ "mechanize", "multipartform_data", "python" ]
stackoverflow_0002439900_mechanize_multipartform_data_python.txt
Q: How to bind an ip address to telnetlib in Python The code below binds an ip address to urllib, urllib2, etc. import socket true_socket = socket.socket def bound_socket(*a, **k): sock = true_socket(*a, **k) sock.bind((sourceIP, 0)) return sock socket.socket = bound_socket Is it also able to bind an ip ...
How to bind an ip address to telnetlib in Python
The code below binds an ip address to urllib, urllib2, etc. import socket true_socket = socket.socket def bound_socket(*a, **k): sock = true_socket(*a, **k) sock.bind((sourceIP, 0)) return sock socket.socket = bound_socket Is it also able to bind an ip address to telnetlib?
[ "telnetlib at least in recent Python releases uses socket.create_connection (see telnetlib's sources here) but that should also be caught by your monkeypatch (sources here -- you'll see it uses a bare identifier socket but that's exactly in the module you're monkeypatching). Of course monkeypatching is always extr...
[ 2 ]
[]
[]
[ "ip_address", "python", "telnetlib" ]
stackoverflow_0002440781_ip_address_python_telnetlib.txt
Q: How to remove lowercase sentence fragments from text? I'm tyring to remove lowercase sentence fragments from standard text files using regular expresions or a simple Perl oneliner. These are commonly referred to as speech or attribution tags, for example - he said, she said, etc. This example shows before and...
How to remove lowercase sentence fragments from text?
I'm tyring to remove lowercase sentence fragments from standard text files using regular expresions or a simple Perl oneliner. These are commonly referred to as speech or attribution tags, for example - he said, she said, etc. This example shows before and after using manual deletion: Original: "Ah, that's perfe...
[ "Here's a Python snippet that should do:\n thetext=\"\"\"triple quoted paste of your sample text\"\"\"\n y=thetext.split('\\n')\n for line in y:\n m=re.findall('(\".*?\")',line)\n if m:\n print ' '.join(m)\n else:\n print line\n\n", "The Text::Balanced module is what you seem to be after if...
[ 3, 0, 0, 0, 0 ]
[]
[]
[ "awk", "perl", "python", "regex" ]
stackoverflow_0002439968_awk_perl_python_regex.txt
Q: Compiler options wrong with python setup.py I'm trying to install matplotlib on my mac setup. I find that setup.py has inaccurate flags, in particular the isysroot points to an earlier SDK. Where does setup.py get its info and how can i fix it? I'm on MacOS 10.5.8, XCode 3.1.2 and Python 2.6 (default config was 2....
Compiler options wrong with python setup.py
I'm trying to install matplotlib on my mac setup. I find that setup.py has inaccurate flags, in particular the isysroot points to an earlier SDK. Where does setup.py get its info and how can i fix it? I'm on MacOS 10.5.8, XCode 3.1.2 and Python 2.6 (default config was 2.5)
[ "I'm guessing you've installed 2.6 on 10.5 using the python.org OS X installer. In that case, the flags are accurate and you should not try to change them. The python.org installers are built using the so-called 10.4u SDK and with a deployment target of 10.3, allowing one installer image to work on Mac OS X syste...
[ 3, 1 ]
[]
[]
[ "distutils", "gcc", "macos", "python", "setup.py" ]
stackoverflow_0002440579_distutils_gcc_macos_python_setup.py.txt
Q: warning in python with MySQLdb when I use MySQLdb get this message: /var/lib/python-support/python2.6/MySQLdb/__init__.py:34: DeprecationWarning: the sets module is deprecated from sets import ImmutableSet I try filter the warning with import warnings warnings.filterwarnings("ignore", message="the sets mod...
warning in python with MySQLdb
when I use MySQLdb get this message: /var/lib/python-support/python2.6/MySQLdb/__init__.py:34: DeprecationWarning: the sets module is deprecated from sets import ImmutableSet I try filter the warning with import warnings warnings.filterwarnings("ignore", message="the sets module is deprecated from sets import I...
[ "From python documentation: you could filter your warning this way, so that if other warnings are caused by an other part of your code, there would still be displayed:\nimport warnings\nwith warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", DeprecationWarning)\n import MySQLdb\n[...]\n\nbut as sa...
[ 4, 1 ]
[]
[]
[ "mysql", "python", "warnings" ]
stackoverflow_0002440799_mysql_python_warnings.txt
Q: pyqt QTreeWidget setItemWidget dissapears after drag/drop I'm trying to keep a widget put into a QTreeWidgetItem after a reparent (drag and drop) using QTreeWidget.setItemWidget() But the result, if you compile the following code - is that the widget inside the QTreeWidgetItem disappears. Any idea why? What code ...
pyqt QTreeWidget setItemWidget dissapears after drag/drop
I'm trying to keep a widget put into a QTreeWidgetItem after a reparent (drag and drop) using QTreeWidget.setItemWidget() But the result, if you compile the following code - is that the widget inside the QTreeWidgetItem disappears. Any idea why? What code would fix this (repopulate the QTreeWidgetItem with the widget ...
[ "managed to get a relatively \"working\" fix in by writing my own treeDropEvent... however if someone has a more elegant solution, please feel free to share. the code below will solve anyone else's headaches for drag/drop with setItemWidgets in a tree, cheers.\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\...
[ 2, 0 ]
[]
[]
[ "pyqt", "python", "qt", "qtreewidget", "user_interface" ]
stackoverflow_0002383212_pyqt_python_qt_qtreewidget_user_interface.txt
Q: Embed Python interpreter in a Python application I'm looking for a way to ship the Python interpreter with my application (also written in Python), so that it doesn't need to have Python installed on the machine. I searched Google and found a bunch of results about how to embed the Python interpreter in applicatio...
Embed Python interpreter in a Python application
I'm looking for a way to ship the Python interpreter with my application (also written in Python), so that it doesn't need to have Python installed on the machine. I searched Google and found a bunch of results about how to embed the Python interpreter in applications written in various languages, but nothing for appli...
[ "For distribution on Windows machines, look into py2exe\npy2exe is a Python Distutils extension which converts Python scripts \ninto executable Windows programs, able to run without requiring a \nPython installation\n\nFor the MacIntosh, there is py2app (but I'm not familiar with it)\nAnd for both Windows and Lin...
[ 9, 2, 2, 0, 0 ]
[]
[]
[ "embedding", "interpreter", "python" ]
stackoverflow_0002441172_embedding_interpreter_python.txt
Q: Printing Stdout In Command Line App Without Overwriting Pending User Input In a basic Unix-shell app, how would you print to stdout without disturbing any pending user input. e.g. Below is a simple Python app that echos user input. A thread running in the background prints a counter every 1 second. import threadin...
Printing Stdout In Command Line App Without Overwriting Pending User Input
In a basic Unix-shell app, how would you print to stdout without disturbing any pending user input. e.g. Below is a simple Python app that echos user input. A thread running in the background prints a counter every 1 second. import threading, time class MyThread( threading.Thread ): running = False def run(sel...
[ "You have to port your code to some way of controlling the terminal as slightly better than a teletype -- e.g. with the curses module in Python's standard library, or other ways to move the cursor away before emitting output, then move it back to where the user's busy inputting stuff.\n", "You could defer writing...
[ 2, 0 ]
[]
[]
[ "bash", "python", "scripting", "shell", "stdout" ]
stackoverflow_0002440387_bash_python_scripting_shell_stdout.txt
Q: How to implement Comet server side with Python? I once tried to implement Comet in PHP. Soon, I found that PHP is not suitable for Comet, since each HTTP request will occupy one process/thread. As a result, it doesn't scale well. I just installed mod_python in my XAMPP. I thought it would be easy to implement Com...
How to implement Comet server side with Python?
I once tried to implement Comet in PHP. Soon, I found that PHP is not suitable for Comet, since each HTTP request will occupy one process/thread. As a result, it doesn't scale well. I just installed mod_python in my XAMPP. I thought it would be easy to implement Comet with Python asynchronous programming. But still ca...
[ "First of all, I'm not async expert at all, I just investigated the topic once. \nIMHO if you're using XAMPP then you're loosing the posibility of doing long polling because Apache uses thread/processes (depending on configuration) for each request.\nWhat you need, is non-blocking web server, like Tornado, that all...
[ 8, 0 ]
[]
[]
[ "comet", "python" ]
stackoverflow_0002441533_comet_python.txt
Q: Django database - how to add this column in raw SQL Suppose I have my models set up already. class books(models.Model): title = models.CharField... ISBN = models.Integer... What if I want to add this column to my table? user = models.ForeignKey(User, unique=True) How would I write the raw SQL in my datab...
Django database - how to add this column in raw SQL
Suppose I have my models set up already. class books(models.Model): title = models.CharField... ISBN = models.Integer... What if I want to add this column to my table? user = models.ForeignKey(User, unique=True) How would I write the raw SQL in my database so that this column works?
[ "You should investigate a tool like South, which does all this for you.\nHowever the SQL would be something like (assuming you're using MySQL):\nALTER TABLE `appname_books` ADD COLUMN `user_id` INTEGER NOT NULL UNIQUE;\nALTER TABLE `appname_books` ADD CONSTRAINT `user_id_refs_user` FOREIGN KEY (`user_id`) REFERENCE...
[ 5 ]
[]
[]
[ "database", "django", "mysql", "python" ]
stackoverflow_0002441771_database_django_mysql_python.txt
Q: Is there a python module compatible with Google Apps Engine's new "Tasks" I'm writing a Python application, that I want to later migrate to GAE. The new "Task Queues" API fulfills a requirement of my app, and I want to simulate it locally until I have the time to migrate the whole thing to GAE. Does anyone know of...
Is there a python module compatible with Google Apps Engine's new "Tasks"
I'm writing a Python application, that I want to later migrate to GAE. The new "Task Queues" API fulfills a requirement of my app, and I want to simulate it locally until I have the time to migrate the whole thing to GAE. Does anyone know of a compatible module I can run locally?
[ "Given the explicitly experimental nature of the thing, there's certainly nothing compatible in existence at this time. And obviously even if there were, Google pretty much says \"we're going to change the API!\" in their warning about it, so anything compatible now would not be compatible when the time comes to m...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "migration", "python", "task" ]
stackoverflow_0001068690_google_app_engine_migration_python_task.txt
Q: How to print a range with decimal points in Python? I can print a range of numbers easily using range, but is is possible to print a range with 1 decimal place from -10 to 10? e.g -10.0, -9.9, -9.8 all they way through to +10? A: [i/10.0 for i in range(-100,101)] (The .0 is not needed in Python 3.x) A: There'...
How to print a range with decimal points in Python?
I can print a range of numbers easily using range, but is is possible to print a range with 1 decimal place from -10 to 10? e.g -10.0, -9.9, -9.8 all they way through to +10?
[ "[i/10.0 for i in range(-100,101)]\n\n(The .0 is not needed in Python 3.x)\n", "There's a recipe on ActiveState that implements a floating-point range. In your example, you can use it like\nfrange(-10, 10.01, 0.1)\n\nNote that this won't generate 1 decimal place on most architectures because of the floating-point...
[ 7, 2, 0, 0, 0 ]
[]
[]
[ "python", "range" ]
stackoverflow_0002439837_python_range.txt
Q: Accessing Class Variables from a List in a nice way in Python Suppose I have a list X = [a, b, c] where a, b, c are instances of the same class C. Now, all these instances a,b,c, have a variable called v, a.v, b.v, c.v ... I simply want a list Y = [a.v, b.v, c.v] Is there a nice command to do this? The be...
Accessing Class Variables from a List in a nice way in Python
Suppose I have a list X = [a, b, c] where a, b, c are instances of the same class C. Now, all these instances a,b,c, have a variable called v, a.v, b.v, c.v ... I simply want a list Y = [a.v, b.v, c.v] Is there a nice command to do this? The best way I can think of is: Y = [] for i in X Y.append(i.v) But ...
[ "That should work:\nY = [x.v for x in X]\n\n", "The list comprehension is the way to go. \nBut you also said you don't know how to use map to do it. Now, I would not recommend to use map for this at all, but it can be done:\nmap( lambda x: x.v, X)\n\nthat is, you create an anonymous function (a lambda) to return ...
[ 11, 5, 2 ]
[]
[]
[ "class", "list", "map", "methods", "python" ]
stackoverflow_0002442000_class_list_map_methods_python.txt
Q: Weird characters in exported csv files when converting I came across a problem I cannot solve on my own concerning the downloadable csv formatted trends data files from Google Insights for Search. I'm to lazy to reformat the files I4S gives me manually what means: Extracting the section with the actual trends dat...
Weird characters in exported csv files when converting
I came across a problem I cannot solve on my own concerning the downloadable csv formatted trends data files from Google Insights for Search. I'm to lazy to reformat the files I4S gives me manually what means: Extracting the section with the actual trends data and reformatting the columns so that I can use it with a m...
[ "repr() is your friend (except on Python 3.X; use ascii() instead).\nprompt>\\python26\\python -c \"print repr(open('report.csv','rb').read()[:300])\"\n'\\xff\\xfeW\\x00e\\x00b\\x00 \\x00S\\x00e\\x00a\\x00r\\x00c\\x00h\\x00 \\x00I\\x00n\\x00t\\x00e\n\\x00r\\x00e\\x00s\\x00t\\x00:\\x00 \\x00f\\x00o\\x00o\\x00b\\x00a...
[ 4, 3, 2 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0002441682_csv_python.txt
Q: Python, SWIG and other strange things I have a firmware for an USB module I can already control by visual C. Now I want to port this to python. for this I need the octopus library which is written in c. I found a file called octopus_wrap which was created by SWIG! then I found a makefile which says: python2.5: ...
Python, SWIG and other strange things
I have a firmware for an USB module I can already control by visual C. Now I want to port this to python. for this I need the octopus library which is written in c. I found a file called octopus_wrap which was created by SWIG! then I found a makefile which says: python2.5: swig -python -outdir ./ ../octopus.i ...
[ "You should link and compile for the python2.6 -lpython26.\nAlso the file extension for windows is .pyd no .so\n" ]
[ 0 ]
[]
[]
[ "python", "swig", "usb", "wrapper" ]
stackoverflow_0002442042_python_swig_usb_wrapper.txt
Q: Python: puzzling behaviour inside httplib I have added one line ( import pdb; pdb.set_trace() ) to httplib's HTTPConnection.putheader, so I can see what's going on inside. Python26\Lib\httplib.py, line 489: def putheader(self, header, value): """Send a request header line to the server. For example: h.pu...
Python: puzzling behaviour inside httplib
I have added one line ( import pdb; pdb.set_trace() ) to httplib's HTTPConnection.putheader, so I can see what's going on inside. Python26\Lib\httplib.py, line 489: def putheader(self, header, value): """Send a request header line to the server. For example: h.putheader('Accept', 'text/html') """ impo...
[ "Answering my own question:\nhttp://en.wikipedia.org/wiki/Name_mangling#Name_mangling_in_Python\n__state is a private name inside the object, it gets mangled as _HTTPConnection__state, so when I want to access it in PDB I have to name it as self._HTTPConnection__state. Only the object can refer to it as __state.\n"...
[ 1, 0 ]
[]
[]
[ "debugging", "httplib", "python" ]
stackoverflow_0002441798_debugging_httplib_python.txt
Q: how to search for file's has a known file extension like .py? how to search for file's has a known file extension like .py ?? fext = raw_input("Put file extension to search: ") dir = raw_input("Dir to search in: ") ##Search for the file and get the right one's A: I believe you want to do something like similar ...
how to search for file's has a known file extension like .py?
how to search for file's has a known file extension like .py ?? fext = raw_input("Put file extension to search: ") dir = raw_input("Dir to search in: ") ##Search for the file and get the right one's
[ "I believe you want to do something like similar to this: /dir/to/search/*.extension?\nThis is called glob and here is how to use it:\nimport glob\nfiles = glob.glob('/path/*.extension')\n\nEdit: and here is the documentation: http://docs.python.org/library/glob.html\n", "import os\nroot=\"/home\"\next = raw_inpu...
[ 4, 1, 0 ]
[ "You can write is as simple as:\nimport os\next = raw_input(\"Put file extension to search: \")\npath = raw_input(\"Dir to search in: \")\nmatching_files = [os.path.join(path, x) for x in os.listdir(path) if x.endswith(ext)]\n\n" ]
[ -1 ]
[ "file", "python", "search" ]
stackoverflow_0002442243_file_python_search.txt
Q: How to delete an element from a list while iterating over it in Python? Given a list of numbers: L = [1, 2, 3, 4, 5] How do I delete an element, let's say 3, from the list while I iterate over it? I tried the following code but it didn't do it: for el in L: if el == 3: del el A: Best is usually to p...
How to delete an element from a list while iterating over it in Python?
Given a list of numbers: L = [1, 2, 3, 4, 5] How do I delete an element, let's say 3, from the list while I iterate over it? I tried the following code but it didn't do it: for el in L: if el == 3: del el
[ "Best is usually to proceed constructively -- build the new list of the items you want instead of removing those you don't. E.g.:\nL[:] = [el for el in L if el != 3]\n\nthe list comprehension builds the desired list and the assignment to the \"whole-list slice\", L[:], ensure you're not just rebinding a name, but ...
[ 13 ]
[ "for el in L:\n if el == 2:\n del L[el]\n\n" ]
[ -4 ]
[ "python" ]
stackoverflow_0002442651_python.txt
Q: python send/receive hex data via TCP socket I have a ethenet access control device that is said to be able to communicate via TCP. How can i send a pachet by entering the HEX data, since this is what i have from their manual (a standard format for the communication packets sent and received after each command) Ca...
python send/receive hex data via TCP socket
I have a ethenet access control device that is said to be able to communicate via TCP. How can i send a pachet by entering the HEX data, since this is what i have from their manual (a standard format for the communication packets sent and received after each command) Can you please show some example code or links to g...
[ "Just encode the hex data in a string:\n'\\x34\\x82\\xf6'\n\n", "I'd use struct.pack to prepare the string of bytes to send, from the data you want to send. Be sure to start the packing format with > to mean you want big-endian ordering and standard sizes, since they document that so clearly!\nSo (I don't know w...
[ 6, 4 ]
[]
[]
[ "access_control", "python", "sockets", "tcp" ]
stackoverflow_0002442704_access_control_python_sockets_tcp.txt
Q: Setting package-wide variables during python setup.py install Is there a way that when a user types python setup.py install to install a Python package, setup.py can be made to set specific variables at the base of the pacakge? A common example would be to basically set mypackage.__revision__ to be the svn revisi...
Setting package-wide variables during python setup.py install
Is there a way that when a user types python setup.py install to install a Python package, setup.py can be made to set specific variables at the base of the pacakge? A common example would be to basically set mypackage.__revision__ to be the svn revision of the checkout if one is working from svn. Another example case...
[ "The SVN version can be set by SVN. You don't need to use setup.py to mess with that.\nSimply include the $Revision$ flag in the text somewhere and tell SVN to do replacements.\nGlobal options are usually handled by configuration files. Why mess with it at install time? It's much easier (and more flexible) to cre...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002442821_python.txt
Q: Calculating Hebrew date in Python I'd like to calculate Hebrew dates (primarily the current Hebrew date) in Python. Which library is mature, easy to use, and documented? I note these. There may be others. Python Date Utilities Library as discussed here Calendrical libhdate Python bindings This informal code list...
Calculating Hebrew date in Python
I'd like to calculate Hebrew dates (primarily the current Hebrew date) in Python. Which library is mature, easy to use, and documented? I note these. There may be others. Python Date Utilities Library as discussed here Calendrical libhdate Python bindings This informal code listing.
[ "The Python Date Utilities library (available on sourceforge) seems to be fine to do what you want, for more specific usage with hebrew dates you could have a look here, there are a lot of examples with many code snippets that should fit your needs i think.\n" ]
[ 5 ]
[]
[]
[ "calendar", "date", "datetime", "hebrew", "python" ]
stackoverflow_0002442674_calendar_date_datetime_hebrew_python.txt
Q: PyYAML parse into arbitary object I have the following Python 2.6 program and YAML definition (using PyYAML): import yaml x = yaml.load( """ product: name : 'Product X' sku : 123 features : - size : '10x30cm' weight : '10kg' ...
PyYAML parse into arbitary object
I have the following Python 2.6 program and YAML definition (using PyYAML): import yaml x = yaml.load( """ product: name : 'Product X' sku : 123 features : - size : '10x30cm' weight : '10kg' """ ) print type(x) print...
[ "So you have a dictionary with string keys and values that can be numbers, nested dictionaries, lists, and you'd like to wrap that into an instance which lets you use attribute access in lieu of dict indexing, and \"call with an index\" in lieu of list indexing -- not sure what \"strongly typed\" has to do with thi...
[ 8 ]
[]
[]
[ "python", "pyyaml", "yaml" ]
stackoverflow_0002442933_python_pyyaml_yaml.txt
Q: numpy.equal with string values The numpy.equal function does not work if a list or array contains strings: >>> import numpy >>> index = numpy.equal([1,2,'a'],None) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: function not supported for these types, and can't coerce safely to ...
numpy.equal with string values
The numpy.equal function does not work if a list or array contains strings: >>> import numpy >>> index = numpy.equal([1,2,'a'],None) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: function not supported for these types, and can't coerce safely to supported types What is the easiest...
[ "If you really need to use numpy, be more careful about what you pass in and it can work:\n>>> import numpy\n>>> a = numpy.array([1, 2, 'a'], dtype=object) # makes type of array what you need\n>>> numpy.equal(a, None)\narray([False, False, False], dtype=bool)\n\nSince you start with a list, there's a chance what yo...
[ 2, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002442799_numpy_python.txt
Q: Python - Check if numbers in list are factors of a number I have a list of numbers (integers) (say, from 1 to 10). They're not necessarily consecutive, but they are in ascending order. I've prompted the user multiple times to enter a choice of the available numbers. When that number is entered, it is removed fro...
Python - Check if numbers in list are factors of a number
I have a list of numbers (integers) (say, from 1 to 10). They're not necessarily consecutive, but they are in ascending order. I've prompted the user multiple times to enter a choice of the available numbers. When that number is entered, it is removed from the list along with any of its factors that may be there. I'...
[ "To check if there are any factors of the number guess remaining you can use any():\nhasfactors = any(guess % n == 0 for n in numbers)\n\nTo check if all the remaining numbers are prime, all() can be used. (Since you say you already prevented the user from inputting prime numbers I assume you have some kind of ispr...
[ 5, 3, 1 ]
[]
[]
[ "factors", "list", "python", "python_3.x" ]
stackoverflow_0002442972_factors_list_python_python_3.x.txt
Q: Concatenate generator and item I have a generator (numbers) and a value (number). I would like to iterate over these as if they were one sequence: i for i in tuple(my_generator) + (my_value,) The problem is, as far as I undestand, this creates 3 tuples only to immediately discard them and also copies items in "my...
Concatenate generator and item
I have a generator (numbers) and a value (number). I would like to iterate over these as if they were one sequence: i for i in tuple(my_generator) + (my_value,) The problem is, as far as I undestand, this creates 3 tuples only to immediately discard them and also copies items in "my_generator" once. Better approch wou...
[ "itertools.chain treats several sequences as a single sequence.\nSo you could use it as:\nimport itertools\n\ndef my_generator():\n yield 1\n yield 2\n\nfor i in itertools.chain(my_generator(), [5]):\n print i\n\nwhich would output:\n1\n2\n5\n\n", "itertools.chain()\n", "Try itertools.chain(*iterables)...
[ 46, 5, 5 ]
[]
[]
[ "generator", "iterator", "list_comprehension", "python" ]
stackoverflow_0002443252_generator_iterator_list_comprehension_python.txt
Q: Make Python Socket Server More Efficient I have very little experience working with sockets and multithreaded programming so to learn more I decided to see if I could hack together a little python socket server to power a chat room. I ended up getting it working pretty well but then I noticed my server's CPU usage...
Make Python Socket Server More Efficient
I have very little experience working with sockets and multithreaded programming so to learn more I decided to see if I could hack together a little python socket server to power a chat room. I ended up getting it working pretty well but then I noticed my server's CPU usage spiked up over 100% when I had it running in ...
[ "There are several possible race conditions in your code, but they would threaten correctness rather than performance: fixing them e.g. by locking would definitely not improve performance.\nRather, I'd focus on what good you think those threads are doing, at all -- since the core of your code is a select.select cal...
[ 6 ]
[]
[]
[ "multithreading", "python", "sockets" ]
stackoverflow_0002443226_multithreading_python_sockets.txt
Q: passing self data into a recursive function I'm trying to set a function to do something like this def __binaryTreeInsert(self, toInsert, currentNode=getRoot(), parentNode=None): where current node starts as root, and then we change it to a different node in the method and recursivly call it again. However, i ...
passing self data into a recursive function
I'm trying to set a function to do something like this def __binaryTreeInsert(self, toInsert, currentNode=getRoot(), parentNode=None): where current node starts as root, and then we change it to a different node in the method and recursivly call it again. However, i cannot get the 'currentNode=getRoot()' to work. I...
[ "While arg=None is the idiomatic Python sentinel value for an non-supplied argument, it doesn't have to be None. In Lua, for instance, the idiomatic non-supplied argument is an empty table. We can actually apply that to this case:\nclass Foo:\n sentinel = {}\n def bar(self, arg=sentinel):\n if arg is...
[ 2, 0, 0 ]
[ "def __binaryTreeInsert(self, toInsert, currentNode=0, parentNode=None):\n if not currentNode: \n currentNode = self.getRoot()\n\n" ]
[ -1 ]
[ "python", "recursion", "self" ]
stackoverflow_0002443264_python_recursion_self.txt
Q: Python Least-Squares Natural Splines I am trying to find a numerical package which will fit a natural spline which minimizes weighted least squares. There is a package in scipy which does what I want for unnatural splines. import numpy as np import matplotlib.pyplot as plt from scipy import interpolate, randn x ...
Python Least-Squares Natural Splines
I am trying to find a numerical package which will fit a natural spline which minimizes weighted least squares. There is a package in scipy which does what I want for unnatural splines. import numpy as np import matplotlib.pyplot as plt from scipy import interpolate, randn x = np.arange(0,5,1.0/6) xs = np.arange(0,5,...
[ "The spline.py file inside of this tar file from this page does a natural spline fit by default. There is also some code on this page that claims to mostly what you want. The pyD3D package also has a natural spline function in its pyDataUtils module. This last one looks the most promising to me. However, it doesn't...
[ 6 ]
[]
[]
[ "python", "scipy", "spline" ]
stackoverflow_0002441058_python_scipy_spline.txt
Q: How to make socket.recv(500) not stop a while loop I made an IRC bot which uses a while true loop to receive whatever is said. To receive I use recv(500), but that stops the loop if there isn't anything to receive, but i need the loop to continue even if there isn't anything to receive. I need a makeshift timer to...
How to make socket.recv(500) not stop a while loop
I made an IRC bot which uses a while true loop to receive whatever is said. To receive I use recv(500), but that stops the loop if there isn't anything to receive, but i need the loop to continue even if there isn't anything to receive. I need a makeshift timer to continue running. Example code: /A lot of stuff/ timer=...
[ "You can settimeout on the socket so that the call returns promptly (with a suitable exception, so you'll need a try/except around it) if nothing's there -- a timeout of 0.1 seconds actually works better than non-blocking sockets in most conditions.\n", "This is going to prove a bad way to design a network applic...
[ 2, 1, 1, 1 ]
[]
[]
[ "python", "sockets", "while_loop" ]
stackoverflow_0002443383_python_sockets_while_loop.txt
Q: Why can't I pass self as a named argument to an instance method in Python? This works: >>> def bar(x, y): ... print x, y ... >>> bar(y=3, x=1) 1 3 And this works: >>> class Foo(object): ... def bar(self, x, y): ... print x, y ... >>> z = Foo() >>> z.bar(y=3, x=1) 1 3 And even this works: >>> ...
Why can't I pass self as a named argument to an instance method in Python?
This works: >>> def bar(x, y): ... print x, y ... >>> bar(y=3, x=1) 1 3 And this works: >>> class Foo(object): ... def bar(self, x, y): ... print x, y ... >>> z = Foo() >>> z.bar(y=3, x=1) 1 3 And even this works: >>> Foo.bar(z, y=3, x=1) 1 3 But why doesn't this work in Python 2.x? >>> Foo.bar(s...
[ "z.bar is a bound method -- it already has an im_self attribute that becomes the first argument (conventionally named self) to the underlying function object, the bound method's im_func attribute. To override that you obviously need to re-bind im_self (edit: or call the im_func instead) -- whatever you do in terms...
[ 6 ]
[]
[]
[ "language_lawyer", "metaprogramming", "methods", "python", "python_2.x" ]
stackoverflow_0002443673_language_lawyer_metaprogramming_methods_python_python_2.x.txt
Q: Piping EOF problems with stdio and C++/Python I got some problems with EOF and stdio in a communication pipeline between a python process and a C++ program. I have no idea what I am doing wrong. When I see an EOF in my program I clear the stdin and next round I try to read in a new line. The problem is: for some r...
Piping EOF problems with stdio and C++/Python
I got some problems with EOF and stdio in a communication pipeline between a python process and a C++ program. I have no idea what I am doing wrong. When I see an EOF in my program I clear the stdin and next round I try to read in a new line. The problem is: for some reason the getline function immediatly (from the sec...
[ "communicate in python is a one shot function. It sends the given input to a process, closes the input stream, and reads the output streams, waiting for the process to terminate.\nThere is no way you can 'restart' the pipe with the same process after \"communicating\".\nConversely, on the other side of the pipe, wh...
[ 1 ]
[]
[]
[ "c++", "iostream", "pipe", "python", "stdin" ]
stackoverflow_0002443701_c++_iostream_pipe_python_stdin.txt
Q: Python 2.6 and 3.1.1, earlier version compatibility I ordered three books to start teaching myself Python - a beginning programming book, a computer science book that uses Python for all of its code references, and a book on Python network programming. Unfortunately, I was a little too quick on ordering them, beca...
Python 2.6 and 3.1.1, earlier version compatibility
I ordered three books to start teaching myself Python - a beginning programming book, a computer science book that uses Python for all of its code references, and a book on Python network programming. Unfortunately, I was a little too quick on ordering them, because I hadn't noticed the version differences. The beginne...
[ "99.8% of 2.3 code is valid in 2.6. The 3.x book should be able to backfill the 2.x knowledge from 2.4 on, assuming it actually touches upon the relevant subjects. See the various \"What's New\" documentation to see, well, what's new.\n" ]
[ 4 ]
[]
[]
[ "compatibility", "python", "version" ]
stackoverflow_0002443746_compatibility_python_version.txt
Q: Implementing the factory design pattern using metaclasses I found a lot of links on metaclasses, and most of them mention that they are useful for implementing factory methods. Can you show me an example of using metaclasses to implement the design pattern? A: I'd love to hear people's comments on this, but I th...
Implementing the factory design pattern using metaclasses
I found a lot of links on metaclasses, and most of them mention that they are useful for implementing factory methods. Can you show me an example of using metaclasses to implement the design pattern?
[ "I'd love to hear people's comments on this, but I think this is an example of what you want to do\nclass FactoryMetaclassObject(type):\n def __init__(cls, name, bases, attrs):\n \"\"\"__init__ will happen when the metaclass is constructed: \n the class object itself (not the instance of the class)...
[ 3, 2, 1 ]
[]
[]
[ "factory", "metaclass", "python" ]
stackoverflow_0002443648_factory_metaclass_python.txt
Q: Recognising tone of the audio I have a guitar and I need my pc to be able to tell what note is being played, recognizing the tone. Is it possible to do it in python, also is it possible with pygame? Being able of doing it in pygame would be very helpful. A: To recognize the frequency of an audio signal, you woul...
Recognising tone of the audio
I have a guitar and I need my pc to be able to tell what note is being played, recognizing the tone. Is it possible to do it in python, also is it possible with pygame? Being able of doing it in pygame would be very helpful.
[ "To recognize the frequency of an audio signal, you would use the FFT (fast Fourier transform) algorithm. As far as I can tell, PyGame has no means to record audio, nor does it support the FFT transform.\nFirst, you need to capture the raw sampled data from the sound card; this kind of data is called PCM (Pulse Cod...
[ 21, 19, 1, 1, 0 ]
[]
[]
[ "audio", "python" ]
stackoverflow_0001797631_audio_python.txt