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: how to return the looped values in a method in python/django that no using array how can I return a looped values in a method that no using array, for now i am using an array. here is my code : def get_ticket_sum_quantity(self, product_id, date_select): prod = Product.objects.get(id=product_id) sumOfQuanti...
how to return the looped values in a method in python/django that no using array
how can I return a looped values in a method that no using array, for now i am using an array. here is my code : def get_ticket_sum_quantity(self, product_id, date_select): prod = Product.objects.get(id=product_id) sumOfQuantity = Ticket.objects.filter(date_select=date_select, product=prod).aggregate(Sum('quant...
[ "Yes, you can use \n\nEither convert your function to a generator, so that after each invocation it returns the next value or Generates StopIteration if there is no value to return.\ndef get_ticket_available_product(self, date_select, client_id, quantity):\n client = Client.objects.get(id=client_id)\n prodCou...
[ 2 ]
[]
[]
[ "arrays", "django", "python" ]
stackoverflow_0008663798_arrays_django_python.txt
Q: Pprint module works slowly with Django in 32bits system I use Django on a 32 bits Ubuntu machine with Python 2.7. My development server has been slow all the time, taking about 15 seconds to render any page. I ran a cProfile test to see what works so slowly. Seems that it's the pprint module. Here's my statistics:...
Pprint module works slowly with Django in 32bits system
I use Django on a 32 bits Ubuntu machine with Python 2.7. My development server has been slow all the time, taking about 15 seconds to render any page. I ran a cProfile test to see what works so slowly. Seems that it's the pprint module. Here's my statistics: ncalls tottime percall cumtime percall filename:lineno...
[ "\nWhy is pprint._safe_repr so slow in Python 2.7 32 bits and fast in 64 bits?\n\nIt is not fast on 64 bits. Your colleague got much less ncalls.\nYou should investigate why a single GET leads to such a large number of calls to _safe_repr().\n" ]
[ 5 ]
[]
[]
[ "django", "performance", "profiling", "python" ]
stackoverflow_0008662050_django_performance_profiling_python.txt
Q: Asyncore data processing with Python 3 I'm using asynchat and trying to use python3. getting this error: error: uncaptured python exception, closing channel <irc.IRC connected at 0x9a5286c> (<class 'AttributeError'>:'str' object has no attribute 'more' [/usr/lib/python3.2/asyncore.py|write|89] [/usr/...
Asyncore data processing with Python 3
I'm using asynchat and trying to use python3. getting this error: error: uncaptured python exception, closing channel <irc.IRC connected at 0x9a5286c> (<class 'AttributeError'>:'str' object has no attribute 'more' [/usr/lib/python3.2/asyncore.py|write|89] [/usr/lib/python3.2 /asyncore.py|handle_write_...
[ "Per http://bugs.python.org/issue12523\n\nActually, the error is that in Python 3 you should use bytes objects when transmitting/receiving data over the network, not (unicode) strings.\n That is, replace '\\r\\n' with b'\\r\\n', etc.\nOf course, the error message should be made less obscure.\n\n", "The error see...
[ 3, 1 ]
[]
[]
[ "attributeerror", "exception", "python", "python_3.x" ]
stackoverflow_0006624651_attributeerror_exception_python_python_3.x.txt
Q: How to read the file contents from a file? Using Python3, hope to os.walk a directory of files, read them into a binary object (string?) and do some further processing on them. First step, though: How to read the file(s) results of os.walk? # NOTE: Execute with python3.2.2 import os import sys path = "/home/user...
How to read the file contents from a file?
Using Python3, hope to os.walk a directory of files, read them into a binary object (string?) and do some further processing on them. First step, though: How to read the file(s) results of os.walk? # NOTE: Execute with python3.2.2 import os import sys path = "/home/user/my-files" count = 0 successcount = 0 errorcoun...
[ "To read a binary file you must open the file in binary mode. Change\ninput = open(fullpath, \"r\")\n\nto \ninput = open(fullpath, \"rb\")\n\nThe result of the read() will be a bytes() object.\n", "As some of your files are binary, they cannot be successfully decoded into unicode characters that Python 3 uses to ...
[ 9, 3 ]
[]
[]
[ "os.walk", "python", "python_3.x" ]
stackoverflow_0008662641_os.walk_python_python_3.x.txt
Q: Convert string with parantheses into nested list I want to convert a string like this: "asd foo bar ( lol bla ( gee bee ) lee ) ree" to a list like this: ["asd","foo","bar",["lol","bla",["gee","bee"],"lee"],"ree"] Is there an easy solution? edit: It should work for any number and depth of parantheses, but it onl...
Convert string with parantheses into nested list
I want to convert a string like this: "asd foo bar ( lol bla ( gee bee ) lee ) ree" to a list like this: ["asd","foo","bar",["lol","bla",["gee","bee"],"lee"],"ree"] Is there an easy solution? edit: It should work for any number and depth of parantheses, but it only has to work for valid strings (no single parantheses...
[ "You can use Python's parser to do the job. Just help it a little:\n>>> a = \"asd foo bar ( lol bla ( gee bee ) lee ) ree\"\n>>> eval(str(a.split()).replace(\"'(',\", '[').replace(\"')'\",']'))\n['asd', 'foo', 'bar', ['lol', 'bla', ['gee', 'bee'], 'lee'], 'ree']\n\nIf you need it to be safe, use ast.literal_eval in...
[ 9, 1 ]
[]
[]
[ "list", "parsing", "python", "string" ]
stackoverflow_0008651110_list_parsing_python_string.txt
Q: Accessing Django's SQL Purifier Off-Line cursor.execute("SELECT word_id from words where word_name = '%s'" % (word)) if cursor.fetchone() == None: return False return True I was thinking that including the explicit ' on close of the %s format parameter might prevent this, but "'...
Accessing Django's SQL Purifier Off-Line
cursor.execute("SELECT word_id from words where word_name = '%s'" % (word)) if cursor.fetchone() == None: return False return True I was thinking that including the explicit ' on close of the %s format parameter might prevent this, but "'best'; DELETE * FROM words;" would be a reall...
[ "If you are not doing this from a django application then you don't need to rely on django's API to protect you from SQL injection attacks. The db API you are working in will provide its own methods for safely inputing parameters into SQL queries. For example if you are using SQLite your can reference the documenta...
[ 4, 1 ]
[]
[]
[ "database", "django", "python", "sql", "sql_injection" ]
stackoverflow_0008663741_database_django_python_sql_sql_injection.txt
Q: Unable to pass argument to the python using Optparse i have written this python program. whenever i run the script using parameters like python script.py -t It returns me current time in unixtime. but whenever i try to pass an argument like python script.py -c 1325058720 It says LMT is not defined. So i remove...
Unable to pass argument to the python using Optparse
i have written this python program. whenever i run the script using parameters like python script.py -t It returns me current time in unixtime. but whenever i try to pass an argument like python script.py -c 1325058720 It says LMT is not defined. So i removed the LMT from the LMT = time.strftime("%a, %d %b %Y %H:%...
[ "I was wrong to access the variable outside the function which didn't clicked me.\n elif options.conv:\n LMT = options.conv\n LMT= float(LMT)\n LMT = time.strftime(\"%a, %d %b %Y %H:%M:%S +0000\", time.localtime(LMT))\n print '%s'% LMT\n\n", "The parameters you pass in are completely i...
[ 1, 0 ]
[]
[]
[ "optparse", "python" ]
stackoverflow_0008653351_optparse_python.txt
Q: Returning Google Search To Python I am trying to get the first 20 results from a Google search. When I use urllib2.urlopen() it gives me an error and says I am forbidden. I heard that it has something to do with faking you user agent string, but i have next to no urllib2 experience and would be very grateful if an...
Returning Google Search To Python
I am trying to get the first 20 results from a Google search. When I use urllib2.urlopen() it gives me an error and says I am forbidden. I heard that it has something to do with faking you user agent string, but i have next to no urllib2 experience and would be very grateful if anyone could help. Thanks, giodamelio
[ "There are basically two ways - accessing Google's API directly, or using xGoogle package.\nGooogle's own API\nGoogle's JSON\\Atom API requires you to get an account and a key. It is the standard and preferred way to get searches in an automated way, which means you won't be banned from their service. The request i...
[ 2, 2, 2 ]
[]
[]
[ "python", "search", "urllib2" ]
stackoverflow_0004363861_python_search_urllib2.txt
Q: Django Sitemap for many sub-sites I have a app that creates websites for users. Each website has many sections, all with their own URL. I'm trying to find the most efficient way to build a sitemap for this app. I can successfully create one massive sitemap.xml file that lists all the links for the entire site. Bu...
Django Sitemap for many sub-sites
I have a app that creates websites for users. Each website has many sections, all with their own URL. I'm trying to find the most efficient way to build a sitemap for this app. I can successfully create one massive sitemap.xml file that lists all the links for the entire site. But this is over 100,000 urls. Another id...
[ "You can Subclass the Sitemap class to provide your own Sitemap implementation that will be referenced by your \"parent\" Sitemap. Take a look at the documentation for an example. Also, you'll have to generate a Sitemap index, as described here.\n" ]
[ 0 ]
[]
[]
[ "django", "python", "sitemap" ]
stackoverflow_0008662350_django_python_sitemap.txt
Q: How to invoke a external application(Windows based) independent of parent python script? I want to invoke an external GUI application from a python script which will be triggered upon some file upload to the server. I would like the process to be launched and kept running whereas the python script should continue...
How to invoke a external application(Windows based) independent of parent python script?
I want to invoke an external GUI application from a python script which will be triggered upon some file upload to the server. I would like the process to be launched and kept running whereas the python script should continue and eventually finish its job and quit. I have tried different options but none proved succes...
[ "had exactly the same problem and took me friggin ages to find it, but here is your answer:\nimport win32api\nwin32api.ShellExecute(0, \"open\", \"python.exe\", 'blah.py', '', 1)\n\nThis guarantees you an independent process - even after you exit the calling python program, this will continue to work.\n" ]
[ 1 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0008396173_python_windows.txt
Q: change a combobox of images to a formset of inputfile I have some models in my app,every one is going to have a set of images(n images),in order to handle this i designed these models: class Gallery(models.Model): HeadImage = models.ImageField(upload_to="gallery") class Image(models.Model): Image = models.I...
change a combobox of images to a formset of inputfile
I have some models in my app,every one is going to have a set of images(n images),in order to handle this i designed these models: class Gallery(models.Model): HeadImage = models.ImageField(upload_to="gallery") class Image(models.Model): Image = models.ImageField(upload_to="gallery") Gallery = models.ForeignK...
[ "If the form you've provided is accurate, 'Tour' doesn't contain a gallery, it implements a gallery. Therefore, you'll probably have better luck using Django's multi-table inheritance. Try something like the following:\nclass Gallery(models.Model):\n head_image = models.ImageField(upload_to=\"gallery\")\n\nclass...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008664588_django_python.txt
Q: Python Mindwave Graphs I got a Neurosky Mindwave for Christmas and was immediately unimpressed with the standard software for it. So I took my basic understanding in python to it and quickly found my shortcomings. So I started poking around and found two pieces of code that I would like to combine. My intent is to...
Python Mindwave Graphs
I got a Neurosky Mindwave for Christmas and was immediately unimpressed with the standard software for it. So I took my basic understanding in python to it and quickly found my shortcomings. So I started poking around and found two pieces of code that I would like to combine. My intent is to create a live graphing util...
[ "It looks like, from thinkgear.py, ThinkGearProtocol is just a factory that uses ThinkGearMetaClass to generate objects whose type is the type of data that was returned. The following code - \nglobal packet_log\npacket_log = []\nlogging.basicConfig(level=logging.DEBUG)\n\nfor pkt in ThinkGearProtocol('/dev/rfcomm9'...
[ 2 ]
[]
[]
[ "graph", "python", "serial_port" ]
stackoverflow_0008650909_graph_python_serial_port.txt
Q: building pylibmc with sasl support I'm trying to build the latest version of pylibmc (1.2.2) to support SASL on CentOS 6. The documentation says that the build require libsasl2, which I have in /usr/lib64/, however, the build process for the python package does not seem to recognize the library is there. I build ...
building pylibmc with sasl support
I'm trying to build the latest version of pylibmc (1.2.2) to support SASL on CentOS 6. The documentation says that the build require libsasl2, which I have in /usr/lib64/, however, the build process for the python package does not seem to recognize the library is there. I build the package with: python setup.py instal...
[ "pylibmc uses libmemcached, so for support saml you should rebuild libmemcached with saml, for that you need to install saml libries, then rebuild libmemcached from source code.\n" ]
[ 1 ]
[]
[]
[ "libmemcache", "memcached", "python" ]
stackoverflow_0008410362_libmemcache_memcached_python.txt
Q: Pygame on Mac - How do I install? Doing this on a mac. I've installed the package from the website but when I run a script with import pygame it says it doesn't exist. Looked online and it says I need to run the configure.py file but I can't seem to locate that file. Any tips? Here is my code so far: import pygame...
Pygame on Mac - How do I install?
Doing this on a mac. I've installed the package from the website but when I run a script with import pygame it says it doesn't exist. Looked online and it says I need to run the configure.py file but I can't seem to locate that file. Any tips? Here is my code so far: import pygame screen = pygame.display.set_mode((64...
[ "The script is probably using a version of python that you did not install pygame into.\nI believe the pygame binary installer (which is what I assume you meant by \"package from the website\") installs into system python. Check which version you are using by default. This is what it should look like when you run...
[ 0 ]
[]
[]
[ "macos", "pygame", "python" ]
stackoverflow_0008266364_macos_pygame_python.txt
Q: Forcibly discarding Python Imaging Library images to reclaim memory I have a program that loads and processes lots of images, of this form: for fn in filenames: im = Image.open(fn) get_some_basic_stats(im) When run on many images the Python process ends up using large amounts of memory -- far more than an...
Forcibly discarding Python Imaging Library images to reclaim memory
I have a program that loads and processes lots of images, of this form: for fn in filenames: im = Image.open(fn) get_some_basic_stats(im) When run on many images the Python process ends up using large amounts of memory -- far more than any one image should account for. Needless to say this eventually results ...
[ "Nothing in python can explicitly destroyed. In CPython, everything is reference counted so it should be deallocated as soon as nothing references it. In your case that should be happening in the next iteration of the loop. You can force the cyclical garbage collector by running gc.collect() but I doubt that'll sol...
[ 3 ]
[]
[]
[ "memory", "python", "python_imaging_library" ]
stackoverflow_0008665199_memory_python_python_imaging_library.txt
Q: Trim scanned images with PIL? What would be the approach to trim an image that's been input using a scanner and therefore has a large white/black area? A: the entropy solution seems problematic and overly intensive computationally. Why not edge detect? I just wrote this python code to solve this same problem fo...
Trim scanned images with PIL?
What would be the approach to trim an image that's been input using a scanner and therefore has a large white/black area?
[ "the entropy solution seems problematic and overly intensive computationally. Why not edge detect?\nI just wrote this python code to solve this same problem for myself. My background was dirty white-ish, so the criteria that I used was darkness and color. I simplified this criteria by just taking the smallest of...
[ 4, 2 ]
[]
[]
[ "image_processing", "python", "python_imaging_library" ]
stackoverflow_0007528816_image_processing_python_python_imaging_library.txt
Q: SPOJ Fashion giving runtime error Python Problem description is here : http://www.spoj.pl/problems/FASHION/ Process : Took two lists as input , sort them using the sort() method in Python and then print the sum Code : import sys,os #Need to maximize the product of two lists def process(index,line): p=li...
SPOJ Fashion giving runtime error Python
Problem description is here : http://www.spoj.pl/problems/FASHION/ Process : Took two lists as input , sort them using the sort() method in Python and then print the sum Code : import sys,os #Need to maximize the product of two lists def process(index,line): p=line.split(" ") #print 'Line after splitting...
[ "That is what SPOJ shows it expect:\nInput:\n2\n2\n1 1\n3 2\n3\n2 3 2\n1 3 2\n\nOutput:\n5\n15\n\nHowever, trying to run your program produces:\n2\n2\n1 1\n3 2\n5 <- that is the output for the first contest. should not output yet\n3\n2 3 2\nTraceback (most recent call last):\n File \"dasdsad.py\", line 35, in...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0008665135_python.txt
Q: How to maintain server-initiated FTP connection between client requests in Python/Django? I'm going to use ftplib to open up an FTP connection to an FTP server provided by the user. The client will be sending FTP commands to my django server via Ajax, which will then be forwarded to the FTP server the user provid...
How to maintain server-initiated FTP connection between client requests in Python/Django?
I'm going to use ftplib to open up an FTP connection to an FTP server provided by the user. The client will be sending FTP commands to my django server via Ajax, which will then be forwarded to the FTP server the user provided. However, I'd like to not have to create a new FTP server connection every time the client s...
[ "You'll need to use a persistent connection framework as what you're trying to achieve really isn't what HTTP was meant for (in the sense that HTTP commands are stateless and independent), and thus not what Django is built for. There are a number of options, but since it seems you are in a restricted environment yo...
[ 0, 0 ]
[]
[]
[ "django", "ftp", "html", "python" ]
stackoverflow_0008663391_django_ftp_html_python.txt
Q: Python regex- match a string like MGRoad to a sting like MG_Road I am very new to python and I want to match a pattern which comes from a list and if matches return the pattern. List contains names of areas in a city and I need to find if a area is present in a url like www.abc.com/category-city_area_name-deal/ ...
Python regex- match a string like MGRoad to a sting like MG_Road
I am very new to python and I want to match a pattern which comes from a list and if matches return the pattern. List contains names of areas in a city and I need to find if a area is present in a url like www.abc.com/category-city_area_name-deal/ city=[AreaName] I need to match AreaName in the url regardless of un...
[ "If you want to ignore underscores and upper/lower case, you can try this without using regex:\nurl = \"www.abc.com/category-city_area_name-deal/\"\ncity = \"AreaName\"\n\nif city.replace('_', '').lower() in url.replace('_', '').lower():\n print 'ok'\n\nThe a.replace('_', '').lower() removes all underscores from...
[ 4 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008665773_python_regex.txt
Q: Improving performance of django DB query I'm using django/apache/sqlite3 and I have a django model that looks like this: class Temp_entry(models.Model): dateTime = models.IntegerField() #datetime sensor = models.IntegerField() # id of sensor temp = models.IntegerField() # temp as temp in Kelvin *...
Improving performance of django DB query
I'm using django/apache/sqlite3 and I have a django model that looks like this: class Temp_entry(models.Model): dateTime = models.IntegerField() #datetime sensor = models.IntegerField() # id of sensor temp = models.IntegerField() # temp as temp in Kelvin * 100 I'm trying to get the last 300 Temp_entr...
[ "If caching is acceptable it always should be used. Something like:\nfrom django.core.cache import cache\n\ncached = cache.get('temp_entries')\nif cached:\n result = cached \nelse:\n result = Temp_entry.objects.filter(sensor=49).order_by('dateTime').reverse().values_list()[:300]\n cache.set('temp_entries',...
[ 7, 3, 2, 0 ]
[]
[]
[ "django", "performance", "python", "sqlite" ]
stackoverflow_0008652950_django_performance_python_sqlite.txt
Q: Matplotlib transparent fill over an image I am trying to draw a transparent polygon over an image on a canvas using matplotlib: Code from canvas class: def update_figure(self, dataOverride = None): if self.data is not None or dataOverride is not none: FigureCanvas.updateGeometry(self) self.axes...
Matplotlib transparent fill over an image
I am trying to draw a transparent polygon over an image on a canvas using matplotlib: Code from canvas class: def update_figure(self, dataOverride = None): if self.data is not None or dataOverride is not none: FigureCanvas.updateGeometry(self) self.axes.clear() if dataOverride is not None: ...
[ "I don't completely understand your code (please provide a fully working example), but the following code puts a polygon over an imshow image:\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.patches import Polygon\n\ndata = np.random.rand(4, 4)\nplt.imshow(data)\n\npointListX = (0, 2, 1)\npoin...
[ 7 ]
[]
[]
[ "image", "matplotlib", "python" ]
stackoverflow_0008663778_image_matplotlib_python.txt
Q: Extract signing certs from a PKCS7 SignedData structure with m2crypto I am trying to use M2Crypto to extract the signing certificates from a Windows PE file. According to the MS specification the data is stored in a PKCS#7 SignedData structure (stored in ASN.1 format, not the base64). I can't seem to get the binar...
Extract signing certs from a PKCS7 SignedData structure with m2crypto
I am trying to use M2Crypto to extract the signing certificates from a Windows PE file. According to the MS specification the data is stored in a PKCS#7 SignedData structure (stored in ASN.1 format, not the base64). I can't seem to get the binary format to load since it is not in PEM. Pardon my ignorance with the cryp...
[ "I think there's more to this than just reading the certificate in PKCS7, unless you know absolutely what the offset & struct are. \nYou might want to take a look at either:\nhttp://msdn.microsoft.com/en-us/library/aa380395(v=VS.85).aspx for the extraction process\nOr possibly\nhttp://msdn.microsoft.com/en-us/libra...
[ 0 ]
[]
[]
[ "m2crypto", "python" ]
stackoverflow_0006669912_m2crypto_python.txt
Q: Including user statistics for multiple views I have a navigation bar that displays "login" and "register" when the user is not signed in. When the user is signed in, the navigation bar will display the user's name and the number of messages he has in his inbox. The problem is that the navigation page is present on...
Including user statistics for multiple views
I have a navigation bar that displays "login" and "register" when the user is not signed in. When the user is signed in, the navigation bar will display the user's name and the number of messages he has in his inbox. The problem is that the navigation page is present on around 50 pages, so there are around 50 view func...
[ "You could create a custom template tag, as DrTyrsa suggested, or you could create context processor.\n", "The simplest way is to include django.contrib.auth.context_processors.auth to the TEMPLATE_CONTEXT_PROCESSORS configuration in your settings.py. As described in the docs it wil add a user and perms variable ...
[ 2, 2, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008666161_django_python.txt
Q: Python 2.7 While Loop time while True: now = datetime.datetime.now() if now.second == 1: print "One" my program print One about 7 times. How do I make it print only once? A: Your computer is too fast. It takes the current time, tests whether the current second is one and then again. And since i...
Python 2.7 While Loop time
while True: now = datetime.datetime.now() if now.second == 1: print "One" my program print One about 7 times. How do I make it print only once?
[ "Your computer is too fast.\nIt takes the current time, tests whether the current second is one and then again. And since it is so fast it can do this within less than one second, you get more lines of output.\nMake it wait after each iteration:\nwhile True:\n now = datetime.datetime.now()\n if now.second == ...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008666965_python.txt
Q: Cgi not executing python I'm having a problem getting CGI to work for Python. I've added Options ExecCGI AddHandler cgi-script cgi py pl inside /etc/apache2/sites-available/default within and now Perl works, but Python gives out a 500 Internal Server Error.. EDIT: This if the current 'default' file <VirtualHost...
Cgi not executing python
I'm having a problem getting CGI to work for Python. I've added Options ExecCGI AddHandler cgi-script cgi py pl inside /etc/apache2/sites-available/default within and now Perl works, but Python gives out a 500 Internal Server Error.. EDIT: This if the current 'default' file <VirtualHost *:80> ServerAdmin webmast...
[ "Try renaming the .py files to .cgi, it worked for me.\n", "Try using the python CGI server instead of apache,if that can meet your needs.\npython -m CGIHTTPServer {port number:default 8000}\n\n" ]
[ 1, 0 ]
[]
[]
[ "apache2", "cgi", "python" ]
stackoverflow_0002215534_apache2_cgi_python.txt
Q: Can not check form values with a ChoiceField I am working on a catalog of classified grouped by categories. However when I submit my form, I get the following error message: Caught ValueError while rendering: Cannot assign "u'9'": "Classified.category" must be a "Category" instance. I believe this is because Djan...
Can not check form values with a ChoiceField
I am working on a catalog of classified grouped by categories. However when I submit my form, I get the following error message: Caught ValueError while rendering: Cannot assign "u'9'": "Classified.category" must be a "Category" instance. I believe this is because Django expects a Category objects instead of a simple ...
[ "Quick solution is to save category manually\nclass ClassifiedForm(forms.ModelForm):\n # [...]\n\n category = forms.ChoiceField(label=u'Category', required=True,\n choices=Category.objects.categoryTree(), widget=forms.Select())\n\n class Meta:\n exclude=('category',)\n\n def save(self)...
[ 1, 0 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0008667684_django_django_forms_django_models_python.txt
Q: SQL Alchemy group_by in Query I am trying to select a grouped average. a1_avg = session.query(func.avg(Table_A.a1_value).label('a1_avg'))\ .filter(between(Table_A.a1_date, '2011-10-01', '2011-10-30'))\ .group_by(Table_A.a1_group) I have tried a few different iterations of this query and this is ...
SQL Alchemy group_by in Query
I am trying to select a grouped average. a1_avg = session.query(func.avg(Table_A.a1_value).label('a1_avg'))\ .filter(between(Table_A.a1_date, '2011-10-01', '2011-10-30'))\ .group_by(Table_A.a1_group) I have tried a few different iterations of this query and this is as close as I can get to what I nee...
[ "I would guess that you are just missing the group identifier (a1_group) in the result. Also (given I understand your model correctly), you need to add a group by clause also for a1_loc column:\nedit-1: updated the query due to question specificaion\na1_avg = session.query(Table_A.a1_loc, Table_A.a1_group, func.avg...
[ 3 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0008667960_python_sqlalchemy.txt
Q: unable to import with git-p4 on windows I've been trying to import a p4 depot path to git using git-p4 python script. After configuring my environment (git 1.7.1, python 2.7, Windwos XP, p4 env variables) I tried to run the git-p4 script, geetting the following ouptut: F:\gitp4>c:\Python27\python.exe git-p4.py clo...
unable to import with git-p4 on windows
I've been trying to import a p4 depot path to git using git-p4 python script. After configuring my environment (git 1.7.1, python 2.7, Windwos XP, p4 env variables) I tried to run the git-p4 script, geetting the following ouptut: F:\gitp4>c:\Python27\python.exe git-p4.py clone --destination=master //depot/quake/main/.....
[ "In response to Restuta's comment:\n\nI've created a batch file to call \"git.cmd\" exec file on a custom path. Contents of my batch file:\n@\"C:\\Program Files\\Git\\cmd\\git.cmd\" %*\nI've modified the git-p4.py file to call that batch file instead of just \"git\".\nEg. (line 2237) Original line: init_cmd = [ \"g...
[ 3 ]
[]
[]
[ "git", "git_p4", "perforce", "python" ]
stackoverflow_0005299122_git_git_p4_perforce_python.txt
Q: How do I transfer data between two computers ? I have two computers on a network. I'll call the computer I'm working on computer A and the remote computer B. My goal is to send a command to B, gather some information, transfer this information to computer A and use this in some meaningfull way. My current method f...
How do I transfer data between two computers ?
I have two computers on a network. I'll call the computer I'm working on computer A and the remote computer B. My goal is to send a command to B, gather some information, transfer this information to computer A and use this in some meaningfull way. My current method follows: Establish a connection to B with paramiko. ...
[ "I would recommend taking a look at twisted. It's the best python framework I've encountered for custom client/server applications like the one you describe.\n", "I have been doing something similar on a larger scale (with 15 clients). I use the pexpect module to do essentially ssh commands on the remote machine ...
[ 1, 0, 0 ]
[]
[]
[ "python", "rpc" ]
stackoverflow_0008649405_python_rpc.txt
Q: How to choose earliest NRF week number, from a set of date ranges in python? I have a list of 104 consecutive weeks. The week numbers come from the National Retail Foundation Calendar. So week 1 will basically be the first week in February. I'm finding ranges of weeks inside this two year list of dates. I'll as...
How to choose earliest NRF week number, from a set of date ranges in python?
I have a list of 104 consecutive weeks. The week numbers come from the National Retail Foundation Calendar. So week 1 will basically be the first week in February. I'm finding ranges of weeks inside this two year list of dates. I'll assume just two ranges for the point of my question. I want to pick the weeks that ...
[ "It looks to me like you simply want to ignore the year in your comparison function (to find the min/max dates). Since your data set is small, why not just iterate over all weeks and perform comparisons based on month & date only?\n" ]
[ 0 ]
[]
[]
[ "date", "python" ]
stackoverflow_0008662371_date_python.txt
Q: MySQL database being hit too many times with django query I'm using django-favorites to pull the list of objects faved by a user. The app has a model and a manager class FavoriteManager(models.Manager): """ A Manager for Favorites """ def favorites_for_user(self, user): """ Returns Favorites f...
MySQL database being hit too many times with django query
I'm using django-favorites to pull the list of objects faved by a user. The app has a model and a manager class FavoriteManager(models.Manager): """ A Manager for Favorites """ def favorites_for_user(self, user): """ Returns Favorites for a specific user """ return self.get_query_se...
[ "You can decide between several solutions:\n\nGeneric relation pre-fetching, you can use this snippet like this example app.\nIdentity map/caching, use the content type and object id to make the key to cache the model, here is an example you can take the code inside __getstate__ and __setstate__ and make a template...
[ 10, 2 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0008667705_django_mysql_python.txt
Q: python %s format specifier failing for utf-8 values I have the following python code which pushes data to db: cursor.execute("INSERT INTO "+ DATA_TABLE + """ (fk_id, title, streetaddress,json) values (%(fk_id)s, %(title)s, %(address)s, %(json)s ) """ ,( result)) But I get the er...
python %s format specifier failing for utf-8 values
I have the following python code which pushes data to db: cursor.execute("INSERT INTO "+ DATA_TABLE + """ (fk_id, title, streetaddress,json) values (%(fk_id)s, %(title)s, %(address)s, %(json)s ) """ ,( result)) But I get the error: File "/usr/lib/pymodules/python2.6/MySQLdb/connect...
[ "you should try to convert all your string in unicode\ncursor.execute(u\"INSERT INTO \"+ unicode(DATA_TABLE) + u\"\"\" (fk_id, title, streetaddress,json) \n values (%(fk_id)s, %(title)s, %(address)s, %(json)s ) \"\"\" ,(\n result))\n\nand pass charset=\"utf-8\" to connect as specifie...
[ 4, 0 ]
[]
[]
[ "mysql", "python", "utf_8" ]
stackoverflow_0008668345_mysql_python_utf_8.txt
Q: Real time chart (SVG) + AJAX/Javascript/Jquery + StdOut + Python + I dont really know myself I am not sure how to accurately describe my problem , and right now i have a total mess in my head , so please deal with it and correct me if i am wrong , and i will be for sure. MAIN GOAL: Is to built a real time line cha...
Real time chart (SVG) + AJAX/Javascript/Jquery + StdOut + Python + I dont really know myself
I am not sure how to accurately describe my problem , and right now i have a total mess in my head , so please deal with it and correct me if i am wrong , and i will be for sure. MAIN GOAL: Is to built a real time line chart , which updates itself without web page reloading based on data , which comes from stdout . S...
[ "Highcharts are nice for a static data or for data updated at max 1000ms speed. Try changing update rate to 100ms - it looks like crap.\nI would recommend Smoothie Charts. Fits perfectly for your scenario.\n", "What you want to do is use JavaScript to render the chart, for example using a library such as highchar...
[ 4, 2, 2, 0 ]
[]
[]
[ "ajax", "cgi", "charts", "python", "svg" ]
stackoverflow_0005808819_ajax_cgi_charts_python_svg.txt
Q: PIL - make 1 PNG from JPG and PNG frame I have 2 images: PNG (99x97) with white, rotated frame and rest is in full transparency. JPG - is my generated thumbnail (80x80) Now I want to put thumbnail into my frame so it looks like some kind of painting. What should I do? EDIT: I forgot to add, that picture must be ...
PIL - make 1 PNG from JPG and PNG frame
I have 2 images: PNG (99x97) with white, rotated frame and rest is in full transparency. JPG - is my generated thumbnail (80x80) Now I want to put thumbnail into my frame so it looks like some kind of painting. What should I do? EDIT: I forgot to add, that picture must be under the frame. Frame image I have some scri...
[ "Here you go. This should take original picture and paste transparent frame image above it. Both pictures should be 100x100, but you can add needed resizing.\nfrom PIL import Image\n\nframe = Image.open('frame.png')\nimg = Image.open('image.jpg')\n\nimg_dest = img.copy().convert('RGBA')\nimg_dest.paste(frame, (0, 0...
[ 0 ]
[]
[]
[ "image", "png", "python", "python_imaging_library" ]
stackoverflow_0008668006_image_png_python_python_imaging_library.txt
Q: How can I call an already locked code block from witin the class again? I am working with locks within a class to avoid multiple threads adding the same elements to a list twice. However, my class gets stuck when I want to access a method protected by a lock from within the class itself. The class looks like this ...
How can I call an already locked code block from witin the class again?
I am working with locks within a class to avoid multiple threads adding the same elements to a list twice. However, my class gets stuck when I want to access a method protected by a lock from within the class itself. The class looks like this (simplified, so it does not make much sense anymore): import threading class...
[ "It looks to me like you need two versions of add()---one that acquires a lock and one that doesn't. get() should call the version that doesn't acquire a lock since it already has the lock.\nAlternatively, have you considered using an RLock object which (based on my reading of the doc) keeps track of recursive att...
[ 2, 1 ]
[]
[]
[ "locking", "python" ]
stackoverflow_0008668657_locking_python.txt
Q: Canvas Selection Tool? wxpython Is there a way to make a canvas selection tool in wxpython? LEFT BUTTON PRESSED: When the left button is pressed start drawing rectangle and update it until the user releases the left button. LEFT BUTTON RELEASED: Finish drawing rectangle It is something similar that you would see ...
Canvas Selection Tool? wxpython
Is there a way to make a canvas selection tool in wxpython? LEFT BUTTON PRESSED: When the left button is pressed start drawing rectangle and update it until the user releases the left button. LEFT BUTTON RELEASED: Finish drawing rectangle It is something similar that you would see in a paint program. If possible plea...
[ "You have an example of a drawing canvas in the source code downloads from wxPython in Action.\nThis is a canvas for freehand sketching. You can start from there to expand its functionality. \nThe simpler example is example1.py from Chapter-06 folder. There are several other examples in the same chapter with increa...
[ 1, 1, 1 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0008621423_python_wxpython_wxwidgets.txt
Q: Asynchronous background processes with web2py I need to to handle a large (time and memory-consuming) process asynchronously in a web2py application called inside a controller method. My specific use case is to call a process via stdlib.subprocess and wait for it to exit without blocking the web server, but I am o...
Asynchronous background processes with web2py
I need to to handle a large (time and memory-consuming) process asynchronously in a web2py application called inside a controller method. My specific use case is to call a process via stdlib.subprocess and wait for it to exit without blocking the web server, but I am open to alternative methods. Hands-on examples woul...
[ "Assuming you'll need to start multiple, possibly simultaneous, instances of the background task, the solution is a task queue. I've heard good things about Celery and RabbitMQ, if you're looking for 3rd-party options, and web2py includes it's own task queue system that might be sufficient for your needs. \nWith ei...
[ 7, 2, 1 ]
[]
[]
[ "asynchronous", "python", "python_2.x", "web2py" ]
stackoverflow_0008668379_asynchronous_python_python_2.x_web2py.txt
Q: Disable joining and abbreviations of similar arguments in argparse I would like to be able in my program to support several short-form arguments like '-c' and -ct'. The problem is that for short-form arguments, argparse has the ability to join them, so it considers that '-ct' is in fact '-c' and '-t', which is NOT...
Disable joining and abbreviations of similar arguments in argparse
I would like to be able in my program to support several short-form arguments like '-c' and -ct'. The problem is that for short-form arguments, argparse has the ability to join them, so it considers that '-ct' is in fact '-c' and '-t', which is NOT what I want and could produce weird bugs (since I also have a separate ...
[ "I believe convention dictates that \"short\" arguments are only a single character and they may be combined into a single word on the command line so that \"-ct\" is equivalent to \"-c -t\". My guess is that argparse doesn't support two-char \"short\" arguments like \"-ct\" so behavior is undefined.\n" ]
[ 4 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0008669123_argparse_python.txt
Q: Django GenericForeignKey lookup for a given model I use a voting app (django-ratings if that makes any difference) which uses django's GenericForeignKey, has a ForeignKey to User, and several other fields like date of latest change. I'd like to get all the objects of one content type, that a single user voted for ...
Django GenericForeignKey lookup for a given model
I use a voting app (django-ratings if that makes any difference) which uses django's GenericForeignKey, has a ForeignKey to User, and several other fields like date of latest change. I'd like to get all the objects of one content type, that a single user voted for ordered by date of latest change. As far as I understan...
[ "Have you checked out select_related()? That may help.\n\nReturns a QuerySet that will automatically \"follow\" foreign-key relationships, selecting that additional related-object data when it executes its query. This is a performance booster which results in (sometimes much) larger queries but means later use of f...
[ 1, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008636845_django_python.txt
Q: how to efficiently store occupied/unoccupied 2D space (with insertion) I have an X by Y space, where X and Y are determined by the sizes of the rectangles given to me. I'm inserting oriented rectangles of a certain size into the space, one at a time. Each insertion is as far left as possible, and then as far up ...
how to efficiently store occupied/unoccupied 2D space (with insertion)
I have an X by Y space, where X and Y are determined by the sizes of the rectangles given to me. I'm inserting oriented rectangles of a certain size into the space, one at a time. Each insertion is as far left as possible, and then as far up as possible (so as close to (0,0) as I can). What's the best way to represe...
[ "If you are trying to efficiently pack rectangles, there are some established algorithms. Here's a Python implementation of one particular algorithm. There's also an article on packing lightmaps here for which I have a Python version (I honestly don't remember whether I ported it myself, or got it from somewhere el...
[ 4, 0, 0 ]
[]
[]
[ "algorithm", "data_structures", "python", "python_3.x" ]
stackoverflow_0008669275_algorithm_data_structures_python_python_3.x.txt
Q: Alternative for scipy.stats.norm.pdf? Does anyone know of an alternative for scipy.stats.norm.pdf()? I'm hosting my python site on Google App Engine and Google doesn't support SciPy. I've tried this function, but that didn't return the same results as scipy: def normpdf(x, mu, sigma): u = (x-mu)/abs(sigma) ...
Alternative for scipy.stats.norm.pdf?
Does anyone know of an alternative for scipy.stats.norm.pdf()? I'm hosting my python site on Google App Engine and Google doesn't support SciPy. I've tried this function, but that didn't return the same results as scipy: def normpdf(x, mu, sigma): u = (x-mu)/abs(sigma) y = (1/(sqrt(2*pi)*abs(sigma)))*exp(-u*u/2...
[ "You got tricked by pythons integer division arithmetics! Here is some working code:\nfrom __future__ import division\n\nimport scipy.stats\nfrom numpy import *\n\ndef normpdf(x, mu, sigma):\n u = (x-mu)/abs(sigma)\n y = (1/(sqrt(2*pi)*abs(sigma)))*exp(-u*u/2)\n return y\n\n\nprint scipy.stats.norm.pdf(20,...
[ 9, 6 ]
[]
[]
[ "math", "normal_distribution", "python", "scipy" ]
stackoverflow_0008669235_math_normal_distribution_python_scipy.txt
Q: Access request in django custom template tags My code in myapp_extras.py: from django import template register = template.Library() @register.inclusion_tag('new/userinfo.html') def address(): address = request.session['address'] return {'address':address} in 'settings.py': TEMPLATE_CONTEXT_PROCESSORS =(...
Access request in django custom template tags
My code in myapp_extras.py: from django import template register = template.Library() @register.inclusion_tag('new/userinfo.html') def address(): address = request.session['address'] return {'address':address} in 'settings.py': TEMPLATE_CONTEXT_PROCESSORS =( "django.core.context_processors.auth", "dj...
[ "request is not a variable in that scope. You will have to get it from the context first. Pass takes_context to the decorator and add context to the tag arguments.\nLike this:\n@register.inclusion_tag('new/userinfo.html', takes_context=True)\ndef address(context):\n request = context['request']\n address = re...
[ 172, 12, 9 ]
[]
[]
[ "django", "django_custom_tags", "django_templates", "python" ]
stackoverflow_0002160261_django_django_custom_tags_django_templates_python.txt
Q: Indices of k-minimum values along an axis of a numpy array Is there a way to return the indices of k-minimum values along an axis of a numpy array without using loops? A: import numpy as np x = np.array([[5, 2, 3],[1, 9, 2]]) # example data k = 2 # return the indices of the 2 smallest values np.argsort(x, axis=1...
Indices of k-minimum values along an axis of a numpy array
Is there a way to return the indices of k-minimum values along an axis of a numpy array without using loops?
[ "import numpy as np\nx = np.array([[5, 2, 3],[1, 9, 2]]) # example data\nk = 2 # return the indices of the 2 smallest values\nnp.argsort(x, axis=1)[:,0:k] # by row\n\narray([[1, 2],\n [0, 2]])\n\n" ]
[ 7 ]
[]
[]
[ "arrays", "indices", "minim", "numpy", "python" ]
stackoverflow_0008669261_arrays_indices_minim_numpy_python.txt
Q: Building XML from a Python structure is it possible to build an XML string from a Python structure (e.g. nested lists, dictionaries, etc.) or it is a non-sense question? Is there any standard tool? Thanks A: There is no object-to-XML serialization in the standard library, but there is pyxser. A: If you need so...
Building XML from a Python structure
is it possible to build an XML string from a Python structure (e.g. nested lists, dictionaries, etc.) or it is a non-sense question? Is there any standard tool? Thanks
[ "There is no object-to-XML serialization in the standard library, but there is pyxser.\n", "If you need some custom format, you can use xml.etree.ElementTree to programatically generate such a format. For example:\nfrom xml.etree import ElementTree\n\ndef dict2xml(d, parent=None):\n if parent is None:\n ...
[ 4, 3 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0008666972_python_xml.txt
Q: PyQt4 - Distinguish Window Resizing from Animation Resizing I need to catch a resize event in my PyQt4 application. However, I need to know whether the resizing was triggered by code (or the User), or is due to a QPropertyAnimation. Is there anyway to differentiate the two? Something like... event.isAnimation...
PyQt4 - Distinguish Window Resizing from Animation Resizing
I need to catch a resize event in my PyQt4 application. However, I need to know whether the resizing was triggered by code (or the User), or is due to a QPropertyAnimation. Is there anyway to differentiate the two? Something like... event.isAnimation() Thanks!
[ "Have you tried to check the QEvent::spontaneous() property ? It return True if the resize is originated from a system event, otherwise return False.\n" ]
[ 1 ]
[]
[]
[ "animation", "events", "pyqt4", "python", "resize" ]
stackoverflow_0008628402_animation_events_pyqt4_python_resize.txt
Q: paramiko sftp.get I am trying to use paramiko to download a file via SFTP. I create the SFTP object like this: transport = paramiko.Transport((sftp_server, sftp_port)) transport.connect(username = sftp_login, password = sftp_password) sftp = paramiko.SFTPClient.from_transport(transport) sftp.get("file_name", '.', ...
paramiko sftp.get
I am trying to use paramiko to download a file via SFTP. I create the SFTP object like this: transport = paramiko.Transport((sftp_server, sftp_port)) transport.connect(username = sftp_login, password = sftp_password) sftp = paramiko.SFTPClient.from_transport(transport) sftp.get("file_name", '.', None) and, I get the e...
[ "The following code worked for me in Ubuntu 11.10:\nsftp.get(\"file_name\", \"file_name\")\n\nI just made a couple of changes that shouldn't affect to your problem:\n\nlocalpath: Used full path to the local file name instead of just '.' (directories aren't allowed)\ncallback: Removed it since None is already the de...
[ 6 ]
[]
[]
[ "paramiko", "python", "sftp" ]
stackoverflow_0008669165_paramiko_python_sftp.txt
Q: How do I make one python dictionary to csv with headers? I've been sitting for some time with a task to import serverlogs from a .txt file, write it out to a python dictionary and write it further out to a csv file to make it readable in a database. When I open it in fx. excel, I want it to be listed with headers....
How do I make one python dictionary to csv with headers?
I've been sitting for some time with a task to import serverlogs from a .txt file, write it out to a python dictionary and write it further out to a csv file to make it readable in a database. When I open it in fx. excel, I want it to be listed with headers. EDIT: I need this to be generic in the way that I can load a ...
[ "The problem is that the code attempts to write a dictionary of lists and csv.DictWriter expects a list of dictionaries.\nThe right way to parse your data to work with the csv module would be to store each row as a dictionary. Hence instead of having something like this:\ndictionary = {'time': allTimes,\n ...
[ 4 ]
[]
[]
[ "csv", "database", "logging", "python" ]
stackoverflow_0008669047_csv_database_logging_python.txt
Q: raising exceptions issue here is my code: class longInputException(Exception): def __init__(self, length, max): Exception.__init__(self) self.length = len(length) self.max = max try: max = 3 s = raw_input('Enter something-->') if len(s) > max: raise longInputExcepti...
raising exceptions issue
here is my code: class longInputException(Exception): def __init__(self, length, max): Exception.__init__(self) self.length = len(length) self.max = max try: max = 3 s = raw_input('Enter something-->') if len(s) > max: raise longInputException(s, max) except longInputEx...
[ "self is the name of the current object within __init__() method (because you have provided self as the first argument in __init__()'s definition), it is not accessible outside of it.\nOptionally you can do something like that (although this is not something you should do, as this may confuse people about which var...
[ 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008670489_python.txt
Q: Is 'import MyClass.MyClass' is equal to 'from MyClass import MyClass ' in python If both , ModuleName is : MyClass.py and Class inside is : class MyClass : ... A: No, they're not the same. The first won't even work; an ordinary import statement imports modules only. The second will put MyClass.MyClass in you...
Is 'import MyClass.MyClass' is equal to 'from MyClass import MyClass ' in python
If both , ModuleName is : MyClass.py and Class inside is : class MyClass : ...
[ "No, they're not the same. The first won't even work; an ordinary import statement imports modules only. The second will put MyClass.MyClass in your scope as MyClass.\n", "The import <x> only allows you to import modules -- you can't do import <module>.<Class>. You can only import a specific class using the from ...
[ 2, 1 ]
[]
[]
[ "import", "python" ]
stackoverflow_0008670556_import_python.txt
Q: Python elements retrieved from container (list, dict, tuple etc) passed by reference or value? I have a function that updates data in a cache (implemented as a dictionary). def updateCache(name, new_data): global cache info = cache[name] # is this being passed to me as a val or ref? datarows = info['d...
Python elements retrieved from container (list, dict, tuple etc) passed by reference or value?
I have a function that updates data in a cache (implemented as a dictionary). def updateCache(name, new_data): global cache info = cache[name] # is this being passed to me as a val or ref? datarows = info['datarows'] datarows.append(new_data) # These will not be necessary if I was dealing with ref...
[ "Let's just try this out, shall we:\ndef updateCache(name, new_data):\n global cache\n info = cache[name]\n datarows = info['datarows']\n datarows.append(new_data)\n\n\ncache = {'foo': {'datarows': []}, 'bar': {'datarows': []}}\n\nprint cache\nupdateCache('foo', 'bar')\nprint cache\n\noutputs:\n{'foo': ...
[ 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008670060_python.txt
Q: Creating pooled objects (Python) I am writing a script that requires interacting with several databases (not concurrently). In order to facilitate this, I am mainting the db related information (connections etc) in a dictionary. As an aside, I am using sqlAlchemy for all interaction with the db. I don't know wheth...
Creating pooled objects (Python)
I am writing a script that requires interacting with several databases (not concurrently). In order to facilitate this, I am mainting the db related information (connections etc) in a dictionary. As an aside, I am using sqlAlchemy for all interaction with the db. I don't know whether that is relevant to this question o...
[ "The code you have is perfectly good. \nJust because you use the same variable name does not mean you are overriding (or freeing) another object that was assigned to that variable. In fact, you can look at the names as temporary labels to your objects.\nNow, you store the final objects in the global dictionary pool...
[ 4 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0008670475_python_sqlalchemy.txt
Q: How do I select from a many-to-many intermediate model in django? I have models of books and people: from django.db import models class Book(models.Model): author = models.ManyToManyField('Person') class Person(models.Model): name = models.CharField(max_length=16) I simplified them a bit here. How do I ...
How do I select from a many-to-many intermediate model in django?
I have models of books and people: from django.db import models class Book(models.Model): author = models.ManyToManyField('Person') class Person(models.Model): name = models.CharField(max_length=16) I simplified them a bit here. How do I craft a django query to get all of the authors of the books? With SQL I...
[ "As easy as 1,2,3 with Filtering on annotations:\nfrom django.db.models import Count\n\nPerson.objects.annotate(count_book=Count('book')).filter(count_book__gt=0)\n\nFor curiosity, i generated the SQL from each of the ways proposed on this topic:\nIn [9]: Person.objects.annotate(count_book=Count('book')).filter(cou...
[ 3, 3, 1 ]
[ "This chapter of the django book answers all your model needs with examples very similar to yours, including a ManyToMany relation. http://www.djangobook.com/en/2.0/chapter10/\n" ]
[ -1 ]
[ "django", "django_models", "python" ]
stackoverflow_0008670389_django_django_models_python.txt
Q: Loading bar pygame How do you make a loading bar / progress bar with pygame, where you will load all the resources before the game starts? A: If you're asking how to draw and animate a progress bar, you would simply draw increasingly wide rectangles onto the surface, with the width proportional to the progress: ...
Loading bar pygame
How do you make a loading bar / progress bar with pygame, where you will load all the resources before the game starts?
[ "If you're asking how to draw and animate a progress bar, you would simply draw increasingly wide rectangles onto the surface, with the width proportional to the progress:\npygame.draw.rect(surface, (255,255,255), pygame.Rect(left,top,maxwidth*progress,height))\n\nYou could also draw a frame around the progress bar...
[ 3 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0008668793_pygame_python.txt
Q: delete not cascaded to table in sqlalchemy I am developing an extension to an existing app which uses sqlalchemy 0.6. The app has sqlalchemy tables created the non-declarative way. I am trying to create in my extension a new table with a foreign key column pointing at the primary key of the main table in the appli...
delete not cascaded to table in sqlalchemy
I am developing an extension to an existing app which uses sqlalchemy 0.6. The app has sqlalchemy tables created the non-declarative way. I am trying to create in my extension a new table with a foreign key column pointing at the primary key of the main table in the application database and I am creating it declarative...
[ "In SQLite you must turn on support for foreign keys explicitly or it just ignores any SQL related to foreign keys.\nengine = create_engine(database_url)\n\ndef on_connect(conn, record):\n conn.execute('pragma foreign_keys=ON')\n\nfrom sqlalchemy import event\nevent.listen(engine, 'connect', on_connect)\n\n" ]
[ 9 ]
[]
[]
[ "foreign_keys", "orm", "python", "sql", "sqlalchemy" ]
stackoverflow_0008667096_foreign_keys_orm_python_sql_sqlalchemy.txt
Q: ElasticSearch pagination through pyes. Offset ignored I'm working off the pyes usage example here I'm indexing test-index with four documents and querying later using different offsets. The start parameter doesn't change the offset for me, I keep getting the same results regardless of its value. Why is this happen...
ElasticSearch pagination through pyes. Offset ignored
I'm working off the pyes usage example here I'm indexing test-index with four documents and querying later using different offsets. The start parameter doesn't change the offset for me, I keep getting the same results regardless of its value. Why is this happening? from pyes import * conn = ES(["localhost:9200"]) try: ...
[ "The problem was in how the request was sent to ES, although I'm still not clear on why it failed.\nInstead of sending the queries directly to ES like I did originally:\nr0 = conn.search(q, indexes = [\"test-index\"], start=0, size=1)\nr1 = conn.search(q, indexes = [\"test-index\"], start=1, size=1)\nr2 = conn.sear...
[ 4, 2 ]
[]
[]
[ "elasticsearch", "pagination", "python" ]
stackoverflow_0008647688_elasticsearch_pagination_python.txt
Q: How does one find the largest consecutive set of numbers in a list that are not necessarily adjacent? For instance, if I have a list [1,4,2,3,5,4,5,6,7,8,1,3,4,5,9,10,11] This algorithm should return [1,2,3,4,5,6,7,8,9,10,11]. To clarify, the longest list should run forwards. I was wondering what is an algorithm...
How does one find the largest consecutive set of numbers in a list that are not necessarily adjacent?
For instance, if I have a list [1,4,2,3,5,4,5,6,7,8,1,3,4,5,9,10,11] This algorithm should return [1,2,3,4,5,6,7,8,9,10,11]. To clarify, the longest list should run forwards. I was wondering what is an algorithmically efficient way to do this (preferably not O(n^2))? Also, I'm open to a solution not in python since t...
[ "Here is a simple one-pass O(n) solution:\ns = [1,4,2,3,5,4,5,6,7,8,1,3,4,5,9,10,11,42]\nmaxrun = -1\nrl = {}\nfor x in s:\n run = rl[x] = rl.get(x-1, 0) + 1\n print x-run+1, 'to', x\n if run > maxrun:\n maxend, maxrun = x, run\nprint range(maxend-maxrun+1, maxend+1)\n\nThe logic may be a little mor...
[ 15, 3, 2, 1, 0, 0, 0, 0, 0 ]
[ "This should do the trick (and is O(n)):\ntarget = 1\nresult = []\nfor x in list:\n for y in result:\n if y[0] == target:\n y[0] += 1\n result.append(x)\n\nFor any starting number, this works:\nresult = []\nfor x in mylist:\n matched = False\n for y in result:\n if y[0] ...
[ -2 ]
[ "algorithm", "arrays", "dynamic_programming", "numpy", "python" ]
stackoverflow_0008664708_algorithm_arrays_dynamic_programming_numpy_python.txt
Q: Calling from an Sybase Database ODBC I am writing a scheduling program for my company and I wanted to pull information from our Management Information System to supplement the schedule. The MIS has information on all of the jobs we need to run including due dates, piececounts, operations, estimated run times and o...
Calling from an Sybase Database ODBC
I am writing a scheduling program for my company and I wanted to pull information from our Management Information System to supplement the schedule. The MIS has information on all of the jobs we need to run including due dates, piececounts, operations, estimated run times and other valuable information for a scheduler....
[ "If I were the CEO, my first thought would be to buy scheduling software before I'd ask an individual or team in my company to write such a thing. It's a difficult but important problem. Why would you want to develop, debug, and maintain such a thing? It's been solved. I'd rather just use an existing solution. ...
[ 1 ]
[]
[]
[ "mysql", "odbc", "php", "python", "sybase" ]
stackoverflow_0008671897_mysql_odbc_php_python_sybase.txt
Q: Using urlencode for Devanagari text The following code: import simplejson,urllib,urllib2 query=[u'नेपाल'] urlbase="http://search.twitter.com/search.json" values={'q':query[0]} data=urllib.urlencode(values) req=urllib2.Request(urlbase,data) response=urllib2.urlopen(req) json=simplejson.load(response) print jso...
Using urlencode for Devanagari text
The following code: import simplejson,urllib,urllib2 query=[u'नेपाल'] urlbase="http://search.twitter.com/search.json" values={'q':query[0]} data=urllib.urlencode(values) req=urllib2.Request(urlbase,data) response=urllib2.urlopen(req) json=simplejson.load(response) print json throws exception: SyntaxError: Non-A...
[ "You need to add the UTF-8 header to your file to tell the Python interpreter that there are unicode literals. You also have to encode the parameters as UTF-8. Here's a working version:\n# -*- coding: utf-8 -*-\nimport simplejson,urllib,urllib2 \n\nquery=[u'नेपाल']\nurlbase=\"http://search.twitter.com/search.json\...
[ 2 ]
[]
[]
[ "python", "urllib" ]
stackoverflow_0008672057_python_urllib.txt
Q: Why is swig not handling AttributeError correctly when using __getattribute__? I have a class that is getting exported from C++ to Python in SWIG. Everything works fine. Now I want to define getattribute to handle virtualize access to variables and functions that are defined in a scripting language built into th...
Why is swig not handling AttributeError correctly when using __getattribute__?
I have a class that is getting exported from C++ to Python in SWIG. Everything works fine. Now I want to define getattribute to handle virtualize access to variables and functions that are defined in a scripting language built into the C++ code. However when I define the getattribute function using %pythoncode it is...
[ "Now, I think I figured this out: \ndef __getattribute__(self, attribute): \n try: \n defattrib = object.__getattribute__(self, attribute) \n except AttributeError,e: \n defattrib = None \n if defattrib is not None: \n return defattrib \n\n # find attributes in user defi...
[ 0 ]
[]
[]
[ "c++", "getattribute", "python", "swig" ]
stackoverflow_0008650070_c++_getattribute_python_swig.txt
Q: Django keeps changing URL from http://localhost/ to http://127.0.0.1:8080/ As the title described, Django keeps changing my URL from /localhost/ to /127.0.0.1:8080/ which keeps messing up my serving static files by Nginx. Any ideas why its doing this? Thanks! /**EDIT**/ Here is the Nginx configuration: server { ...
Django keeps changing URL from http://localhost/ to http://127.0.0.1:8080/
As the title described, Django keeps changing my URL from /localhost/ to /127.0.0.1:8080/ which keeps messing up my serving static files by Nginx. Any ideas why its doing this? Thanks! /**EDIT**/ Here is the Nginx configuration: server { listen 80; ## listen for ipv4 listen [::]:80 default ipv6only=on; ## ...
[ "If you're using VirtualHost, you need to set USE_X_FORWARDED_HOST = True in your settings.py\nHere's the reference: Django Doc for Settings.py\n\nUSE_X_FORWARDED_HOST New in Django 1.3.1: Please, see the release\n notes\nDefault: False\nA boolean that specifies whether to use the X-Forwarded-Host header in\n pre...
[ 7, 4, 1 ]
[]
[]
[ "django", "django_forms", "nginx", "python" ]
stackoverflow_0005468225_django_django_forms_nginx_python.txt
Q: How could I capture the final url after redirects are followed with python, django, or shell based tool? Ok I'm doing a Django project where I have affiliate links for different sites. So I want to be able to automatically determine where the final domain ends up being after all the redirects are followed because ...
How could I capture the final url after redirects are followed with python, django, or shell based tool?
Ok I'm doing a Django project where I have affiliate links for different sites. So I want to be able to automatically determine where the final domain ends up being after all the redirects are followed because allot of the affiliate links will be from a 3rd party rather than the destination it's self. For example an af...
[ "By default, urllib2.urlopen() follows redirects. The response has a geturl() method which returns the address of the actual place you ended up. See the documentation.\n", "You don't need any custom tools to perform such a check. Basic shell utils are enough:\ncurl -s --head --location 'http://afl.affiliatenetwor...
[ 3, 1, 0 ]
[]
[]
[ "django", "linux", "python" ]
stackoverflow_0005002402_django_linux_python.txt
Q: Name threads in PyDev debug view PyDev's debug view shows the threads, however their names are cryptic: Is there a way to name these threads from within the python code? A: It looks like the names being displayed in PyDev are the ones assigned by default. To fix that you can give a name to the thread when it's ...
Name threads in PyDev debug view
PyDev's debug view shows the threads, however their names are cryptic: Is there a way to name these threads from within the python code?
[ "It looks like the names being displayed in PyDev are the ones assigned by default.\nTo fix that you can give a name to the thread when it's created:\nthreading.Thread(name=<name>, target=...)\n\nor, later, just by setting the name attribute:\nthread = threading.Thread(*args, **kwargs)\nthread.name = <name>\n\n", ...
[ 3, 3 ]
[]
[]
[ "debugging", "multithreading", "pydev", "python" ]
stackoverflow_0008672306_debugging_multithreading_pydev_python.txt
Q: Scripting Virtualbox to create networks I know that VB offers many things to control it : SDK, API, COM, web server etc What I'd like to do is have a GUI to simply create VM connected through networks but I have to know: what is the best solution use Frontends [1], webserver, COM* or API ? elsewhere libvirt ? A a...
Scripting Virtualbox to create networks
I know that VB offers many things to control it : SDK, API, COM, web server etc What I'd like to do is have a GUI to simply create VM connected through networks but I have to know: what is the best solution use Frontends [1], webserver, COM* or API ? elsewhere libvirt ? A an example a use case could be : I put 3 VMs o...
[ "My qualifications for answering this being that I created and have maintained Vagrant since early 2010. Here are my general opinions of each of the available frontends for scripting VirtualBox:\n\nvboxwebsrv is the VirtualBox web service which provides an API to control VirtualBox. The pro of this is that web serv...
[ 4 ]
[]
[]
[ "c++", "networking", "python", "virtualbox" ]
stackoverflow_0008052088_c++_networking_python_virtualbox.txt
Q: Correct usage of fmin_l_bfgs_b for fitting model parameters I have a some experimental data (for y, x, t_exp, m_exp), and want to find the "optimal" model parameters (A, B, C, D, E) for this data using the constrained multivariate BFGS method. Parameter E must be greater than 0, the others are unconstrained. def f...
Correct usage of fmin_l_bfgs_b for fitting model parameters
I have a some experimental data (for y, x, t_exp, m_exp), and want to find the "optimal" model parameters (A, B, C, D, E) for this data using the constrained multivariate BFGS method. Parameter E must be greater than 0, the others are unconstrained. def func(x, A, B, C, D, E, *args): return A * (x ** E) * numpy.cos...
[ "I didn't want to try to figure out what the model you're using represented, so here's a simple example fitting to a line:\n\nx_true = arange(0,10,0.1)\nm_true = 2.5\nb_true = 1.0\ny_true = m_true*x_true + b_true\n\ndef func(params, *args):\n x = args[0]\n y = args[1]\n m, b = params\n y_model = m*x+b\n...
[ 13 ]
[]
[]
[ "model_fitting", "numpy", "python", "scipy" ]
stackoverflow_0008672005_model_fitting_numpy_python_scipy.txt
Q: How do I grab text in a HTML tag without getting further embedded tag text? I'm trying to use BeautifulSoup to parse a list of addresses on a page. When I get to a tag with text and embedded tags, how do I only grab text from the tag without getting text in any further (lower level) embedded text at all? I use a ...
How do I grab text in a HTML tag without getting further embedded tag text?
I'm trying to use BeautifulSoup to parse a list of addresses on a page. When I get to a tag with text and embedded tags, how do I only grab text from the tag without getting text in any further (lower level) embedded text at all? I use a pTag to go from location to location in the .html page and here's the code I deal...
[ "It is possible to remove elements using the extract method:\n>>> from BeautifulSoup import BeautifulSoup\n>>> s = '<html><address>Some street address<br />City, State and ZIP<br /><div class=\"phone\">(123) 456-7890</div></address></html>'\n>>> soup = BeautifulSoup(s)\n>>> soup.address.div.extract()\n<div class=\"...
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0008666687_beautifulsoup_python.txt
Q: Python: split float after 3rd decimal place I have a series of strings, which are two numbers: 1.782-100.799 -18.107-102.016 -17.504104.059 How do I split my string after the 3rd decimal place of the first number in each string? so it looks as follows: 1.782 -100.799 -18.107 -102.016 -17.504 104.059 A: Heuristi...
Python: split float after 3rd decimal place
I have a series of strings, which are two numbers: 1.782-100.799 -18.107-102.016 -17.504104.059 How do I split my string after the 3rd decimal place of the first number in each string? so it looks as follows: 1.782 -100.799 -18.107 -102.016 -17.504 104.059
[ "Heuristic approach using regular expressions:\n>>> import re\n>>> s = \"\"\"1.782-100.799\n... -18.107-102.016\n... -17.504104.059\"\"\"\n>>> re.findall('-?\\d{1,3}(?:\\.\\d{3})*', s)\n['1.782', '-100.799', '-18.107', '-102.016', '-17.504', '104.059']\n\nOr do this line-by-line to get pairs:\n>>> [re.findall('-?\\...
[ 4, 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008672768_python.txt
Q: Pyramid: how to add record to database? I've tried to add record to database from command line, but it did not work (I mean no record was added to db and no error was raised). Here is code: from myproject.models import DBSession, Model session = DBSession() md = Model(name='text') session.add(md) In models.py DB...
Pyramid: how to add record to database?
I've tried to add record to database from command line, but it did not work (I mean no record was added to db and no error was raised). Here is code: from myproject.models import DBSession, Model session = DBSession() md = Model(name='text') session.add(md) In models.py DBSession() was defined automatically by scaffo...
[ "Likely your session is attached to a transaction manager DBSession = .. extensions=[ZopeTransactionExtension()]), which is not active when using the console. Thus you have to be the transaction manager and do it yourself.\nimport transaction\ntransaction.commit()\n\nat the end of your code. Remember that session.a...
[ 7 ]
[]
[]
[ "pyramid", "python" ]
stackoverflow_0008672524_pyramid_python.txt
Q: Detecting a repeating cycle in a sequence of numbers (python) I was wondering what would be a a fairly 'common' or normal way of doing this. Wasn't really looking for the shortest possible answer like a 2-liner or anything. I've just quickly put this piece of code together but I can't not feel like there's way too...
Detecting a repeating cycle in a sequence of numbers (python)
I was wondering what would be a a fairly 'common' or normal way of doing this. Wasn't really looking for the shortest possible answer like a 2-liner or anything. I've just quickly put this piece of code together but I can't not feel like there's way too much in there. Also if there are any libraries that could help wit...
[ "I may not be properly understanding this, but I think there is a very simple solution with regex.\n(.+ .+)( \\1)+\n\nHere is an example:\n>>> regex = re.compile(r'(.+ .+)( \\1)+')\n>>> match = regex.search('3 0 5 5 1 5 1 6 8')\n>>> match.group(0) # entire match\n'5 1 5 1'\n>>> match.group(1) # repeating port...
[ 20, 3 ]
[]
[]
[ "cycle", "numbers", "python", "sequence" ]
stackoverflow_0008672853_cycle_numbers_python_sequence.txt
Q: How to access an element of a set using an equivalent object? If I have an object that compares equal to an element of a Python set, but is not the same object, is there a reasonable way to get a reference to the object in the set? The use case would be using the set to identify and share duplicated data. Example ...
How to access an element of a set using an equivalent object?
If I have an object that compares equal to an element of a Python set, but is not the same object, is there a reasonable way to get a reference to the object in the set? The use case would be using the set to identify and share duplicated data. Example (Python 2.7): >>> a = "This is a string" >>> b = "This is a string"...
[ "I found a similar question on python-list: Get item from set. There is a clever answer with reference to get_equivalent(container, item) (Python recipe). \nThe trick is to construct a wrapper object for the 'key' object, and check if wrapper is in the set using the in operator. If the wrapper hashes equal to the k...
[ 5, 3 ]
[]
[]
[ "object_identity", "python", "set" ]
stackoverflow_0008616284_object_identity_python_set.txt
Q: CSV Rows to XML files using Python I have csv file that looks like this: artist,year,id,video_name,new_video_id,file_root_name,video_type ,,,,,, Clay Aiken,1,clay_aiken,Sorry Seems To Be...,sorry-seems-to-be,02_sc_ca_sorry,FLV Clay Aiken,1,clay_aiken,Everything I Do (I Do It For You),everything-i-do-i-do-it-for-yo...
CSV Rows to XML files using Python
I have csv file that looks like this: artist,year,id,video_name,new_video_id,file_root_name,video_type ,,,,,, Clay Aiken,1,clay_aiken,Sorry Seems To Be...,sorry-seems-to-be,02_sc_ca_sorry,FLV Clay Aiken,1,clay_aiken,Everything I Do (I Do It For You),everything-i-do-i-do-it-for-you,03_sc_ca_everything,FLV Clay Aiken,1,c...
[ "I'd start with something like this:\nimport csv\nimport sys\n\nfrom xml.etree import ElementTree\nfrom xml.dom import minidom\n\nvideo_data = ((256, 336000),\n (512, 592000),\n (768, 848000),\n (1128, 1208000))\n\nwith open(sys.argv[1], 'rU') as f:\n reader = csv.DictReade...
[ 5, 1 ]
[]
[]
[ "csv", "python", "xml" ]
stackoverflow_0008672872_csv_python_xml.txt
Q: imp.load_source() in Python When is it useful to use imp.load_source() method for importing Python module? Has it some advantage in some scenario in opposite to normal importing with import keyword? A: import always looks in the following order: already imported modules import hooks files in the locations in s...
imp.load_source() in Python
When is it useful to use imp.load_source() method for importing Python module? Has it some advantage in some scenario in opposite to normal importing with import keyword?
[ "import always looks in the following order:\n\nalready imported modules\nimport hooks\nfiles in the locations in sys.path\nbuiltin modules\n\nIf you want to import a module which would not be found by any of these mechanisms, but you know the filename, then you could use imp.load_source(). Or if you want to import...
[ 2 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0008673380_import_module_python.txt
Q: How to put string from function as an argument for sqlite3.connect() in python I have option menu widget: optionTuple = ("filename1", "filename2", "filename3") filename1, filename2, filename3 are also names of files in directory then I have button which inter alia gets selected option value: def btnConvertClick(...
How to put string from function as an argument for sqlite3.connect() in python
I have option menu widget: optionTuple = ("filename1", "filename2", "filename3") filename1, filename2, filename3 are also names of files in directory then I have button which inter alia gets selected option value: def btnConvertClick(self): filename = '"'+ optionMenuWidget.cget('text')+'"' then I try to open [s...
[ "Try setting the filename without the quotes:\nfilename = optionMenuWidget.cget\n\n" ]
[ 2 ]
[]
[]
[ "function", "python", "sqlite", "tkinter" ]
stackoverflow_0008673491_function_python_sqlite_tkinter.txt
Q: Is it possible to write dynamic web pages in Python with the Really Simple HTTP Server? I know that with the SimpleHTTPServer I can make my directories accessible by web-browsers via Internet. So, I run just one line of the code and, as a result, another person working on another computer can use his/her browser t...
Is it possible to write dynamic web pages in Python with the Really Simple HTTP Server?
I know that with the SimpleHTTPServer I can make my directories accessible by web-browsers via Internet. So, I run just one line of the code and, as a result, another person working on another computer can use his/her browser to see content of my directories. But I wander if I can make more complicated things. For exam...
[ "While it is possible, you have to do pretty much everything yourself (parsing request parameters, handle routing, etc).\nIf you are not looking to get experience in creating web-frameworks, but just want to create a small site you should probably use a minimalistic framework instead.\nTry Bottle, a simple single-f...
[ 4, 0, 0 ]
[]
[]
[ "get", "post", "python", "simplehttpserver", "webserver" ]
stackoverflow_0002321813_get_post_python_simplehttpserver_webserver.txt
Q: How to create curved (left or right)-arrow using matplotlib? I am using matplotlib.patches.FancyArrow to draw arrow between points. By changing *shape*: ['full', 'left', 'right'], I can create full, left or right-shaped arrow. Now instead of straight arrows, I want to join points by curve arrows. The class matpl...
How to create curved (left or right)-arrow using matplotlib?
I am using matplotlib.patches.FancyArrow to draw arrow between points. By changing *shape*: ['full', 'left', 'right'], I can create full, left or right-shaped arrow. Now instead of straight arrows, I want to join points by curve arrows. The class matplotlib.patches.FancyArrowPatch does it, however, the arrow shape is...
[ "Maybe you need:\nset_connectionstyle(\"arc,angleA=0,armA=30,rad=10\")\n\ntogether with\nset_arrowstyle(\"Fancy,head_length=0.2\")\n\n" ]
[ 0 ]
[]
[]
[ "matplotlib", "plot", "python" ]
stackoverflow_0008673351_matplotlib_plot_python.txt
Q: 2d-barcode image generator in Python under Qt4? There is any library that support 2d-barcode image generator in python ?? i need any help to generate a 2d-barcode (QR-code) ?? A: You can tak a look at https://github.com/lincolnloop/python-qrcode, also if it is not related to Qt4 A library for Qt4 is prison, but ...
2d-barcode image generator in Python under Qt4?
There is any library that support 2d-barcode image generator in python ?? i need any help to generate a 2d-barcode (QR-code) ??
[ "You can tak a look at https://github.com/lincolnloop/python-qrcode, also if it is not related to Qt4\nA library for Qt4 is prison, but it seems to have not the python binding\n" ]
[ 1 ]
[]
[]
[ "barcode", "python", "qt4" ]
stackoverflow_0008673180_barcode_python_qt4.txt
Q: using dynamic python class definition and amfast dynamic class mapping and code generation to generate ActionScript class I have an xml snippet that contains an object hierarchy: doc = """\ <RootObj val1="ValueOne" stat1="Stat1" stat2="Stat2"> <internalarray type="array"> <InternalObject val1="12" val2="12" ...
using dynamic python class definition and amfast dynamic class mapping and code generation to generate ActionScript class
I have an xml snippet that contains an object hierarchy: doc = """\ <RootObj val1="ValueOne" stat1="Stat1" stat2="Stat2"> <internalarray type="array"> <InternalObject val1="12" val2="12" /> <InternalObject val1="13" val2="13" /> <InternalObject val1="14" val2="14" /> <InternalObject val1="15" val2="15...
[ "Ok, so apparently, this is something nobody knows how to do, so I came up with a workaround.\nI modified the buildClass() function like so:\ndef buildClass(name, node):\n global _classes\n symbol_table = {}\n args = []\n varnames = \"\"\n varnameswithtypes = \"\"\n for subnode in node:\n args.append(build...
[ 0 ]
[]
[]
[ "actionscript_3", "dynamic_class_creation", "python" ]
stackoverflow_0008567372_actionscript_3_dynamic_class_creation_python.txt
Q: Website Links to Downloadable Files Don't Seem to Update I have a problem with links on my website. Please forgive me if this is asked somewhere else, but I have no idea how to search for this. A little background on the current situation: I've created a python program that randomly generates planets for a sci-fi ...
Website Links to Downloadable Files Don't Seem to Update
I have a problem with links on my website. Please forgive me if this is asked somewhere else, but I have no idea how to search for this. A little background on the current situation: I've created a python program that randomly generates planets for a sci-fi game. Each created planet is placed in a text file to be viewe...
[ "I don't know anything about Python, but in PHP, in some fopen modes, if a file is trying to be made with the same name as an existing file, it will cancel the operation.\n" ]
[ 0 ]
[]
[]
[ "html", "python", "web" ]
stackoverflow_0008674077_html_python_web.txt
Q: getting epydoc output from output during runtime? I'm trying to create a self documenting python web service. My Situation: I've got an object accessible via RESTful python web service. http://foo.com/api/monkey And, what I'd like to do is if there's an error during a call to http://foo.com/api/monkey like htt...
getting epydoc output from output during runtime?
I'm trying to create a self documenting python web service. My Situation: I've got an object accessible via RESTful python web service. http://foo.com/api/monkey And, what I'd like to do is if there's an error during a call to http://foo.com/api/monkey like http://foo.com/api/monkey/get was called without "&monkey_...
[ "The first use case (\"there's an error during a call\") is poorly-defined. 404 errors, for example, don't result in help pages, they're perfectly ordinary. \nA http://foo.com/api/bad/path/get request can't figure out which help page to send, since it didn't make a monkey request.\nAlso, putting /get on your path...
[ 1 ]
[]
[]
[ "documentation_generation", "python", "web_services" ]
stackoverflow_0008674031_documentation_generation_python_web_services.txt
Q: Sproutcore with Python Scipy I have a computational backend made in Python Scipy and the frontend and admin section will be made in Sproutcore. What do i need to make the sproutcore run the python engine. I think i need a python framework that sits between sproutcore and scipy. This framework's only job will be t...
Sproutcore with Python Scipy
I have a computational backend made in Python Scipy and the frontend and admin section will be made in Sproutcore. What do i need to make the sproutcore run the python engine. I think i need a python framework that sits between sproutcore and scipy. This framework's only job will be to facilitate communication. Other...
[ "You can use any framework you like! I happen to like something like SimpleApi atop Flask (which you can run with nginx, apache2 or any wsgi-compliant server). This basically puts an TCP/IP listener on top of whatever python code you like. \nI am guessing all you want to expose is essentially run(some_well_contr...
[ 0 ]
[]
[]
[ "python", "scipy", "sproutcore" ]
stackoverflow_0007538587_python_scipy_sproutcore.txt
Q: What is the meaning of '*' in numpy? >>> shape=(2,2) >>> np.random.randn(*shape) array([[-1.64633649, -0.03132273], [-0.92331459, 1.05325462]]) I can't find it in numpy's documentation. Any help is appreciated. A: This is not NumPy-specific syntax; it is Python syntax. The so-called *-operator is Python syn...
What is the meaning of '*' in numpy?
>>> shape=(2,2) >>> np.random.randn(*shape) array([[-1.64633649, -0.03132273], [-0.92331459, 1.05325462]]) I can't find it in numpy's documentation. Any help is appreciated.
[ "This is not NumPy-specific syntax; it is Python syntax. The so-called *-operator is Python syntax that does sequence unpacking in argument lists (see Unpacking Argument Lists).\nThe use in your example is to unpack the shape tuple into separate arguments. This is needed because numpy.random.randn takes an arbitrar...
[ 17, 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0008450055_numpy_python.txt
Q: which data types help in timer behavior flow in python for MaxTime: run function1 for timeout 10 secs after timeout 10 sec ,again run function1 for timeout 10 secs after timeout 10 sec , again run function1 for timeout 10 secs ... (do it untill MaxTime is reached ) which modules below ...
which data types help in timer behavior flow in python
for MaxTime: run function1 for timeout 10 secs after timeout 10 sec ,again run function1 for timeout 10 secs after timeout 10 sec , again run function1 for timeout 10 secs ... (do it untill MaxTime is reached ) which modules below can be used/helpful ? sched.scheduler or threading.timer...
[ "Do you mean something like pygame.time.Clock()?\nExecute function1() every 10 seconds until 100 seconds pass:\nimport logging\nimport pygame\n\nlogging.basicConfig(format='%(asctime)s %(message)s', datefmt='%H:%M:%S')\ndef function1():\n logging.warning(\"write logs\")\n\nfps = .1 # call function1() every ...
[ 1, 1 ]
[]
[]
[ "algorithm", "python", "timer" ]
stackoverflow_0008672282_algorithm_python_timer.txt
Q: MySQLdb inserting a dict into a table I have a row of data in dict format. Is there an easy way to insert it into a mysql table. I know that I can write a custom function to convert dict into a custom sql query, but I am looking for a more direct alternative. A: Well... According to the documentation for paramst...
MySQLdb inserting a dict into a table
I have a row of data in dict format. Is there an easy way to insert it into a mysql table. I know that I can write a custom function to convert dict into a custom sql query, but I am looking for a more direct alternative.
[ "Well... According to the documentation for paramstyle:\n\nSet to 'format' = ANSI C printf format codes, e.g. '...WHERE name=%s'.\n If a mapping object is used for conn.execute(), then the interface\n actually uses 'pyformat' = Python extended format codes, e.g.\n '...WHERE name=%(name)s'. However, the API does ...
[ 5, 2 ]
[]
[]
[ "dictionary", "insert", "mysql_python", "python" ]
stackoverflow_0008674426_dictionary_insert_mysql_python_python.txt
Q: Having an odd issue with SQLAlchemy and joins I save email addresses in two tables: userid and domain. The model looks something like this: class Email(): id = Column(Integer, primary_key=True) parent_id = Column(Unicode, ForeignKey('domain.id')) parent = relationship('Domain') userid = Column(Unic...
Having an odd issue with SQLAlchemy and joins
I save email addresses in two tables: userid and domain. The model looks something like this: class Email(): id = Column(Integer, primary_key=True) parent_id = Column(Unicode, ForeignKey('domain.id')) parent = relationship('Domain') userid = Column(Unicode) class Domain(): id = Column(Integer, prim...
[ "Figured out the problem. Had to do with inheritance and aliasing. Lesson: If joining two objects inherited from the same object, alias at least one of the objects!\n" ]
[ 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0008483493_python_sqlalchemy.txt
Q: Unique IDs to multidimensional array elements in python I have a multidimensional array with elements that can be completely random. For example, [ [ [1, 2], [2, 1], [3, 1], [4, 2] ], [ [2, 1], [4, 3], [3, 4], [1, 3] ] ] I'd like to assign an ID to each unique element (as in [1,2], not the elements withi...
Unique IDs to multidimensional array elements in python
I have a multidimensional array with elements that can be completely random. For example, [ [ [1, 2], [2, 1], [3, 1], [4, 2] ], [ [2, 1], [4, 3], [3, 4], [1, 3] ] ] I'd like to assign an ID to each unique element (as in [1,2], not the elements within those) so that I can recognize it later on when this array ...
[ "How about using something like this?\nclass ItemUniqifier(object):\n def __init__(self):\n self.id = 0\n self.element_map = {}\n self.reverse_map = {}\n\n def getIdFor(self, obj):\n obj_id = self.element_map.get(obj)\n if obj_id is None:\n obj_id = self.id\n ...
[ 2, 0, 0, 0 ]
[]
[]
[ "multidimensional_array", "python", "unique_id" ]
stackoverflow_0008482156_multidimensional_array_python_unique_id.txt
Q: In python - the operator which a set uses for test if an object is in the set If I have a list of objects, I can use the __cmp__ method to override objects are compared. This affects how the == operator works, and the item in list function. However, it doesn't seem to affect the item in set function - I'm wonderin...
In python - the operator which a set uses for test if an object is in the set
If I have a list of objects, I can use the __cmp__ method to override objects are compared. This affects how the == operator works, and the item in list function. However, it doesn't seem to affect the item in set function - I'm wondering how I can change the MyClass object so that I can override the behaviour how the ...
[ "set uses __hash__ for comparison. Override that, and you'll be good:\nclass MyClass(object):\n def __init__(self, s):\n self.s = s\n def __cmp__(self, other):\n return cmp(self.s, other.s)\n def __hash__(self):\n return hash(self.s) # Use default hash for 'self.s'\n\ninstance1, insta...
[ 9 ]
[]
[]
[ "object", "overriding", "python", "set" ]
stackoverflow_0008675105_object_overriding_python_set.txt
Q: telnetlib | read all message when I have to click space if do it mannually As you know, sometimes, you have to click space to get the next page under telnet connections, unix. For instance, you 'more' a text file. You can't get all the content at one time. Using 'space' can get to the next page. Here is the proble...
telnetlib | read all message when I have to click space if do it mannually
As you know, sometimes, you have to click space to get the next page under telnet connections, unix. For instance, you 'more' a text file. You can't get all the content at one time. Using 'space' can get to the next page. Here is the problem, what should I do when using telnetlib, python? I have to get all the informat...
[ "Instead of using more(1) or less(1) to view a file, use cat(1). It will not perform any pagination tasks and will write all the content of the file to the terminal, raw.\n" ]
[ 1 ]
[]
[]
[ "python", "telnetlib", "unix" ]
stackoverflow_0008675138_python_telnetlib_unix.txt
Q: wxPython Panel in existing window: slow and small I'm experiencing very different behavior when creating a wx.Panel depending on whether the main window's already called Show(). With the below code, the application opens quickly with MainPanel created & populated before MainFrame.Show(). Using "New" to re-create ...
wxPython Panel in existing window: slow and small
I'm experiencing very different behavior when creating a wx.Panel depending on whether the main window's already called Show(). With the below code, the application opens quickly with MainPanel created & populated before MainFrame.Show(). Using "New" to re-create it has multi-second lag while it re-makes the 200 texts...
[ "The panel will get the correct size if the Frame feels a SizeEvent. So this works for your second question:\ndef OnNew(self, evt):\n if self.panel:\n self.panel.Destroy()\n self.panel = MainPanel(self)\n self.SendSizeEvent()\n\nControl of windows and widgets becomes easier by using sizers. With siz...
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0008675017_python_wxpython.txt
Q: Using Tornado web to access a HTTP stream and serve streamed data to web clients I would like to use the Tornado web server to connect to a HTTP stream like the Twitter Stream and serve the streamed data via websockets to a web client. I've got both working seperatly, one Tornado instance using twitstream and the ...
Using Tornado web to access a HTTP stream and serve streamed data to web clients
I would like to use the Tornado web server to connect to a HTTP stream like the Twitter Stream and serve the streamed data via websockets to a web client. I've got both working seperatly, one Tornado instance using twitstream and the other using tornado.websocket.WebSocketHandler, but i would like both services combine...
[ "If you start a separate thread and use that thread to push messages to the WebSocket listeners, that will solve your problem\n" ]
[ 0 ]
[]
[]
[ "python", "tornado", "websocket" ]
stackoverflow_0006197435_python_tornado_websocket.txt
Q: Clean way for inter-thread communication with select I'm trying to implement a FUSE-driven filesystem in Python, which serves data from both local and remote sources. The filesystem is handled by the main FUSE thread: filesystem requests are dealt with straight as they're requested. class MyFilesystem(Fuse): d...
Clean way for inter-thread communication with select
I'm trying to implement a FUSE-driven filesystem in Python, which serves data from both local and remote sources. The filesystem is handled by the main FUSE thread: filesystem requests are dealt with straight as they're requested. class MyFilesystem(Fuse): def read(self, path, size, offset): if self._isLoca...
[ "Using sockets for inter-thread communication is perfectly acceptable, but it will be slower than implementing it with threads and locks using in-memory data structures.\nNotice that 'slower' is relative: Hard disk operations might still be slower by a tenfold.\nAlthough it's not a direct answer to the question, ma...
[ 2, 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0008671229_multithreading_python.txt
Q: Price of switching control between C++ and Python I'm developing a C++ application that is extended/ scriptable with Python. Of course C++ is much faster than Python, in general, but does that necessarily mean that you should prefer to execute C++ code over Python code as often as possible? I'm asking this because...
Price of switching control between C++ and Python
I'm developing a C++ application that is extended/ scriptable with Python. Of course C++ is much faster than Python, in general, but does that necessarily mean that you should prefer to execute C++ code over Python code as often as possible? I'm asking this because I'm not sure, is there any performance cost of switchi...
[ "I don't know there is a concrete rule for this, but a general rule that many follow is to:\n\nPrototype in python. This is quicker to write, and may be easier to read/reason about.\nOnce you have a prototype, you can now identify the slow portions that should be written in c++ (through profiling).\nDepending on t...
[ 8, 2, 1, 0 ]
[]
[]
[ "c++", "performance", "python" ]
stackoverflow_0008675062_c++_performance_python.txt
Q: including additional static xml with python I need my current script to include additional xml. This is the script in its current form: import csv import sys from xml.etree import ElementTree from xml.dom import minidom video_data = ((256, 336000), (512, 592000), (768, 848000), ...
including additional static xml with python
I need my current script to include additional xml. This is the script in its current form: import csv import sys from xml.etree import ElementTree from xml.dom import minidom video_data = ((256, 336000), (512, 592000), (768, 848000), (1128, 1208000)) with open(sys.argv[1], ...
[ "Why don't you replace\n print minidom.parseString(ElementTree.tostring(switch_tag)).toprettyxml()\n\nwith\n print header + ElementTree.tostring(switch_tag) + footer\n\nWhere header and footer are what is above and below the switch tag in your second example output, respectively. Alternatively, if you want to use t...
[ 2 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0008674610_python_xml.txt
Q: Python advanced string searching with operators and boolean I have a function that searches a string in a list of lists then returns a list containing the matching lists: def foo(myList,keyword,first=True): if first: #Search only first element or each sublist return [x for x in myList if keyword in x] ...
Python advanced string searching with operators and boolean
I have a function that searches a string in a list of lists then returns a list containing the matching lists: def foo(myList,keyword,first=True): if first: #Search only first element or each sublist return [x for x in myList if keyword in x] else: #Search first and second elements of each sublist ...
[ "I would try constructing a regex for each portion of the search query. First you could break the query into the portions using shlex.split(), and then create each regex individually. Here is my crack at it:\nimport shlex, re\n\ndef foo(query):\n pieces = shlex.split(query)\n include, exclude = [], []\n ...
[ 4, 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008675253_google_app_engine_python.txt
Q: Appengine, performance degradation with python27 I wanted to test python27 on appengine so I have migrated my app from python25. Performance got more than 2x slower for every request! Then I've returned to python25 and performance is again as it was before. Here is a picture: (milliseconds/request) (cgi handler ...
Appengine, performance degradation with python27
I wanted to test python27 on appengine so I have migrated my app from python25. Performance got more than 2x slower for every request! Then I've returned to python25 and performance is again as it was before. Here is a picture: (milliseconds/request) (cgi handler python 27, then python25) My app uses Werkzeug, Jinja2...
[ "Somewhere on Usenet I read a statement like this from Google \"he Python 2.7 runtime is slower than the Python 2.5 runtime in some cases and faster in others. We aren't publicizing the reasons why at this point.\". Seems nobody has found so far a scenario where 2.7 is faster than 2.5 thus ...\nI read into this\n\...
[ 17, 5, 3, 1, 0 ]
[ "As far as I know, Python 2.7 should be faster than 2.5. However, there are some factors that can influence speeds:\n\nThe way the binary is compiled;\nWhether your libraries (such as Memcache) are compiled as C(++) or Python. A C++ module is, of course, faster than the Python equivalent;\nThe server it's on - I ha...
[ -1 ]
[ "google_app_engine", "performance", "python" ]
stackoverflow_0008341112_google_app_engine_performance_python.txt
Q: How to use "map" function in Python? (How to rewrite a for loop?) I have an array of classes and I want to create objects of them. This works: classArray = [Auto, Wheel] objectArray = [] for myClass in classArray: objectArray += [myClass()] Can I use the map function to accomplish the same? ...
How to use "map" function in Python? (How to rewrite a for loop?)
I have an array of classes and I want to create objects of them. This works: classArray = [Auto, Wheel] objectArray = [] for myClass in classArray: objectArray += [myClass()] Can I use the map function to accomplish the same? objectArray = map( ??? , classArray) My apologies if this is a dumb ...
[ "You could use a list comprehension instead. Many consider them to be preferred over the map function.\nobjectArrray = [ c() for c in classArray ]\n\n\nIf you insist on using map, you can do\nmap(lambda c: c(), classArray)\n\nHere, I am creating an anonymous function with lambda that simply takes the item, and call...
[ 9 ]
[]
[]
[ "map", "python" ]
stackoverflow_0008675431_map_python.txt
Q: pyinotify interrupt check_events I know pyinotify.Notifier.check_events(self, timeout=None) can take a timeout - but I'd prefer it poll indefinitely. Is it possible to interrupt it? I am calling Notifier.stop(self), but it does not seem to be escaping from check_events. In the below example, another thread calls s...
pyinotify interrupt check_events
I know pyinotify.Notifier.check_events(self, timeout=None) can take a timeout - but I'd prefer it poll indefinitely. Is it possible to interrupt it? I am calling Notifier.stop(self), but it does not seem to be escaping from check_events. In the below example, another thread calls stopIt(), and self.notifier.stop() is c...
[ "Even though threads run concurrently, each thread has its own independent flow of execution. One thread can not inject commands into another thread's flow of execution by calling its methods (such as by calling stopIt). \nSo what else can we do? Well, besides the obvious option of using the timeout, you could use ...
[ 1 ]
[]
[]
[ "pyinotify", "python" ]
stackoverflow_0008675666_pyinotify_python.txt
Q: List of Lists: finding a value throughout I am using Python to write a program that looks through lists of lists and changes values. In my list of lists I have 3's and I want to find their index. Right now I can only get it to work on the first row. I want it to find 3's on any of the lists in "numbers." Here is s...
List of Lists: finding a value throughout
I am using Python to write a program that looks through lists of lists and changes values. In my list of lists I have 3's and I want to find their index. Right now I can only get it to work on the first row. I want it to find 3's on any of the lists in "numbers." Here is some sample code to wash away the mud: numbers =...
[ "If you only want to get the row index, iterate over numbers using enumerate [docs] and test whether 3 is in the list using in [docs]:\nfor index, row in enumerate(numbers):\n if 3 in row:\n print \"3 found in row %i\" % index\n\nFor row and column index, iterate over both lists:\nfor index, row in enumer...
[ 2, 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008674015_python.txt
Q: problems with carrays in python I have this code: import numpy as np import tables as tb ndim = 50000 h5in = tb.openFile('data.h5','r') data = h5in.root.x h5out = tb.openFile('testout.h5', mode='w', title="argsort distances") root = h5out.root x = h5out.createCArray(root,'x',tb.Int16Atom(),shape=(ndim,ndim)) fo...
problems with carrays in python
I have this code: import numpy as np import tables as tb ndim = 50000 h5in = tb.openFile('data.h5','r') data = h5in.root.x h5out = tb.openFile('testout.h5', mode='w', title="argsort distances") root = h5out.root x = h5out.createCArray(root,'x',tb.Int16Atom(),shape=(ndim,ndim)) for i in xrange(ndim): x[:,i] = np....
[ "Replace the for loop with:\nx[:,:] = np.argsort(dist, axis=1).T \n\nUPDATE: If this is too large, then try to find a compromise in the slices size:\nslice_size = 100 # or 1000 if it fits into your memory\nfor i in xrange(0, ndim, slice_size):\n x[:,i:i+slice_size] = np.argsort(dist[i:i+slice_size,:], axis=1)\n\...
[ 1, 0 ]
[]
[]
[ "arrays", "interop", "performance", "pytables", "python" ]
stackoverflow_0008671361_arrays_interop_performance_pytables_python.txt
Q: Slow Line2D rendering in matplotlib I am trying to use Line2D to render a line between the last point clicked on a polygon and the user's mouse. My current code currently works, but it lags FOREVER between renders, so that the line lags way behind the mouse. Current relevant code is: #in constructor cid2 = self.u...
Slow Line2D rendering in matplotlib
I am trying to use Line2D to render a line between the last point clicked on a polygon and the user's mouse. My current code currently works, but it lags FOREVER between renders, so that the line lags way behind the mouse. Current relevant code is: #in constructor cid2 = self.ui.canvas2.mpl_connect('motion_notify_even...
[ "Do not create a new Line2D for every mouse move. A Line2D can have more than 2 points. So instead, use Line2D.set_data() to alter the data in a single Line2D. \nDrawing one Line2D with thousands of points will surely be faster than instantiating and drawing thousands of Line2Ds.\ndef renderMeasureLine(self, mouseE...
[ 2 ]
[]
[]
[ "image", "matplotlib", "python", "rendering" ]
stackoverflow_0008676105_image_matplotlib_python_rendering.txt
Q: Python - Scrapy SgmlLinkExtractor Deny Value Is Being Ignored I am using Scrapy to crawl http://www.investopedia.com. I have a crawl filter definition in my "Spider.py" file: rules = ( # Crawl filters Rule(SgmlLinkExtractor(deny=settings['DENY_FILTER']), callback='parse_item', follow=True, process_links='p...
Python - Scrapy SgmlLinkExtractor Deny Value Is Being Ignored
I am using Scrapy to crawl http://www.investopedia.com. I have a crawl filter definition in my "Spider.py" file: rules = ( # Crawl filters Rule(SgmlLinkExtractor(deny=settings['DENY_FILTER']), callback='parse_item', follow=True, process_links='process_links'), ) settings['DENY_FILTER'] is being pulled from the...
[ "Try to pass deny arguments in place\nRule(SgmlLinkExtractor(deny=('regexp1', 'regexp2',),...\n\nIf your deny rules will work, I think you should access DENY_FILTER defined in settings.py as:\nDENY_FILTER = ('regexp1', 'regexp2',)\n\nby writing:\nRule(SgmlLinkExtractor(deny=settings.DENY_FILTER), ...\n\nAlso, plea...
[ 0 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0008674514_python_scrapy.txt
Q: Easier setup for writing to MySQL on OSX with Python I have a Python script that writes to a MySQL database using mysql-python. This is fine for Linux and Windows but on OSX this library is too difficult for my clients to install. Requires editing configuration files, directory symlinks, installing gcc, xcode, ......
Easier setup for writing to MySQL on OSX with Python
I have a Python script that writes to a MySQL database using mysql-python. This is fine for Linux and Windows but on OSX this library is too difficult for my clients to install. Requires editing configuration files, directory symlinks, installing gcc, xcode, ... An overwhelming process for non-technical users. So, is t...
[ "Unfortunately, there really is no trivial solution at the moment. If you need to use MySQL with Python, the simplest and most reliable solution on OS X is to install everything - Python, MySQLdb, any other third-party Python packages needed, MySQL client libraries, and, if necessary, MySQL server libraries and ut...
[ 2 ]
[]
[]
[ "macos", "mysql", "mysql_python", "python" ]
stackoverflow_0008675885_macos_mysql_mysql_python_python.txt