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: probably a python syntax error just have some code dealing with hashes so here's a problem i ran into... THE PYTHON: import whirlpool import cgi form = cgi.FieldStorage() iR = form["iR"].value print iR iH = whirlpool.Whirlpool(iR) pT = iH.hexdigest() crosscheck = "8d8309ca6af848095bcabaf9a53b1b6ce7f594c1434fd6e...
probably a python syntax error
just have some code dealing with hashes so here's a problem i ran into... THE PYTHON: import whirlpool import cgi form = cgi.FieldStorage() iR = form["iR"].value print iR iH = whirlpool.Whirlpool(iR) pT = iH.hexdigest() crosscheck = "8d8309ca6af848095bcabaf9a53b1b6ce7f594c1434fd6e5177e7e5c20e76cd30936d8606e7f36acbef...
[ "If you want to use a Python script as CGI then you need to use it as CGI (i.e., set it as the value of the action attribute of the form) instead of invoking it directly.\n" ]
[ 0 ]
[]
[]
[ "cgi", "forms", "hash", "php", "python" ]
stackoverflow_0004801888_cgi_forms_hash_php_python.txt
Q: How can I use pyparsing to parse nested expressions that have multiple opener/closer types? I'd like to use pyparsing to parse an expression of the form: expr = '(gimme [some {nested [lists]}])', and get back a python list of the form: [[['gimme', ['some', ['nested', ['lists']]]]]]. Right now my grammar looks like...
How can I use pyparsing to parse nested expressions that have multiple opener/closer types?
I'd like to use pyparsing to parse an expression of the form: expr = '(gimme [some {nested [lists]}])', and get back a python list of the form: [[['gimme', ['some', ['nested', ['lists']]]]]]. Right now my grammar looks like this: nestedParens = nestedExpr('(', ')') nestedBrackets = nestedExpr('[', ']') nestedCur...
[ "Here's a pyparsing solution that uses a self-modifying grammar to dynamically match the correct closing brace character.\nfrom pyparsing import *\n\ndata = '(gimme [some {nested, nested [lists]}])'\n\nopening = oneOf(\"( { [\")\nnonBracePrintables = ''.join(c for c in printables if c not in '(){}[]')\nclosingFor =...
[ 27 ]
[ "This should do the trick for you. I tested it on your example:\nimport re\nimport ast\n\ndef parse(s):\n s = re.sub(\"[\\{\\(\\[]\", '[', s)\n s = re.sub(\"[\\}\\)\\]]\", ']', s)\n answer = ''\n for i,char in enumerate(s):\n if char == '[':\n answer += char + \"'\"\n elif char ...
[ -3 ]
[ "pyparsing", "python" ]
stackoverflow_0004801403_pyparsing_python.txt
Q: Elegant way to modify a list of variables by reference in Python? Let's say I have a function f() that takes a list and returns a mutation of that list. If I want to apply that function to five member variables in my class instance (i), I can do this: for x in [i.a, i.b, i.c, i.d, i.e]: x[:] = f(x) 1) Is ther...
Elegant way to modify a list of variables by reference in Python?
Let's say I have a function f() that takes a list and returns a mutation of that list. If I want to apply that function to five member variables in my class instance (i), I can do this: for x in [i.a, i.b, i.c, i.d, i.e]: x[:] = f(x) 1) Is there a more elegant way? I don't want f() to modify the passed list. 2) If...
[ "Another solution, though it's probably not elegant:\nfor x in ['a', 'b', 'c', 'd', 'e']:\n setattr(i, x, f(getattr(i, x)))\n\n", "Python doesn't have pass by reference. The best you can do is write a function which constructs a new list and assign the result of the function to the original list. Example:\ndef...
[ 4, 2, 2 ]
[]
[]
[ "python", "reference" ]
stackoverflow_0004801918_python_reference.txt
Q: Python _ctypes import error on OSX 10.6 I'm very new to Python development, and am having a problem with one of my apps in OSX. Technologies being used in this project python 2.6 django google app engine rpx (openid) When loading up the site on my windows app, there are no issues, but when trying to same app on ...
Python _ctypes import error on OSX 10.6
I'm very new to Python development, and am having a problem with one of my apps in OSX. Technologies being used in this project python 2.6 django google app engine rpx (openid) When loading up the site on my windows app, there are no issues, but when trying to same app on OSX 10.6, I get the following issue: ImportE...
[ "OS X 10.6's Python 2.6 does include ctypes by default. You can even see part of it in the error report. So if there's a problem with the installation, it's only a problem with part of ctypes. That suggests that either it was damaged somehow or that something else is interfering with some part of the ctypes inte...
[ 6, 3, 2, 0 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0002394903_macos_python.txt
Q: How to use subprocess to execute programs with Python Hello i am using the subprocess.Popen() class and i succesful execute commands on the terminal, but when i try to execute programs for example an script written on Python and i try to pass arguments the system fails. This is the code: argPath = "tes...
How to use subprocess to execute programs with Python
Hello i am using the subprocess.Popen() class and i succesful execute commands on the terminal, but when i try to execute programs for example an script written on Python and i try to pass arguments the system fails. This is the code: argPath = "test1" args = open(argPath, 'w') if s...
[ "OK, I'm ignoring that your code doesn't run (neither the script you try to execute, not the main script actually works), and looking at what you are doing:\nIt does execute the script, or you would get an error, like \"bin/sh: foo: not found\".\nAlso you seem to be using an open file as stdin after you have writte...
[ 3, 2 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0004801798_python_python_3.x.txt
Q: How to import rlib in an rpython program to be translated using pypy's rpython I am trying to do some file io in a program to be compiled with pypy's translate tool. Since open and os.open are not supported, I need rlib.streamio. I tried to do import rlib but it gives the following error [translation:ERROR] Impor...
How to import rlib in an rpython program to be translated using pypy's rpython
I am trying to do some file io in a program to be compiled with pypy's translate tool. Since open and os.open are not supported, I need rlib.streamio. I tried to do import rlib but it gives the following error [translation:ERROR] ImportError': import statement always raises [type ImportError: 'No module named rlib'] ...
[ "It's\nfrom pypy.rlib import streamio\n\n", "So it seems that pypy's translate looks for modules in the path of script (or installed modules), rather than its own system. Once I copied rlib into the current directory, I could compile it. I just had to\n$ cp -r pypy-1.4.1-src/pypy/rlib .\n\nThen\n$ ./pypy-1.4.1-sr...
[ 4, 0 ]
[]
[]
[ "compilation", "file_io", "pypy", "python" ]
stackoverflow_0004800076_compilation_file_io_pypy_python.txt
Q: Capture Image as Array with Python OpenCV I've seen from the sample how to display an image from the webcam, but how do I get the image captured as an array? import cv capture = cv.CaptureFromCAM(0) img = cv.QueryFrame(capture) img.tostring() gives me weird caracters. Thanks in adv. A: I think this is what you...
Capture Image as Array with Python OpenCV
I've seen from the sample how to display an image from the webcam, but how do I get the image captured as an array? import cv capture = cv.CaptureFromCAM(0) img = cv.QueryFrame(capture) img.tostring() gives me weird caracters. Thanks in adv.
[ "I think this is what you're looking for:\nimg=cv.LoadImage(\"asd.png\")\nmat=cv.GetMat(img)\nmat[3,1]\n(83.0, 88.0, 89.0)\n\nanyway, you should check opencv python cookbook for use with PIL and NUMPY packages.\n", "Be sure to get an opencv with numpy support included. The sequence that works for me is capture an...
[ 3, 2, 1, 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0003528813_opencv_python.txt
Q: Python - asyncore.dispatcher module error I started learning this asyncore.dispatcher module and when I run the first example program it gives the error as per below: Python version 2.6 asyncore module is installed and there is also dispatcher class inside it. What may be the problem ! Error: AttributeError: 'mod...
Python - asyncore.dispatcher module error
I started learning this asyncore.dispatcher module and when I run the first example program it gives the error as per below: Python version 2.6 asyncore module is installed and there is also dispatcher class inside it. What may be the problem ! Error: AttributeError: 'module' object has no attribute 'dispatcher' Exam...
[ "Your problem is that you named your file asyncore.py. It's shadowing the asyncore.py in the python standard lib so the file is importing itself instead of the real one. You want to rename your copy of the file and delete asyncore.pyc in the same directory if it exists. Then when you run your file, you'll be import...
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0004801365_python.txt
Q: Why does this use of Smooth cause Python to crash? I'm using Python 2.6 against OpenCV 2.0. I've started a file capture and pulled frames. I've displayed the image to make sure it's valid. When I call this routine, python crashes: def SmoothImage(self,SmoothingMaskSize=3): temp=cv.CreateImage(cv.GetSize(sel...
Why does this use of Smooth cause Python to crash?
I'm using Python 2.6 against OpenCV 2.0. I've started a file capture and pulled frames. I've displayed the image to make sure it's valid. When I call this routine, python crashes: def SmoothImage(self,SmoothingMaskSize=3): temp=cv.CreateImage(cv.GetSize(self._lpImage),self._lpImage.depth,self._lpImage.nChannels)...
[ "The bindings that come with the OpenCV 2.0 installer are buggy; I had similar problem where some very simple operations triggered crashes. Compiling from the source should fix it.\n", "If you don't need access to the object-oriented parts of OpenCV, you should take a look at ctypes-opencv, which is a better set ...
[ 0, 0, 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0002035842_opencv_python.txt
Q: Customize Python unittest report with HTML or Textile I'm using unittest for testing my python code. I'm seeking a way that I can do the following: Customize the report of test run. Export it as HTML or Textile document. Any ideas? A: testoob should support your reporting requirements (not sure whether it supp...
Customize Python unittest report with HTML or Textile
I'm using unittest for testing my python code. I'm seeking a way that I can do the following: Customize the report of test run. Export it as HTML or Textile document. Any ideas?
[ "testoob should support your reporting requirements (not sure whether it supports textile reporting, but it definitely does support HTML reporting).\n", "I ended up using HTMLTestRunner, such a great and simple tool.\n" ]
[ 3, 2 ]
[]
[]
[ "customization", "html", "python", "textile", "unit_testing" ]
stackoverflow_0003285713_customization_html_python_textile_unit_testing.txt
Q: Print histogram in python 3 I have a word length_of_word | repetitions dictionary and I want to make a histogram of that like the one in link below using only python built in functions no numpy or anything like it. http://dev.collabshot.com/show/723400/ Please help me out at least with some pointers. A: I guess ...
Print histogram in python 3
I have a word length_of_word | repetitions dictionary and I want to make a histogram of that like the one in link below using only python built in functions no numpy or anything like it. http://dev.collabshot.com/show/723400/ Please help me out at least with some pointers.
[ "I guess you must have a dict that looks like this one, right ?\n>>> d = {1:1, 2:10, 3:10, 4:6, 5:5, 6:4, 7:2, 8:1}\n>>> d\n{1: 1, 2: 10, 3: 10, 4: 6, 5: 5, 6: 4, 7: 2, 8: 1}\n\nIf so, I have a function that does the trick:\n>>> def histo(dict_words):\n # Get max values, plus delta to ease display\n x_max = m...
[ 3 ]
[]
[]
[ "histogram", "python", "python_3.x" ]
stackoverflow_0004801352_histogram_python_python_3.x.txt
Q: How do I flush everything from Celery? I accidently added too many things to the queue, and now it froze. Can't get it to do anything else. A: Have you tried to restart the celery service with --discard parameter ?
How do I flush everything from Celery?
I accidently added too many things to the queue, and now it froze. Can't get it to do anything else.
[ "Have you tried to restart the celery service with --discard parameter ?\n" ]
[ 7 ]
[]
[]
[ "celery", "django", "python" ]
stackoverflow_0004802807_celery_django_python.txt
Q: How to make 3D plots in Python? This is the MATLAB version of the 3D plotting code: EDIT: This is the current code: plt.figure(2) fig_b = Axes3D(fig2) xx2 = np.arange(0, L+h_grid*L, h_grid*L) yy2 = np.arange(-b, b+h_grid*b, h_grid*b) X, Y = np.meshgrid(xx2, yy2) W = ...
How to make 3D plots in Python?
This is the MATLAB version of the 3D plotting code: EDIT: This is the current code: plt.figure(2) fig_b = Axes3D(fig2) xx2 = np.arange(0, L+h_grid*L, h_grid*L) yy2 = np.arange(-b, b+h_grid*b, h_grid*b) X, Y = np.meshgrid(xx2, yy2) W = np.zeros((41,21), float) mx =...
[ "What's wrong? You are trying to make a non-number negative.\nIn other words: AxesSubplot (whatever that is) doesn't implement the unary - operator.\nSo, that code can not reasonably be \"what you have done\", as you don't even define b in that code, yet it exists and is of some custom type called AxesSubplot. If y...
[ 4, 4 ]
[]
[]
[ "matlab", "matplotlib", "mplot3d", "python" ]
stackoverflow_0004802157_matlab_matplotlib_mplot3d_python.txt
Q: Is it possible to reduce the amount of arguments this on the boilerplate function? I'm currently trying to create an automagic django model instantiator. This function will take a couple of arguments, instantiate a few django models, link some foreign keys together, save the lot and return the main model back to m...
Is it possible to reduce the amount of arguments this on the boilerplate function?
I'm currently trying to create an automagic django model instantiator. This function will take a couple of arguments, instantiate a few django models, link some foreign keys together, save the lot and return the main model back to me. This is all fine and all but in the end, the function takes 4 normal arguments and 2 ...
[ "Sometimes, a function's gotta take a lot of arguments. There is nothing wrong with this, per se. Here are some tips on making it a little cleaner:\nDon't name the bool, \"bool\":\ndef create_rule(profile, lifestyles, is_something, title, input, output):\n rule = Rule.objects.create(\n ....\n bool=is_somet...
[ 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0004803061_django_django_models_python.txt
Q: Django: Name error at ROUTE/ I've a Django project advisor with core application. My routes are separated into a small group of files. I try to include them from the main urls.py, but django fails with the following exception NameError at /ask name 'advisor' is not defined Request Method: GET Request URL: ht...
Django: Name error at ROUTE/
I've a Django project advisor with core application. My routes are separated into a small group of files. I try to include them from the main urls.py, but django fails with the following exception NameError at /ask name 'advisor' is not defined Request Method: GET Request URL: http://localhost:8000/ask Django Ve...
[ "(r'^ask/$', include('advisor.core.urls.ask')),\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_urls", "python", "url_routing" ]
stackoverflow_0004803400_django_django_urls_python_url_routing.txt
Q: SQL queries through PYODBC fail silently on one machine, works on another I am working on a program to automate parsing data from XML files and storing it into several databases. (Specifically the USGS realtime water quality service, if anyone's interested, at http://waterservices.usgs.gov/rest/WaterML-Interim-RE...
SQL queries through PYODBC fail silently on one machine, works on another
I am working on a program to automate parsing data from XML files and storing it into several databases. (Specifically the USGS realtime water quality service, if anyone's interested, at http://waterservices.usgs.gov/rest/WaterML-Interim-REST-Service.html) It's written in Python 2.5.1 using LXML and PYODBC. The datab...
[ "\nI have no idea how to check whether\n we have the same version of the\n Microsoft ODBC drivers.\n\nI think you're looking for Control Panel | Administrative Tools | Data Sources (ODBC). Click the \"Drivers\" tab.\nI think either Access 2000 or Office 2000 shipped with a desktop edition of SQL Server called \"M...
[ 1 ]
[]
[]
[ "database", "pyodbc", "python", "sql" ]
stackoverflow_0002050613_database_pyodbc_python_sql.txt
Q: Python: Simplest (non-PIL) way to get image metadata (mainly size) I'm gathering basic metadata for images - mainly their dimensions, although it'd be nice to get any other available metadata as well. The image formats I'm interested in are png, jpg, and gif. I'm using PIL at the moment, but it occurred to me the...
Python: Simplest (non-PIL) way to get image metadata (mainly size)
I'm gathering basic metadata for images - mainly their dimensions, although it'd be nice to get any other available metadata as well. The image formats I'm interested in are png, jpg, and gif. I'm using PIL at the moment, but it occurred to me there may be a simpler way that doesn't involve external dependencies or bi...
[ "I don't think there is anything built in, but if you look up those file formats, you will find that the size is encoded near the beginning of the file.\nYou can use the struct module to parse just enough of the header to work out the size\n", "See ImageMagick, a fantastic library for dealing with bitmap images. ...
[ 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004800425_python.txt
Q: Python string formatting I'm building up several command strings to pass to os.system. I want to group the common stuff into a string then add the specific stuff as needed. For example: CMD = "python app.py %s -o %s > /dev/null" option1 = "-i 192.169.0.1" option2 = "results-file" cmd = CMD, (option1, option2) #doe...
Python string formatting
I'm building up several command strings to pass to os.system. I want to group the common stuff into a string then add the specific stuff as needed. For example: CMD = "python app.py %s -o %s > /dev/null" option1 = "-i 192.169.0.1" option2 = "results-file" cmd = CMD, (option1, option2) #doesn't work os.system(cmd) I kn...
[ "You use the % operator.\ncmd = CMD % (option1, option2)\n\nSee also: Python documentation on string formatting\n", "You could do it this way using the string format() method which processes Format String Syntax:\nCMD = \"python app.py {} -o {} > /dev/null\"\noption1 = \"-i 192.169.0.1\"\noption2 = \"results-file...
[ 3, 3, 0 ]
[]
[]
[ "python", "string_formatting" ]
stackoverflow_0004803885_python_string_formatting.txt
Q: How to sort a dict by values and return a list of formatted strings? I've got a dict: text_to_count = { "text1": 1, "text2":0, "text3":2} I'd like to create a list of formatted strings by sorting this dict's values (in descending order). I.e., I like following list: result = ["2 - text3", "1 - text1", "0 - text2"...
How to sort a dict by values and return a list of formatted strings?
I've got a dict: text_to_count = { "text1": 1, "text2":0, "text3":2} I'd like to create a list of formatted strings by sorting this dict's values (in descending order). I.e., I like following list: result = ["2 - text3", "1 - text1", "0 - text2"] Any ideas? Edit: While waiting for responses, I kept hacking at it and ...
[ "['%d - %s' % (v, k) for (k, v) in sorted(text_to_count.iteritems(),\n key=operator.itemgetter(1), reverse=True)]\n\n", "How's this?\nresult = ['{1} - {0}'.format(*pair) for pair in sorted(text_to_count.iteritems(), key = lambda (_,v): v, reverse = True)]\n\n", "And one more, codegolf style:\n>>> ['%s - %s'%...
[ 2, 1, 0 ]
[]
[]
[ "dictionary", "list", "python", "string_formatting" ]
stackoverflow_0004801344_dictionary_list_python_string_formatting.txt
Q: Decode function tries to encode Python I am trying to print a unicode string without the specific encoding hex in it. I'm grabbing this data from facebook which has an encoding type in the html headers of UTF-8. When I print the type - it says its unicode, but then when I try to decode it with unicode-escape says ...
Decode function tries to encode Python
I am trying to print a unicode string without the specific encoding hex in it. I'm grabbing this data from facebook which has an encoding type in the html headers of UTF-8. When I print the type - it says its unicode, but then when I try to decode it with unicode-escape says there is an encoding error. Why is it trying...
[ "It's not the decode that's failing. It's because you are trying to display the result to the console. When you use print it encodes the string using the default encoding which is ASCII. Don't use print and it should work.\n\n>>> a=u'really long string containing \\\\u20ac and some other text'\n>>> type(a)\n<type '...
[ 8, 3, 2 ]
[]
[]
[ "python", "unicode", "unicode_escapes" ]
stackoverflow_0004799917_python_unicode_unicode_escapes.txt
Q: Recommendations for a clean vanilla machine install Ubuntu LAMP setup with python on Amazon EC2 I'm setting up a ubuntu LAMP server on EC2, can anyone recommend a simple machine image Requirements: Ubuntu Server LAMP Python, Python-imaging ( can self install ) The server is for testing a python application. Thank...
Recommendations for a clean vanilla machine install Ubuntu LAMP setup with python on Amazon EC2
I'm setting up a ubuntu LAMP server on EC2, can anyone recommend a simple machine image Requirements: Ubuntu Server LAMP Python, Python-imaging ( can self install ) The server is for testing a python application. Thanks
[ "This seems to foot the bill: https://10.cloud.ubuntu.com/faq/\nThey've got a link to the images they registered with Amazon.\n" ]
[ 2 ]
[]
[]
[ "amazon_ec2", "python", "ubuntu" ]
stackoverflow_0004804303_amazon_ec2_python_ubuntu.txt
Q: Create an html formatted report I have a Python 2.6 app running on Linux that creates a CSV file. From the app, I need to create an HTML report, as a single HTML file, that presents the data from the CSV (probably as a table) and also highlights fields where the values meet certain criteria. Charting type function...
Create an html formatted report
I have a Python 2.6 app running on Linux that creates a CSV file. From the app, I need to create an HTML report, as a single HTML file, that presents the data from the CSV (probably as a table) and also highlights fields where the values meet certain criteria. Charting type functionality would be a nice to have. What's...
[ "Choose a Python csv library from here. Now that you have the data mapped to Python data structures you can iterate on it and create the html. I would use the Jinja2 templating engine which is nicely documented. Highlighting rows/cells would work by setting certain css classes on the respective tr/td elements in th...
[ 7 ]
[]
[]
[ "html", "python", "reporting" ]
stackoverflow_0004804510_html_python_reporting.txt
Q: How to use complex SQL scripts with python I could write a SP inside Mysql and excute with a call statement. But looking to write it in python instead. I got stuck with using sql script on multiple lines. conn = pyodbc.connect('DSN=MySQL;PWD=xxxx') csr = conn.cursor() Sql= 'SELECT something, something FRO...
How to use complex SQL scripts with python
I could write a SP inside Mysql and excute with a call statement. But looking to write it in python instead. I got stuck with using sql script on multiple lines. conn = pyodbc.connect('DSN=MySQL;PWD=xxxx') csr = conn.cursor() Sql= 'SELECT something, something FROM table WHERE foo=bar ORDER BY foo ' ...
[ "If you don't mind the overhead, take a look at sqlalchemy:\n\nSQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL.\n\n", "Heh, I don't mind to make it a proper answer.\nString literals in triple quotes can include linebreaks an...
[ 2, 2 ]
[]
[]
[ "python", "sql" ]
stackoverflow_0004797222_python_sql.txt
Q: How to organise python / Boost Python projects I have a python project, to which I would like to interface with some C++ libraries using Boost::Python. I would like to know how others go about organising their python/boost::python/C++ code within the same project. By organisation I mean in terms of file/directory...
How to organise python / Boost Python projects
I have a python project, to which I would like to interface with some C++ libraries using Boost::Python. I would like to know how others go about organising their python/boost::python/C++ code within the same project. By organisation I mean in terms of file/directory structure, build procedures etc.
[ "In what follows, pif denotes Python InterFace. First I've got a generic header file, called conv_pif.hpp, which has Boost headers and C++ Std Library headers and such. Then for each boost python module, I have a file (here corresponding to the example module genocpp) of the form string_pif.cpp, where string corres...
[ 1, 0 ]
[]
[]
[ "boost_python", "c++", "organization", "python" ]
stackoverflow_0004774807_boost_python_c++_organization_python.txt
Q: Advice on creating a screensaver updatable via a CMS I've been asked to provide someone with a screensaver which contains some content pulled from a mysql database. Having never developed a screensaver before, I'm wondering how best to go about this. The screensaver will be used in an office of around 20 machines ...
Advice on creating a screensaver updatable via a CMS
I've been asked to provide someone with a screensaver which contains some content pulled from a mysql database. Having never developed a screensaver before, I'm wondering how best to go about this. The screensaver will be used in an office of around 20 machines running Windows - I was originally going to use Flash to d...
[ "PyScreensaver (plus maybe some TurboGears or Django for managing the database on the server side, if you don't have anything for that, yet)\n" ]
[ 0 ]
[]
[]
[ "java", "python" ]
stackoverflow_0004803910_java_python.txt
Q: python: ftp get directory creation date I want to connect to my ftp server where directorys like "01-26-2011" are created on a daily basis (no specific pattern, "Jan2011-26" is also a possible directory name). Inside this directory are again some directories. I want to write a script that checks every 10 minutes i...
python: ftp get directory creation date
I want to connect to my ftp server where directorys like "01-26-2011" are created on a daily basis (no specific pattern, "Jan2011-26" is also a possible directory name). Inside this directory are again some directories. I want to write a script that checks every 10 minutes if a new directory is created. So my question ...
[ "Depending on the details you need, you can use FTPLIB To list the directories listing. You could do something like save them to a list and compare in 10 min the 2 sorted lists. You can also digg deeper and search in FTPLIB for any attributes. I don't know much FTPLIB, but here a solution.\n" ]
[ 0 ]
[]
[]
[ "creation", "date", "ftp", "python" ]
stackoverflow_0004805135_creation_date_ftp_python.txt
Q: python: enforce that a class method is only called from within another class method? I have a class with two methods A and B. The class will be subclassed. Is there an elegant way to enforce that B() is only ever called on an object of the class from within the A() method? Let's constrain it and say that A() is on...
python: enforce that a class method is only called from within another class method?
I have a class with two methods A and B. The class will be subclassed. Is there an elegant way to enforce that B() is only ever called on an object of the class from within the A() method? Let's constrain it and say that A() is only called in one place but subclasses implement A() and can optionally call B() within tha...
[ "Actual private methods is an evil. Mark your method as internal by adding a leading underscore. This tells programmers not to use it unless they know what they are doing.\n", "Although I don't recommend the practice, here's a way it could be done using sys._getframe():\nimport sys\n\nclass Base(object):\n def...
[ 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004803651_python.txt
Q: problem with unicode decoding This is funny.. I am trying to read geographic lookup data from openstreetmap. The code that performs the query looks like this params = urllib.urlencode({'q': ",".join([e for e in full_address]), 'format': "json", "addressdetails" : "1"}) query = "http://nominatim.openstreetmap.org/s...
problem with unicode decoding
This is funny.. I am trying to read geographic lookup data from openstreetmap. The code that performs the query looks like this params = urllib.urlencode({'q': ",".join([e for e in full_address]), 'format': "json", "addressdetails" : "1"}) query = "http://nominatim.openstreetmap.org/search?%s" % params print query time...
[ "\nWhen I go and print the response, the\n u with umlaut is encoded latin1 (0xFC)\n\nYou are just misinterpreting the output. It's a unicode string (you can tell by the u in prefix), there's no encoding \"attached\" - the \\xFC means there it's the codepoint with number 0xFC, which happens to be the U-Umlaut (see ...
[ 8, 1 ]
[]
[]
[ "encoding", "iso_8859_1", "latin1", "python", "utf_8" ]
stackoverflow_0004805267_encoding_iso_8859_1_latin1_python_utf_8.txt
Q: Using south to refactor a Django model with inheritance I was wondering if the following migration is possible with Django south and still retain data. Before: I currently have two apps, one called tv, one called movies, each with a VideoFile model (simplified here): tv/models.py: class VideoFile(models.Model): ...
Using south to refactor a Django model with inheritance
I was wondering if the following migration is possible with Django south and still retain data. Before: I currently have two apps, one called tv, one called movies, each with a VideoFile model (simplified here): tv/models.py: class VideoFile(models.Model): show = models.ForeignKey(Show, blank=True, null=True) n...
[ "Check out response below by Paul for some notes on compatibility with newer versions of Django/South.\n\nThis seemed like an interesting problem, and I'm becoming a big fan of South, so I decided to look into this a bit. I built a test project on the abstract of what you've described above, and have successfully ...
[ 49, 9, 3, 1 ]
[]
[]
[ "django", "django_south", "migration", "python" ]
stackoverflow_0001600129_django_django_south_migration_python.txt
Q: I cannot initialize class in python I have a class Flight, and I'm trying initialize it, but I have a syntax error in print x=Flight(flightFromInput='nebrasca') This is a content of my example file class Flight: flightFrom = None flightTo = None departureDate = None arrivalDate=None airline=N...
I cannot initialize class in python
I have a class Flight, and I'm trying initialize it, but I have a syntax error in print x=Flight(flightFromInput='nebrasca') This is a content of my example file class Flight: flightFrom = None flightTo = None departureDate = None arrivalDate=None airline=None serviceClass=None departureAi...
[ "You should write \nx = Flight(flightFromInput='nebrasca')\nprint x\n\n", "In python an assignment statement doesn't return the assigned value. So you cannot use it within another statement. As the other answers suggested, you can work around this by printing x in a separate line.\nNote, that there are exceptions...
[ 8, 4, 1 ]
[]
[]
[ "class", "python" ]
stackoverflow_0004805787_class_python.txt
Q: Processing messages from a child process thorough stderr and stdout with Python My python code spawns the child process, and it prints out messages both stdout and stderr. I need to print them differently. I have the following code to spawn child process and get the stdout result from it. cmd = ["vsmake.exe", "-f"...
Processing messages from a child process thorough stderr and stdout with Python
My python code spawns the child process, and it prints out messages both stdout and stderr. I need to print them differently. I have the following code to spawn child process and get the stdout result from it. cmd = ["vsmake.exe", "-f"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) for line in iter(p.stdout.readlin...
[ "p = Popen(cmd, bufsize=1024,\nstdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)\np.stdin.close()\nprint p.stdout.read() #This will print the standard output from the spawned process\nprint p.stderr.read() #This is what you need, error output <-----\n\nSo basically the error output gets redirected to the stderr...
[ 7, 1 ]
[]
[]
[ "child_process", "python", "spawn", "stderr", "stdout" ]
stackoverflow_0004805576_child_process_python_spawn_stderr_stdout.txt
Q: Programmatically generate thumbnail CAP for small video How can python make a simple cap for a video. Ideia: take 9 snapshots for 9 even placed (on the timeline) times, and displace then in a JGP How should I do this? Is PIL the only way? (it's not going to be easy to do what I want, right?) Aren't there any modul...
Programmatically generate thumbnail CAP for small video
How can python make a simple cap for a video. Ideia: take 9 snapshots for 9 even placed (on the timeline) times, and displace then in a JGP How should I do this? Is PIL the only way? (it's not going to be easy to do what I want, right?) Aren't there any module (python seens to have GREAT modeles for almoust anything, o...
[ "This is a quick change to something I've done some time ago, using ffmpeg for frame extraction and PIL to create the full thumbs image.\nimport os, sys\nfrom PIL import Image\n\n# Use \"ffmpeg -i <videofile>\" to get total length by parsing the error message\nchout, chin, cherr = os.popen3(\"ffmpeg -i %s\" % sys.a...
[ 7 ]
[]
[]
[ "python", "python_imaging_library", "thumbnails", "video" ]
stackoverflow_0004805563_python_python_imaging_library_thumbnails_video.txt
Q: Looking for generator of Python <--> XML bindings I'm looking for a generator which takes schema file(s) (XSD) on input and generates Python code (bindings) able to transform xml file to Python objects and the other way around. It should be customizable so that I could plug in my code dealing with transformation b...
Looking for generator of Python <--> XML bindings
I'm looking for a generator which takes schema file(s) (XSD) on input and generates Python code (bindings) able to transform xml file to Python objects and the other way around. It should be customizable so that I could plug in my code dealing with transformation between specific types defined in schema and Python's ob...
[ "Try PyXB.\n", "http://www.rexx.com/~dkuhlman/generateDS.html\nThat's the first Google hit.\nHow to convert XSD to Python Class\nThat's the second Google hit.\n" ]
[ 3, 1 ]
[]
[]
[ "data_binding", "python", "xml", "xsd", "xsd2code" ]
stackoverflow_0004805431_data_binding_python_xml_xsd_xsd2code.txt
Q: Python Wget?/Scripting books? I've been learning python here recently....mainly for scripting purposes....since apparently it's supposed to be almost as good as bash for doing small script jobs. But two questions, Does python have it's own sort of "wget" or do you have to use a library for that (or does it have on...
Python Wget?/Scripting books?
I've been learning python here recently....mainly for scripting purposes....since apparently it's supposed to be almost as good as bash for doing small script jobs. But two questions, Does python have it's own sort of "wget" or do you have to use a library for that (or does it have one built in?) for stuff such as retr...
[ "It all depends on what you want to do. Python offers you access to wget just like bash. You can call your normal wget command and retrieve a simple file using e.g. os.system.\nHowever, depending on how much power you require, Python offers you much more flexibility with additional packages. You may want to take a ...
[ 2, 2, 0 ]
[]
[]
[ "python", "scripting" ]
stackoverflow_0004805683_python_scripting.txt
Q: GQL: Not equal filter on a multivalued property Tinkering a little with GAE's datastore i've found that i can't think a proper way to filter out results using the inequality filter '!=' on a multivalued property: class Entry(db.Model): ... tags = db.StringListProperty() e1 = Entry() e2 = Entry() e1.tags =...
GQL: Not equal filter on a multivalued property
Tinkering a little with GAE's datastore i've found that i can't think a proper way to filter out results using the inequality filter '!=' on a multivalued property: class Entry(db.Model): ... tags = db.StringListProperty() e1 = Entry() e2 = Entry() e1.tags = ['tag1', 'tag2', 'tag3'] e2.tags = ['tag1', 'tag3', ...
[ "I've thought about this a bunch and I don't think there is a good way to do it (please correct me if I'm wrong). My non-clever solution is to not use StringListProperty and to cascade a bunch of filters: \nclass Entry(db.Model):\n ...\n tag_1 = db.StringProperty();\n tag_2 = db.StringProperty();\n ...\nEntry....
[ 0 ]
[]
[]
[ "google_cloud_datastore", "gql", "multivalue", "python" ]
stackoverflow_0004795293_google_cloud_datastore_gql_multivalue_python.txt
Q: How can Python continuously fill multiple threads of subprocess? I'm running an app, foo, on Linux. From a Bash script/terminal prompt, my application runs multi-threaded with this command: $ foo -config x.ini -threads 4 < inputfile System Monitor and top report foo averages about 380% CPU load (quad-core machine...
How can Python continuously fill multiple threads of subprocess?
I'm running an app, foo, on Linux. From a Bash script/terminal prompt, my application runs multi-threaded with this command: $ foo -config x.ini -threads 4 < inputfile System Monitor and top report foo averages about 380% CPU load (quad-core machine). I've recreated this functionality in Python 2.6x with: proc = subp...
[ "When you call a command with Popen like this it doesn't matter if it's called from Python or from the shell. It's the \"foo\" command that starts it's processes, not Python.\nSo the answer is \"Yes, subprocesses can be multi-threaded when called from Python.\"\n", "First things first, are you guessing it is sing...
[ 4, 1, 0 ]
[]
[]
[ "multithreading", "python", "subprocess" ]
stackoverflow_0004802119_multithreading_python_subprocess.txt
Q: nltk in python code for emotion extraction I would be very glad if you could help me to find a solution for linking my python code with nltk. my code is for creating an emotion extraction engine in background of a chat environment. i could separate the chatters and their conversations. Now i need to extract noun, ...
nltk in python code for emotion extraction
I would be very glad if you could help me to find a solution for linking my python code with nltk. my code is for creating an emotion extraction engine in background of a chat environment. i could separate the chatters and their conversations. Now i need to extract noun, verbs, adjectives etc. from their conversation. ...
[ "What you are trying to achieve is called POS Tagging.\nfrom nltk import pos_tag, word_tokenize\n\nsentence = \"No, Mr. Bond. I expect you to die!\"\ntagged_sentence = pos_tag(word_tokenize(sentence)) \n\nprint tagged_sentence\n\nThe result is a list of (word,tag) tuples:\n[('No', 'DT'), (',', ','), ('Mr.', 'NNP'),...
[ 4, 2 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0004803032_nltk_python.txt
Q: Pinax (13, 'Permission denied') I'm a noob but I made my application work beautifully using python manage.py runserver but when I brought it to Apache + mod_wsgi, I keep getting this error. The debug messages aren't much help. Here is a screenshot of the entire debug image: http://img694.imageshack.us/img694/6723/...
Pinax (13, 'Permission denied')
I'm a noob but I made my application work beautifully using python manage.py runserver but when I brought it to Apache + mod_wsgi, I keep getting this error. The debug messages aren't much help. Here is a screenshot of the entire debug image: http://img694.imageshack.us/img694/6723/screenshotfb.png Here is the dump of ...
[ "Under Apache/mod_wsgi your code will run as Apache user and will not usually have access rights to write to directories that you as a user has. Read:\nhttp://code.google.com/p/modwsgi/wiki/ApplicationIssues#Access_Rights_Of_Apache_User\nThe easiest way around that is run make the daemon process run as same user as...
[ 4, 0 ]
[]
[]
[ "deployment", "django", "pinax", "python", "wsgi" ]
stackoverflow_0002278394_deployment_django_pinax_python_wsgi.txt
Q: Python: Best practice for dynamically constructing regex I have a simple function to remove a "word" from some text: def remove_word_from(word, text): if not text or not word: return text rec = re.compile(r'(^|\s)(' + word + ')($|\s)', re.IGNORECASE) return rec.sub(r'\1\3', text, 1) The proble...
Python: Best practice for dynamically constructing regex
I have a simple function to remove a "word" from some text: def remove_word_from(word, text): if not text or not word: return text rec = re.compile(r'(^|\s)(' + word + ')($|\s)', re.IGNORECASE) return rec.sub(r'\1\3', text, 1) The problem, of course, is that if word contains characters such as "(" ...
[ "You can use re.escape(word) to escape the word.\n", "Unless you're forced to use regexps, couldn't you use instead the replace method for strings ?\ntext = text.replace(word, '')\n\nThis allows you to get rid of punctuation issues.\n" ]
[ 23, 0 ]
[ "Write a sanitizer function and pass word through that first.\ndef sanitize(word):\n def literalize(wd, escapee):\n return wd.replace(escapee, \"\\\\%s\"%escapee)\n return reduce(literalize, \"()[]*?{}.+|\", word)\n\ndef remove_word_from(word, text):\n if not text or not word: return text\n rec =...
[ -1 ]
[ "python", "regex" ]
stackoverflow_0004807141_python_regex.txt
Q: import class problem Possible Duplicate: Basic Python imports question i have project with this structure: project_folder: __init__.py classes_folder: __init__.py class1.py class2.py tests_folder: __init__.py test1.py Now i need import class1.py in test1.py. H...
import class problem
Possible Duplicate: Basic Python imports question i have project with this structure: project_folder: __init__.py classes_folder: __init__.py class1.py class2.py tests_folder: __init__.py test1.py Now i need import class1.py in test1.py. How can i do this?
[ "assuming PYTHONPATH=. and you are located in project folder then ...\nimport classes_folder.class1\nBy \"located\" I mean that you're running python from project folder.\nit's all relative to your PYTHONPATH. Take that into account.\nSo if you are located in project folder/tests_folder in order to avoid issues mak...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004807246_python.txt
Q: What libraries exist for creating raw multipart emails? I would like to ideally set up a user interface for designing emails that include text, html, and images, and would like this interface to output the raw encoded email so I can then pipe it to my mail application, save it in a database, etc.. Are there any ...
What libraries exist for creating raw multipart emails?
I would like to ideally set up a user interface for designing emails that include text, html, and images, and would like this interface to output the raw encoded email so I can then pipe it to my mail application, save it in a database, etc.. Are there any libraries that I could look at for generating raw emails, and...
[ "For python, try Turbomail . It's quite flexibile\n", "There is the Java mail API.\n", "Python has modules both for creating and sending emails in the standard library. Don't know about Java or Ruby. For generating HTML I'd use some HTML template language. There are tons of them for Python. Pick one you like.\n...
[ 3, 2, 1, 0 ]
[]
[]
[ "email", "java", "jquery", "python", "ruby" ]
stackoverflow_0004803499_email_java_jquery_python_ruby.txt
Q: Querying Python Functions by Signature What's the best way to document/decorate your Python functions/methods so that you're able to easily query them by signature (e.g. argument count, argument type, and return type)? I'm playing around with a genetic-programming package, and I'd like to extend it to be able to d...
Querying Python Functions by Signature
What's the best way to document/decorate your Python functions/methods so that you're able to easily query them by signature (e.g. argument count, argument type, and return type)? I'm playing around with a genetic-programming package, and I'd like to extend it to be able to dynamically replace a function in an expressi...
[ "You can get function's argument list using inspect. This includes default values, but of course cannot provide types, because the very definitions lack this info.\nDecorators like the one you shown seem the best solution for 2.x if you need type info. But I'd probably make their syntax a bit less parenthesized:\n@...
[ 2, 2, 0 ]
[]
[]
[ "python", "reflection" ]
stackoverflow_0004806490_python_reflection.txt
Q: Need advice on customized datastructure vs using in-memory DB? I'm writing a network scheduling like program in Python 2.6+ in which I have a complex queue requirement: Queue should store packets, should retrieve by timestamp or by packet ID in O(1), should be able to retrieve all the packets below a certain thres...
Need advice on customized datastructure vs using in-memory DB?
I'm writing a network scheduling like program in Python 2.6+ in which I have a complex queue requirement: Queue should store packets, should retrieve by timestamp or by packet ID in O(1), should be able to retrieve all the packets below a certain threshold, sort packet by priorities etc. It should insert and delete wit...
[ "A database is just some indexes and fancy algorithms wrapped around a single data structure -- a table. You don't have a lot of control about what happens under the hood.\nI'd try using the built-in Python datastructures.\n", "A Fibonacci Heap may be beneficial because (quoting from the article):\n\nOperations ...
[ 0, 0 ]
[]
[]
[ "data_structures", "python" ]
stackoverflow_0004802900_data_structures_python.txt
Q: Where can I get a complete list of UTF-8 characters for the English language? I'm mainly interested in the English language characters and punctuation. I need it for test data so I can emulate how an API handles different characters. Can I generate it using Python or PHP? A: Most English characters are simply as...
Where can I get a complete list of UTF-8 characters for the English language?
I'm mainly interested in the English language characters and punctuation. I need it for test data so I can emulate how an API handles different characters. Can I generate it using Python or PHP?
[ "Most English characters are simply ascii, but here is a complete list of utf-8 characters.\nHere is another list, sorted by sets of characters.\n", "You might want to check out the string module for python, that's got a few helpful data structures with data in them:\nhttp://docs.python.org/library/string.html#\n...
[ 2, 0, 0 ]
[]
[]
[ "character", "php", "python", "utf_8" ]
stackoverflow_0004807550_character_php_python_utf_8.txt
Q: Integrating Facebook Python SDK with Django What is the most efficient way to integrate Facebook Python SDK with Django's authentication system? Or shouldn't I do this at all and create my own users models? Basically, I'm using the Facebook JavaScript SDK for actually signing users on. Right now, when the JavaScri...
Integrating Facebook Python SDK with Django
What is the most efficient way to integrate Facebook Python SDK with Django's authentication system? Or shouldn't I do this at all and create my own users models? Basically, I'm using the Facebook JavaScript SDK for actually signing users on. Right now, when the JavaScript SDK creates the cookie, I'm using the Python S...
[ "I've had good luck with the django-socialregistration app.\n" ]
[ 2 ]
[]
[]
[ "django", "facebook", "python" ]
stackoverflow_0004807725_django_facebook_python.txt
Q: understanding how to Import variables from a method Lets say i have something like this: This is file tree.py: class leaf(): def green(): x = 100 This is file view.py: from tree import leaf.green g = green() print g.x How do i get the variable form subclass green I know for class its just: This is file tre...
understanding how to Import variables from a method
Lets say i have something like this: This is file tree.py: class leaf(): def green(): x = 100 This is file view.py: from tree import leaf.green g = green() print g.x How do i get the variable form subclass green I know for class its just: This is file tree.py: class leaf(): x = 100 This is file view.py: f...
[ "I think the root of your problem is that you need to learn more about how classes in Python work. Fortunately, the tutorial in the Python docs has a section on classes.\nIf that doesn't help, going through something like Learn Python the Hard Way and doing the exercises can be immensely helpful.\n", "x is local ...
[ 2, 1 ]
[]
[]
[ "python", "variables" ]
stackoverflow_0004807680_python_variables.txt
Q: Python sendmail() delivering after 12 hour delay I'm trying to avoid checking my email all the time, so I download all of my email once every 4 hours. I have a cron job that fetches unread messages from a Gmail account and then sends them to an account that I check. Recently however messages have been showing up ...
Python sendmail() delivering after 12 hour delay
I'm trying to avoid checking my email all the time, so I download all of my email once every 4 hours. I have a cron job that fetches unread messages from a Gmail account and then sends them to an account that I check. Recently however messages have been showing up inconsistently, sometimes with over a day's delay. All...
[ "Have a look into the mail headers of your send mails. One is added for each mail server, together with a timestamp. Then you can see the culprit.\n", "Take a look at your mail server logs. I bet you have lots of errors in there about GMail not accepting your email because (it looks like spam | that host has sen...
[ 1, 0 ]
[]
[]
[ "delay", "email", "python", "sendmail" ]
stackoverflow_0004807735_delay_email_python_sendmail.txt
Q: Python list initialization in for loop How do initialize a list in a for loop: for x, y in zip(list_x, list_y): x = f(x, y) unfortunately, this loop does not alter list_x even though I want it to. Is there a way to have references to the elements of list_x in the loop? I realize I could use a list comprehens...
Python list initialization in for loop
How do initialize a list in a for loop: for x, y in zip(list_x, list_y): x = f(x, y) unfortunately, this loop does not alter list_x even though I want it to. Is there a way to have references to the elements of list_x in the loop? I realize I could use a list comprehension, but that's hard to read when the for lo...
[ "why would list-comprehension be complicated?\nlist_x[:] = [f(tup) for tup in zip(list_x, list_y)]\n\nInstead of having 20-line for loop, you could use a set of generator expressions or abstract a subset of code into an f function.\nIt's really is pointless to talk about what could be done w/o seeing the code.\n", ...
[ 10, 3, 3 ]
[]
[]
[ "list", "list_comprehension", "python" ]
stackoverflow_0004807864_list_list_comprehension_python.txt
Q: Python, faking stdin I'm currently writing an abstraction over darcs in python, however once I'm trying to send data to my repository, the repository requests for a key; I was thinking wether it was possible to make python send keys to darcs, using stdin, or whatever, to emulate what the user would be typing, sinc...
Python, faking stdin
I'm currently writing an abstraction over darcs in python, however once I'm trying to send data to my repository, the repository requests for a key; I was thinking wether it was possible to make python send keys to darcs, using stdin, or whatever, to emulate what the user would be typing, since in this way; I could all...
[ "Try pexpect, which is built exactly for this purpose (automating other interactive apps).\nSee: http://pypi.python.org/pypi/pexpect/\nA usage example from the docs:\n import pexpect\n child = pexpect.spawn ('ftp ftp.openbsd.org')\n child.expect ('Name .*: ')\n child.sendline ('anonymous')\n child.expect...
[ 4, 3 ]
[]
[]
[ "pipe", "python", "stdin", "version_control" ]
stackoverflow_0004808138_pipe_python_stdin_version_control.txt
Q: Showing a file choosing dialog for a tree view column that contains paths I'm trying to show a GtkFileChooserDialog when a GtkTreeView column that contains paths is edited. I've come up with 2 possible ways to implement this: Hook the "editing-started" signal on the GtkCellRendererText that shows the path. Howeve...
Showing a file choosing dialog for a tree view column that contains paths
I'm trying to show a GtkFileChooserDialog when a GtkTreeView column that contains paths is edited. I've come up with 2 possible ways to implement this: Hook the "editing-started" signal on the GtkCellRendererText that shows the path. However this still requires that the "editing" be done inside the cell. I can't show ...
[ "You can override CellRendererText's do_start_editing method to completely change its behaviour:\nclass CellRendererFile(gtk.CellRendererText):\n def __init__(self):\n gtk.CellRendererText.__init__(self)\n self.props.editable = True\n\n def do_start_editing(self, event, widget, path, background_...
[ 1 ]
[]
[]
[ "gtk", "gtktreeview", "pygtk", "python" ]
stackoverflow_0004778500_gtk_gtktreeview_pygtk_python.txt
Q: python goto link generated by javascript everybody! i need to get some data from website, that generate its content with javascript. somehow, with ClientForm module help, i could authorize on the site and get needed data by passing needed form values to search lists. but than, i get a few pages of results. and i n...
python goto link generated by javascript
everybody! i need to get some data from website, that generate its content with javascript. somehow, with ClientForm module help, i could authorize on the site and get needed data by passing needed form values to search lists. but than, i get a few pages of results. and i need to loop over that pages, saving them. but ...
[ "Your options are essentially:\n\nWork out what the javascript is doing, and try to copy it in Python, so that the server sends you the same data. If you're not already using it, Firebug is the sort of thing you'll need.\nUse a browser control framework, such as Selenium RC, to interact with a browser using Python....
[ 1, 0 ]
[]
[]
[ "href", "hyperlink", "javascript", "python" ]
stackoverflow_0004806816_href_hyperlink_javascript_python.txt
Q: fabric and svn password Assuming that I cannot run something like this with Fabric: run("svn update --password 'password' .") how's the proper way to pass to Fabric the password for the remote interactive command line? The problem is that the repo is checked out as svn+ssh and I don't have a http/https/svn option...
fabric and svn password
Assuming that I cannot run something like this with Fabric: run("svn update --password 'password' .") how's the proper way to pass to Fabric the password for the remote interactive command line? The problem is that the repo is checked out as svn+ssh and I don't have a http/https/svn option
[ "Try SSHkey. It allows you to connect to the server without password.\nIn this case, you will have to setup a sshkey between your remote server and the repo.\nAt remote server: Generate key pair\n $ ssh-keygen -t dsa\n\nLeave the passphase empty! \nThis will generate 2 files \n\n~/.ssh/id_dsa (private key)\n~/.ssh/...
[ 7, 3, 2, 2, 0, 0 ]
[]
[]
[ "fabric", "python", "svn" ]
stackoverflow_0002561472_fabric_python_svn.txt
Q: Python FTP to iPad I'm on Windows 7. I cannot connect to my iPad with a simple Python script: HOST = '192.168.1.122' try: f = ftplib.FTP(HOST) except (socket.error, socket.gaierror), e: MessageBox.Show('ERROR: cannot reach "%s"' % HOST) return try: f.connect(HOST,2121) f.login() e...
Python FTP to iPad
I'm on Windows 7. I cannot connect to my iPad with a simple Python script: HOST = '192.168.1.122' try: f = ftplib.FTP(HOST) except (socket.error, socket.gaierror), e: MessageBox.Show('ERROR: cannot reach "%s"' % HOST) return try: f.connect(HOST,2121) f.login() except ftplib.error_perm:...
[ "You should read docs before anything:\n\nclass ftplib.FTP([host[, user[,\n passwd[, acct[, timeout]]]]]) Return a\n new instance of the FTP class. When\n host is given, the method call\n connect(host) is made. When user is\n given, additionally the method call\n login(user, passwd, acct) is made\n (where pa...
[ 4 ]
[]
[]
[ "ftp", "ipad", "python" ]
stackoverflow_0004805779_ftp_ipad_python.txt
Q: In Django, how do I write a this for every function? Whenever someone loads a page, I want to print "Hello" in console. I don't want to add a decorator to all my 100 views. That's silly. I sort of want this decorator to automatically be added to my views. Hmm... A: Middleware: http://docs.djangoproject.com/en/...
In Django, how do I write a this for every function?
Whenever someone loads a page, I want to print "Hello" in console. I don't want to add a decorator to all my 100 views. That's silly. I sort of want this decorator to automatically be added to my views. Hmm...
[ "Middleware: http://docs.djangoproject.com/en/dev/topics/http/middleware/#writing-your-own-middleware\nDefine a middleware class, override one of the functions defined above, print \"Hello\", return the appropriate object (according to docs), and add the middleware class to your settings.py\nclass PrintHelloMiddlew...
[ 5 ]
[]
[]
[ "decorator", "django", "oop", "python" ]
stackoverflow_0004808664_decorator_django_oop_python.txt
Q: PyQt displaying all margins There is too much space around my widgets in my application and I want to track down which widgets are causing this space. Is the only source of space contentMargins? Is there extra space created by QBoxLayout objects? What about the matplotlib FigureCanvas? My main question is: Is t...
PyQt displaying all margins
There is too much space around my widgets in my application and I want to track down which widgets are causing this space. Is the only source of space contentMargins? Is there extra space created by QBoxLayout objects? What about the matplotlib FigureCanvas? My main question is: Is there a program that recursively t...
[ "I am not aware of such program, but if you use Qt Designer, you can open *.ui files with any text viewer and look for properties with suspicious names such as \"margin\" or \"spacing\". Box layouts have them too, for example:\n <layout class=\"QVBoxLayout\" >\n <property name=\"spacing\" >\n <number>6</number>\...
[ 0 ]
[]
[]
[ "pyqt", "python", "qt" ]
stackoverflow_0004807899_pyqt_python_qt.txt
Q: How to fetch environment variables in Mac OS X using python? How can I lookup environment variables (e.g. export HG_USER from .profile) using python code in Mac OS X? A: os.environ is a dictionary containing all the environment variables. You need to import os before you can use it. So, for example HG_USER would...
How to fetch environment variables in Mac OS X using python?
How can I lookup environment variables (e.g. export HG_USER from .profile) using python code in Mac OS X?
[ "os.environ is a dictionary containing all the environment variables. You need to import os before you can use it.\nSo, for example HG_USER would be accessed by os.environ['HG_USER'].\n", "Use the os module:\nimport os\nos.environ\n\nReturns a dictionary with the environment variables as keys.\n", "Use os:\n>>>...
[ 11, 2, 2, 1 ]
[]
[]
[ ".profile", "environment_variables", "macos", "python" ]
stackoverflow_0004808809_.profile_environment_variables_macos_python.txt
Q: If I set a variable in my middleware, how do I make that available to my views in my views.py? This is my middleware: class Go(): def process_view(self, request, view_func, view_args, view_kwargs): aaa = "hello" return None If I go into my views.py and print aaa, I get an error. A: Try reque...
If I set a variable in my middleware, how do I make that available to my views in my views.py?
This is my middleware: class Go(): def process_view(self, request, view_func, view_args, view_kwargs): aaa = "hello" return None If I go into my views.py and print aaa, I get an error.
[ "Try\nrequest.aaa = \"hello\"\n\nand then in your view:\nprint request.aaa\n\n", "If you want it available in your views, you can add anything you want to the request object as that's ultimately passed down to your views.\nrequest.myvar = 'hello'\n\n" ]
[ 1, 1 ]
[]
[]
[ "django", "middleware", "python" ]
stackoverflow_0004808925_django_middleware_python.txt
Q: Find occurrence using multiple attributes in ElementTree/Python I have the following XML. <?xml version="1.0" encoding="UTF-8"?> <testsuites tests="10" failures="0" disabled="0" errors="0" time="0.001" name="AllTests"> <testsuite name="TestOne" tests="5" failures="0" disabled="0" errors="0" time="0.001"> <te...
Find occurrence using multiple attributes in ElementTree/Python
I have the following XML. <?xml version="1.0" encoding="UTF-8"?> <testsuites tests="10" failures="0" disabled="0" errors="0" time="0.001" name="AllTests"> <testsuite name="TestOne" tests="5" failures="0" disabled="0" errors="0" time="0.001"> <testcase name="DefaultConstructor" status="run" time="0" classname="Tes...
[ "This depends on what version you're using. If you have ElementTree 1.3+ (including in Python 2.7 standard library) you can use a basic xpath expression, as described in the docs, like [@attrib='value']:\nx = ElmentTree(file='testdata.xml')\ncases = x.findall(\".//testcase[@name='VHDL_BUILD_Passthrough'][@classname...
[ 24, 0 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0004808753_elementtree_python_xml.txt
Q: How can I send an SMS via AT command with Zoom 7.2m Tri-Band USB Modem? I am trying to make a simple python 2.6 application on OSX 10.6.6 that can send and receive SMS on my Zoom 7.2m (3g) USB Modem. On initially plugging into the USB modem, no TTY or CU sessions seem to be created. I have to run the modem softwar...
How can I send an SMS via AT command with Zoom 7.2m Tri-Band USB Modem?
I am trying to make a simple python 2.6 application on OSX 10.6.6 that can send and receive SMS on my Zoom 7.2m (3g) USB Modem. On initially plugging into the USB modem, no TTY or CU sessions seem to be created. I have to run the modem software to initiate the following sessions; cu.LJADeviceInterface2621 cu.LJADiagCon...
[ "Also remember that there are many projects out there that do the task for you (pysms is one of them)\n", "Well, I never use that modem but I suppose it uses standard GSM AT commands, and AT+CMGW is wrong.\nYou should send: AT+CMGS=\"+111111111\"\\r\\n SMS TEXT Ctrl-Z\nAnd that should work\n" ]
[ 1, 0 ]
[]
[]
[ "at_command", "gsm", "python", "serial_port", "zooming" ]
stackoverflow_0004795441_at_command_gsm_python_serial_port_zooming.txt
Q: Django: get the path to the current django app I have a Django app with some management commands. In one of those commands, I need to write a log file which is located in /logs allong side views.py, models.py, etc ... Considering that my management command script is in /management/commands/mycommand.py, is there ...
Django: get the path to the current django app
I have a Django app with some management commands. In one of those commands, I need to write a log file which is located in /logs allong side views.py, models.py, etc ... Considering that my management command script is in /management/commands/mycommand.py, is there any reliable way to determine the location of the ap...
[ "That's what your settings are for. \nAdd this to your settings\nMY_APP_LOG_DIRECTORY = \"path/to/logs\"\n\nIn your view functions, use\nfrom django.conf import settings\n\nNow you can use settings.MY_APP_LOG_DIRECTORY all you want.\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004809841_django_python.txt
Q: Tab key not indenting in Python I recently upgraded to python2.7 and noticed that the tab key does not function appropriately in the shell. Instead, it appears to search through the underlying directory (the standard unix behavior). If I change back over to python2.6, it works appropriately. Is there a way to add ...
Tab key not indenting in Python
I recently upgraded to python2.7 and noticed that the tab key does not function appropriately in the shell. Instead, it appears to search through the underlying directory (the standard unix behavior). If I change back over to python2.6, it works appropriately. Is there a way to add this functionality back to 2.7? For e...
[ "This is a known bug with python 2.7 on Mac OSX. More details (including a fix) can be found in the bug report.\n" ]
[ 9 ]
[]
[]
[ "python", "python_2.7", "shell" ]
stackoverflow_0004809820_python_python_2.7_shell.txt
Q: How to specify the bash environment to use the Numeric module for Python? I am trying to manually install the (now deprecated but I need it) Numeric module for python. I use Mandriva 2010. I have downloaded Numeric 24.2, used: python setup.py build python setup.py install --prefix=/other/directory So now, in /ot...
How to specify the bash environment to use the Numeric module for Python?
I am trying to manually install the (now deprecated but I need it) Numeric module for python. I use Mandriva 2010. I have downloaded Numeric 24.2, used: python setup.py build python setup.py install --prefix=/other/directory So now, in /other/directory, I have the following directories: ./include/python2.6/Numeric/ ....
[ "$PYTHONPATH should include the entry /other/directory/lib/python2.6/site-packages, and if a native library was installed in /other/directory/lib, then $LD_LIBRARY_PATH should include /other/directory/lib.\n", "I finally managed to find somebody to sorted it right!\nTo use Numeric, you have to add /other/directo...
[ 1, 0 ]
[]
[]
[ "linux", "module", "numeric", "path", "python" ]
stackoverflow_0004799815_linux_module_numeric_path_python.txt
Q: Django 1.1 FormWizard, Dynamically extend form I am trying to create a multipage form, where the number of field elements on the second page is defined by the answers given on the first. I have a formWizard set up and my understanding is that I need to use process_step() to alter the setup for the next page. I ca...
Django 1.1 FormWizard, Dynamically extend form
I am trying to create a multipage form, where the number of field elements on the second page is defined by the answers given on the first. I have a formWizard set up and my understanding is that I need to use process_step() to alter the setup for the next page. I can either extend an existing form definition to add m...
[ "Spender,\nAt least at the moment I don't know a way of merging multiple forms onto one page in a FormWizard. In django 1.2 you will be able to include FormSets as steps in FormWizards (as per this ticket) but those only deal with multiple copies of identical forms, not compilations of many forms. But there is a ...
[ 1, 0 ]
[]
[]
[ "django", "forms", "python", "wizard" ]
stackoverflow_0001963568_django_forms_python_wizard.txt
Q: How come this Django plugin won't work? https://github.com/sunlightlabs/django-mediasync/ The media syncs to S3, but it doesn't change the {% MEDIA_URL %} to the s3 url in my template (when I go to production) I followed all the instructions. Here's my settings.py. MEDIASYNC = { 'AWS_KEY': AWS_ACCESSKEY, '...
How come this Django plugin won't work?
ERROR: type should be string, got "https://github.com/sunlightlabs/django-mediasync/\nThe media syncs to S3, but it doesn't change the {% MEDIA_URL %} to the s3 url in my template (when I go to production)\nI followed all the instructions. Here's my settings.py.\nMEDIASYNC = {\n 'AWS_KEY': AWS_ACCESSKEY,\n 'AWS_SECRET': AWS_SECRETKEY,\n 'AWS_BUCKET': \"happy_media\",\n 'BACKEND': 'mediasync.backends.s3',\n 'SERVE_REMOTE': True,\n 'AWS_BUCKET_CNAME': True,\n 'DOCTYPE': 'html4',\n 'USE_SSL': False,\n 'CACHE_BUSTER': 1234,\n}\n\nI also added this to the urls.py\nfrom django.template import add_to_builtins\nadd_to_builtins('mediasync.templatetags.media')\n\nI also have:\n'django.core.context_processors.media' to my context processors in settings.py\n\n"
[ "Try including 'django.core.context_processors.media' to your list of context processors in settings.py. I think that's what exposes MEDIA_URL and makes it visible in templates.\n", "Do you have this template contex processor ?\ndjango.core.context_processors.request\n\n", "Solved.\nI simply did this:\n{% med...
[ 0, 0, 0 ]
[]
[]
[ "amazon_s3", "django", "production", "python" ]
stackoverflow_0004801139_amazon_s3_django_production_python.txt
Q: loop fails when increasing string from elements in list I have some problem with sequence generator. I have a file where each line contain one fragment (8 letters). I load it from file in to list, where each element is one fragment. It is DNA so it should go that way: 1. Takes first 8-letter element 2. Check for e...
loop fails when increasing string from elements in list
I have some problem with sequence generator. I have a file where each line contain one fragment (8 letters). I load it from file in to list, where each element is one fragment. It is DNA so it should go that way: 1. Takes first 8-letter element 2. Check for element in which first 7 letters is the same as last 7 letters...
[ "Because your fragments are shuffled, your algorithm needs to take that into account; currently, you're just looping through the fragments once, which is unlikely to include more than a few fragments if they're not in the right order. For example, say you have 5 fragments, which I'm going to refer to by their orde...
[ 3, 1, 0 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0004804064_linux_python.txt
Q: How can I profile pure dll? I have project that creates dlls. These dlls are invoked from python later by special plugin system blue-sky. So in this project it's very hard to build executable file, but I need profiling. Are there any profilers that can work with pure dlls? I've tried Intel Amplifier, Microsoft VS...
How can I profile pure dll?
I have project that creates dlls. These dlls are invoked from python later by special plugin system blue-sky. So in this project it's very hard to build executable file, but I need profiling. Are there any profilers that can work with pure dlls? I've tried Intel Amplifier, Microsoft VS2008 profiler they don't work. I'...
[ "You can't profile code that isn't running- that's the definition of profiling. You will need to build something that can run (an executable file) that links to the DLL and use that.\n", "If your dll is loaded by Python then you need to profile the Python process. With the Microsoft profiler as long as all the ....
[ 1, 1 ]
[]
[]
[ "c++", "dll", "profiling", "python" ]
stackoverflow_0004809950_c++_dll_profiling_python.txt
Q: how to clear the screen in python Possible Duplicates: clear terminal in python How to clear python interpreter console? I'm trying to write a program in Python but I don't know how to clear the screen. I use both Windows and Linux and I use commands to clear the screen in those, but I don't know how to do it in...
how to clear the screen in python
Possible Duplicates: clear terminal in python How to clear python interpreter console? I'm trying to write a program in Python but I don't know how to clear the screen. I use both Windows and Linux and I use commands to clear the screen in those, but I don't know how to do it in Python. How do I use Python to clear ...
[ "If you mean the screen where you have that interpreter prompt >>> you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do \nimport os\nos.system('cls') # on windows\n\nor\nos.system('clear') # on linux / os x\n\n" ]
[ 298 ]
[]
[]
[ "python", "screen" ]
stackoverflow_0004810537_python_screen.txt
Q: How do I make the DEBUG variable in my settings.py available in my templates in Django? Without having to go through the dictionary in render_to_response? A: Django has this built into the django.core.context_processors.debug context processor. So you just need to add that to your TEMPLATE_CONTEXT_PROCESSORS se...
How do I make the DEBUG variable in my settings.py available in my templates in Django?
Without having to go through the dictionary in render_to_response?
[ "Django has this built into the django.core.context_processors.debug context processor. So you just need to add that to your TEMPLATE_CONTEXT_PROCESSORS setting in your settings.py. This adds the debug context variable to all views using request context, and the source looks like this:\ndef debug(request):\n \"...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004810530_django_python.txt
Q: Iterate again within the for loop is there a way to iterate again within the for loop? For example: for x in list: if(condition): #I'd like to grab the next iteration of the list So if I had [1,2,3,4], I'd be iterating over 1 first, then trying to advance the iteration to 2 within the for loop so that wh...
Iterate again within the for loop
is there a way to iterate again within the for loop? For example: for x in list: if(condition): #I'd like to grab the next iteration of the list So if I had [1,2,3,4], I'd be iterating over 1 first, then trying to advance the iteration to 2 within the for loop so that when the loop started again, it'd be at 3...
[ "You could do something like this:\na = [1,2,3,4,5]\nb = iter(a)\n\ntry:\n while True:\n c = b.next()\n if (condition):\n c = b.next()\nexcept StopIteration:\n pass\n\n", "If the item you're using over is an iterable object you can use item.next() to grab the next element. But you'l...
[ 4, 3, 1, 1, 1, 1, 0 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0004810160_for_loop_python.txt
Q: f seems to be always positive in the MATLAB code, but in my Python code, f also gets negative values How to convert the following MATLAB code to Python? Here is my solution, but it doesn't quite produce the same results. For example, f seems to be always positive in the MATLAB code, but in my Python code, f also g...
f seems to be always positive in the MATLAB code, but in my Python code, f also gets negative values
How to convert the following MATLAB code to Python? Here is my solution, but it doesn't quite produce the same results. For example, f seems to be always positive in the MATLAB code, but in my Python code, f also gets negative values. Any ideas how to fix the program? Mostly, I am concerned about these: MATLAB: f...
[ "I don't know about matlab, but for python the code\nfor k in range(1,nx+1): \n j = k+2\n\nis the same as\nj = nx+2\n\nThis isn't your main problem, but it's worrying.\n" ]
[ 3 ]
[]
[]
[ "eigenvector", "matlab", "matrix", "python" ]
stackoverflow_0004779522_eigenvector_matlab_matrix_python.txt
Q: What is this extra character python puts before every field in an sql query? >>> c.execute('select * from zeol').fetchall() [(u'BBUL1', u'BCF-0106', u'', u'ENVIR', u'2011-01-25', u'18:02:10.92', u'***', u'ALARM', u'', u'', u'33387', u'7401', u'EXTERNAL AL 1', u'SYSTEM ON BATTERY', u''), (u'BBUL1', u'BCF-0106...
What is this extra character python puts before every field in an sql query?
>>> c.execute('select * from zeol').fetchall() [(u'BBUL1', u'BCF-0106', u'', u'ENVIR', u'2011-01-25', u'18:02:10.92', u'***', u'ALARM', u'', u'', u'33387', u'7401', u'EXTERNAL AL 1', u'SYSTEM ON BATTERY', u''), (u'BBUL1', u'BCF-0106', u'', u'ENVIR', u'2011-01-25', u'18:02:10.92', u'***', u'ALARM', u'', u'', u'...
[ "Because that means that this is python unicode string.\n", "That's part of the Python syntax for string constants; it means each string constant is a sequence of Unicode codepoints rather than 8-bit bytes. It shows up in the interactive environment because that uses repr to dump complex data structures. It won...
[ 3, 2, 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0004810853_python_sqlite.txt
Q: Python API for Amazon Simple Email Service I've made the API for Amazon SES: http://tagmask.com/vladimir/posts/26 It is my first experience in creating an API for such serious service. I want to make it useful for people, so my main question is what best practices to creating such API? A: I am assuming this won...
Python API for Amazon Simple Email Service
I've made the API for Amazon SES: http://tagmask.com/vladimir/posts/26 It is my first experience in creating an API for such serious service. I want to make it useful for people, so my main question is what best practices to creating such API?
[ "I am assuming this wont be a REST API or service, rather a wrapper for the new Amazon SES.\nFor a RESTful service, i'd defer you to REST guidelines\nAs for generic API design, there's a good start here. There are several PDF's available worth a read.\n" ]
[ 0 ]
[]
[]
[ "amazon_ses", "amazon_web_services", "api", "python" ]
stackoverflow_0004809456_amazon_ses_amazon_web_services_api_python.txt
Q: Sending file attachments using SMTPLIB.data() I'm trying to send an email using smtplib using the low-level commands such as MAIL, RCPT and DATA. This allows me to disguise the To field while still delivering to the proper inbox (required). My issue is that I have not found a way to send file attachments this way,...
Sending file attachments using SMTPLIB.data()
I'm trying to send an email using smtplib using the low-level commands such as MAIL, RCPT and DATA. This allows me to disguise the To field while still delivering to the proper inbox (required). My issue is that I have not found a way to send file attachments this way, and I have not found a way to 'spoof' the To field...
[ "This was actually pretty simple,\ncreate the MIMEMultipart message object, and simply call\nsmtp_server.data(message.as_string())\n\n" ]
[ 0 ]
[]
[]
[ "python", "smtplib" ]
stackoverflow_0004810896_python_smtplib.txt
Q: How to convert a MATLAB file to PYTHON? On someone's blog, I found some code that I want to modify with python. But I dont known Matlab syntax or code or have MATLAB to test... Can anyone help re-write with python, less comments. The Yahoo symbols I would be interested in would MSFT, IBM, and SPY. The Output as ...
How to convert a MATLAB file to PYTHON?
On someone's blog, I found some code that I want to modify with python. But I dont known Matlab syntax or code or have MATLAB to test... Can anyone help re-write with python, less comments. The Yahoo symbols I would be interested in would MSFT, IBM, and SPY. The Output as CSV works well. function DataOut = Get_Yaho...
[ "Here's a MATLAB to Python \"complier\": http://ompc.juricap.com/\nThere's even an on-line version you can cut and paste your code into: http://ompclib.appspot.com/m2py\nIt converted your code without crashing, but I can eyeball some problems in the conversion. However, it might be a nice starting point that you...
[ 1 ]
[]
[]
[ "csv", "matlab", "python" ]
stackoverflow_0004811136_csv_matlab_python.txt
Q: Setting a Super's property in a Subclass' __init__ I ran into an issue where I needed a custom getter with a vanilla setter. The problem happens when I try to set the attribute in a subclass's __init__. If I place the super's __init__ last it will overwrite the set in the Child class. Obviously having the super r...
Setting a Super's property in a Subclass' __init__
I ran into an issue where I needed a custom getter with a vanilla setter. The problem happens when I try to set the attribute in a subclass's __init__. If I place the super's __init__ last it will overwrite the set in the Child class. Obviously having the super run it's __init__ first fixes the issue and I've put an a...
[ "I would personally prefer the following solution:\nclass Parent(object):\n def __init__(self, x=None):\n self._x = x\n\nclass Child(Parent):\n def __init__(self, x):\n super(Child, self).__init__(x)\n\n" ]
[ 4 ]
[]
[]
[ "inheritance", "properties", "python" ]
stackoverflow_0004811485_inheritance_properties_python.txt
Q: finding a list item by its index I've started off with this. def month(n): lst = ['Months','Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] lst.index(x) I need it to work as follows: >>>first = month(1) >>>first 'Jan' >>> second = month(11) >>> second 'Nov' How can this be do...
finding a list item by its index
I've started off with this. def month(n): lst = ['Months','Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] lst.index(x) I need it to work as follows: >>>first = month(1) >>>first 'Jan' >>> second = month(11) >>> second 'Nov' How can this be done?
[ "def month(n):\n lst = ['Months','Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\n return lst[n]\n\n", "Why not use a dictionary?\nlst = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']\nmonths = dict(zip(range(1, 13), lst))\nmonth = months.g...
[ 4, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0004811379_list_python.txt
Q: List of Django model instance foreign keys losing consistency during state changes I have model, Match, with two foreign keys: class Match(model.Model): winner = models.ForeignKey(Player) loser = models.ForeignKey(Player) When I loop over Match I find that each model instance uses a unique object for the fo...
List of Django model instance foreign keys losing consistency during state changes
I have model, Match, with two foreign keys: class Match(model.Model): winner = models.ForeignKey(Player) loser = models.ForeignKey(Player) When I loop over Match I find that each model instance uses a unique object for the foreign key. This ends up biting me because it introduces inconsistency, here is an exampl...
[ "This is because, as far as I can tell, there's no global cache of model instances, so each query creates new instances, and your lists of related objcts are created lazily using separate queries.\nYou might find that select_related() is smart enough to solve the problem in this case. Instead of code like:\nmatch ...
[ 2, 1, 0, 0 ]
[]
[]
[ "django", "django_models", "foreign_keys", "python" ]
stackoverflow_0003019916_django_django_models_foreign_keys_python.txt
Q: Running an application in your localhost using php I have written a php script that will enable me to run a few batch files and python script in cmd prompt. The batch files and the python script are located in the same machine as my php script. The php script have a hyperlink image where if a user click the image ...
Running an application in your localhost using php
I have written a php script that will enable me to run a few batch files and python script in cmd prompt. The batch files and the python script are located in the same machine as my php script. The php script have a hyperlink image where if a user click the image it will load the command prompt to run the batch files a...
[ "You're using ActiveX, which firefox does not support. It sounds like you're trying to run a python script via a web browser? The simplest way to do this in a way that will work with all browsers is CGI. This means that the code will run on the web server instead of in the web browser, though, which might not be...
[ 0 ]
[]
[]
[ "batch_file", "firefox", "internet_explorer", "php", "python" ]
stackoverflow_0004802467_batch_file_firefox_internet_explorer_php_python.txt
Q: Quick Python Regex Question: Matching negated sets of characters I want to find strings that do NOT match a particular sequence of characters. For example: something like REGEX = r'[^XY]*' I'd like to look for strings that have any number of characters except an X and Y next to each other...the REGEX above doesn'...
Quick Python Regex Question: Matching negated sets of characters
I want to find strings that do NOT match a particular sequence of characters. For example: something like REGEX = r'[^XY]*' I'd like to look for strings that have any number of characters except an X and Y next to each other...the REGEX above doesn't work since it blocks X's and Y's separately.
[ "How about:\nif \"XY\" not in s:\n print \"matched\"\nelse\n print \"not matched\"\n\nOr is this for inclusion in some longer regexp? Then maybe you want a negative lookahead expression:\nREGEXP=\"...(?!XY)...\"\n\nEDIT: fixed typo\n", "There are a few ways to do that.\n^(?!.*XY).*$\n\nThe lookahead expressi...
[ 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004810858_python_regex.txt
Q: Parallelism with SciPy.optimize I'm working on some research code which uses scipy.optimize.leastsq to optimize a function. It does this about 18 times per iteration, so I would like call leastsq in parallel to reduce running time. This shouldn't be a problem because the optimizations are almost completely separat...
Parallelism with SciPy.optimize
I'm working on some research code which uses scipy.optimize.leastsq to optimize a function. It does this about 18 times per iteration, so I would like call leastsq in parallel to reduce running time. This shouldn't be a problem because the optimizations are almost completely separate so very little synchronization is r...
[ "Using processes instead of threads will make a difference -- it will work whether the program is threadsafe or not. Of course, whether it is faster depends if the time taken in solving the problem is larger than the overhead.\nUsing processes may require some additional hassle with setting up all necessary data. T...
[ 2 ]
[ "How many CPUs/cores? There's nothing to be gained if what you have is running at 100% without threading. If leastq() is not thread safe, and you're not using a 100% of the computer you have, then you can run one instance of the program per core and have the instances synchronize through the file system.\n" ]
[ -1 ]
[ "multithreading", "optimization", "python", "scipy", "thread_safety" ]
stackoverflow_0004598339_multithreading_optimization_python_scipy_thread_safety.txt
Q: Testing cherrypy with nose/fixture/webtest (amidoinitrite) I am developing a CherryPy application and I want to write some automated tests for it. I chose to use nosetests for it. The application uses sqlalchemy as db backend so I need to use fixture package to provide fixed datasets. Also I want to do webtests. H...
Testing cherrypy with nose/fixture/webtest (amidoinitrite)
I am developing a CherryPy application and I want to write some automated tests for it. I chose to use nosetests for it. The application uses sqlalchemy as db backend so I need to use fixture package to provide fixed datasets. Also I want to do webtests. Here is how I set it all together: I have a helper function init_...
[ "That looks mostly like normal testing glue for a system of any size. In other words, it's not overly-complicated.\nIn fact, I'd suggest slightly more complexity in one respect: I think you're going to find setting up a new database in each child test class to be really slow. It's more common to at least set up all...
[ 1 ]
[]
[]
[ "cherrypy", "fixture", "nose", "python", "webtest" ]
stackoverflow_0004806304_cherrypy_fixture_nose_python_webtest.txt
Q: python: get the abstract syntax tree of imported function? Let's say I've already imported a python module in the interpreter. How can I get the abstract syntax tree of the imported module (and any functions and classes within it) within the interpreter? I don't want to have to re-parse the source files. Thanks! ...
python: get the abstract syntax tree of imported function?
Let's say I've already imported a python module in the interpreter. How can I get the abstract syntax tree of the imported module (and any functions and classes within it) within the interpreter? I don't want to have to re-parse the source files. Thanks!
[ "Maybe you find some inspiration in this recipe:\n\nhttp://code.activestate.com/recipes/533146-ast-pretty-printer/\n\n\nA function that outputs a human-readable version of a Python AST.\n\nPython 2 option (as compiler is removed in Python 3): Use compiler combined with inspect (which, of course, still uses the sour...
[ 13, 0 ]
[]
[]
[ "abstract_syntax_tree", "python" ]
stackoverflow_0004812144_abstract_syntax_tree_python.txt
Q: Implement a function Implement a function punctuation() that takes no parameters, inputs a string from the user, and prints all of the punctuation characters appearing in the string, in order from left to right. def punctuation(): a = raw_input("Please enter a string:") check = ['!', ',', '.', ':', '?',...
Implement a function
Implement a function punctuation() that takes no parameters, inputs a string from the user, and prints all of the punctuation characters appearing in the string, in order from left to right. def punctuation(): a = raw_input("Please enter a string:") check = ['!', ',', '.', ':', '?', ';'] for p in check: ...
[ "It sounds like you are using Python 3. raw_input() has been replaced with input()\n", "You might want to do it the reverse way as far as your logic is concerned.\n\nMaintain a list (or string of) punctuation characters. (Check if the standard library module string has any help here)\nGo through each character o...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004812076_python.txt
Q: How come my Django code doesn't rollback changes when there is an error? Below is my code. (It's run by Celery, but I don't think that's important.) When an error occurs, the mongo record gets removed (yay!) but the .rollback() does not work, so mysql keeps the record instead of rolling it back. Why? class Submitt...
How come my Django code doesn't rollback changes when there is an error?
Below is my code. (It's run by Celery, but I don't think that's important.) When an error occurs, the mongo record gets removed (yay!) but the .rollback() does not work, so mysql keeps the record instead of rolling it back. Why? class Submitter(Task): @transaction.commit_manually def run(self, post, **kwargs): ...
[ "Because you're not using the InnoDB table engine, which, unlike MyISAM, supports transactions.\n" ]
[ 3 ]
[]
[]
[ "database", "django", "mysql", "python" ]
stackoverflow_0004812253_database_django_mysql_python.txt
Q: problem with turbogear2 quickstart example Hello I have Ubuntu 10.10 installed. And I wanted to try out Turbogear. I got the installation steps correctly I think. Problems that I have encountered though is in the steps where you create the quickstart example When I type in the command to create a quickstart examp...
problem with turbogear2 quickstart example
Hello I have Ubuntu 10.10 installed. And I wanted to try out Turbogear. I got the installation steps correctly I think. Problems that I have encountered though is in the steps where you create the quickstart example When I type in the command to create a quickstart example I followed the default values which is exampl...
[ "As to why it didn't get installed is an issue for turbogears, but...\n$ easy_install Genshi\n\nwill fix this.\n" ]
[ 3 ]
[]
[]
[ "genshi", "python", "turbogears2" ]
stackoverflow_0004811706_genshi_python_turbogears2.txt
Q: Can the main loop of a program be moved out of GUI? I'm using python 3 / tkinter if that matters. In looking at code samples I noticed that the main loop is typically in the GUI part of the code, and the rest of the code provides callbacks for GUI to call when needed. But my simulation runs independently of the us...
Can the main loop of a program be moved out of GUI?
I'm using python 3 / tkinter if that matters. In looking at code samples I noticed that the main loop is typically in the GUI part of the code, and the rest of the code provides callbacks for GUI to call when needed. But my simulation runs independently of the user interaction; the UI is there to provide a view, from t...
[ "Why not seperate your logic and presentation. Write your sim backend to respond to a single text based protcol to receive cmds and send back results, and then just talk to it from your gui program over e.g. unix sockets.\n", "Write your own main loop that calls the functions that check for and process GUI events...
[ 2, 1, 1 ]
[]
[]
[ "design_patterns", "python", "tkinter", "user_interface" ]
stackoverflow_0004812323_design_patterns_python_tkinter_user_interface.txt
Q: Python: Best way to call methods from another class? I have the following code: class Player: def __init__(self, username, trip, model): self.username = username self.trip = trip self.hp = 100 #### For player moving location/room #### def Move(self, dest): if dest == se...
Python: Best way to call methods from another class?
I have the following code: class Player: def __init__(self, username, trip, model): self.username = username self.trip = trip self.hp = 100 #### For player moving location/room #### def Move(self, dest): if dest == self.loc: return True # Check destinat...
[ "In my opinion, the first option is right out as it uses globals for no good reason. So the choice is between the second and the third.\nThe deciding feature is if you are going to want to use the same Player instance for more than one aGame value. If there will only ever be one value, then I would either pass it t...
[ 3, 0, 0, 0 ]
[]
[]
[ "class", "dictionary", "global", "oop", "python" ]
stackoverflow_0004812402_class_dictionary_global_oop_python.txt
Q: Function where characters will either +1 or -1 Implement a function crypto() where every character at a odd position i in the alphabet will be encrypted with the character at position i+1 and every character at an even position i will be encrypted with the character at position i-1. Or like, 'a' is encrypted with...
Function where characters will either +1 or -1
Implement a function crypto() where every character at a odd position i in the alphabet will be encrypted with the character at position i+1 and every character at an even position i will be encrypted with the character at position i-1. Or like, 'a' is encrypted with 'b', 'b' with 'a', 'c' with 'd', 'd' with 'c', 'e' ...
[ "Separate this problem into two parts:\n\nGiven a character, what character should it encrypt to? You're on the right track by using the ord function here. You can write a simple function that takes in a letter and returns the letter it should be encrypted to, if it should be changed at all.\nHow do you go through ...
[ 5, 3 ]
[]
[]
[ "python" ]
stackoverflow_0004812245_python.txt
Q: Automatic indexes for expando properties in the google app engine for python The google app engine python sdk offers an Expando type object which can be used for adding dynamic properties to an object that can be persisted to the datastore. The app engine also requires that for any property on which the objects ne...
Automatic indexes for expando properties in the google app engine for python
The google app engine python sdk offers an Expando type object which can be used for adding dynamic properties to an object that can be persisted to the datastore. The app engine also requires that for any property on which the objects need to be searched or sorted, an index must be created before uploading the app to ...
[ "All properties are automatically indexed for simple queries. Simple queries, in this case, are those that either:\n\nUse only equality filters, with no sort orders or inequality filters.\nHave an inequality filter or sort order on a single field, with no other filters.\n\nIf you want to do more complex queries - s...
[ 4 ]
[]
[]
[ "expando", "google_app_engine", "python" ]
stackoverflow_0004807957_expando_google_app_engine_python.txt
Q: python interpreter: interrupt and continue After I interrupt execution in Python interpreter (using CTRL-BREAK in Windows), can I continue execution? If not, is there any other way to interactively pause execution (so I can view variable values), and then continue? I prefer not to use the debugger because it's mu...
python interpreter: interrupt and continue
After I interrupt execution in Python interpreter (using CTRL-BREAK in Windows), can I continue execution? If not, is there any other way to interactively pause execution (so I can view variable values), and then continue? I prefer not to use the debugger because it's much slower than normal execution.
[ "I don't know if you mean pdb by debugger, but if you don't (and it might be helpful for others here), you can try:\n\nhttp://docs.python.org/library/pdb.html\n\nHere's a nice tutorial btw:\n\nhttp://onlamp.com/pub/a/python/2005/09/01/debugger.html\n\n", "I found some useful links that kinda answer my question:\n...
[ 2, 2 ]
[]
[]
[ "debugging", "interpreter", "python", "windows" ]
stackoverflow_0004198059_debugging_interpreter_python_windows.txt
Q: How can I log the outgoing request of urlfetch in google app engine python? I'm having trouble getting oauth to work with linkedin in GAE Python and I suspect it's the format of the outgoing request. How can I log or somehow view the outgoing request my devserver is making to the oauth provider? A: You can do th...
How can I log the outgoing request of urlfetch in google app engine python?
I'm having trouble getting oauth to work with linkedin in GAE Python and I suspect it's the format of the outgoing request. How can I log or somehow view the outgoing request my devserver is making to the oauth provider?
[ "You can do this by registering an API call hook for URLFetch requests. You can see the complete contents of the request or response object by logging request.ToASCII() or response.ToASCII()\n" ]
[ 5 ]
[]
[]
[ "google_app_engine", "linkedin", "oauth", "python" ]
stackoverflow_0004791050_google_app_engine_linkedin_oauth_python.txt
Q: Django: AttributeError - Object has no attribute This view is throwing the AttributeError saying :'PhotoForm' object has no attribute 'reservation'. What happens- the function passes, but doesn't actually upload the image. In debugging it, the form is not valid. I tried printing form.reservation form.message for...
Django: AttributeError - Object has no attribute
This view is throwing the AttributeError saying :'PhotoForm' object has no attribute 'reservation'. What happens- the function passes, but doesn't actually upload the image. In debugging it, the form is not valid. I tried printing form.reservation form.message form.photo But that shows this traceback ( which is the...
[ "should not forms (with image or file fields) be initialized with request.FILES?\nform = PhotoForm(request.POST, request.FILES)\n\n", "The key was having files=request.FILES in the form. \n@login_required\ndef new_photo(request, template_name=\"photo/newphoto.html\"):\n\n form = PhotoForm( user= request.user, da...
[ 5, 4, 0 ]
[]
[]
[ "django", "django_forms", "django_views", "python" ]
stackoverflow_0004777482_django_django_forms_django_views_python.txt
Q: How to perform queries in Django following double-join relationships (or: How to get around Django's restrictions on ManyToMany "through" models?) There must be a way to do this query through the ORM, but I'm not seeing it. The Setup Here's what I'm modelling: one Tenant can occupy multiple rooms and one User can ...
How to perform queries in Django following double-join relationships (or: How to get around Django's restrictions on ManyToMany "through" models?)
There must be a way to do this query through the ORM, but I'm not seeing it. The Setup Here's what I'm modelling: one Tenant can occupy multiple rooms and one User can own multiple rooms. So Rooms have an FK to Tenant and an FK to User. Rooms are also maintained by a (possibly distinct) User. That is, I have these (sim...
[ "The proper way to do this is with related_name:\nclass Tenant(models.Model):\n name = models.CharField(max_length=100)\n\nclass Room(models.Model):\n owner = models.ForeignKey(User, related_name='owns')\n maintainer = models.ForeignKey(User, related_name='maintains')\n tenant = models.ForeignKey(Tenant...
[ 3 ]
[]
[]
[ "django", "django_models", "django_orm", "django_queryset", "python" ]
stackoverflow_0004812106_django_django_models_django_orm_django_queryset_python.txt
Q: Get or Create matching Key and User (Python - App Engine) Trying to match a record and user using 'get_or_insert' in Python on Google App Engine. Using the below Models, I want to check if a User has a record for a Book already created (listed in BookUser), if they do have a record in BookUser get the details for ...
Get or Create matching Key and User (Python - App Engine)
Trying to match a record and user using 'get_or_insert' in Python on Google App Engine. Using the below Models, I want to check if a User has a record for a Book already created (listed in BookUser), if they do have a record in BookUser get the details for it. If they don't create it with XX data and associate it to th...
[ "You could make the BookUser entity's key a composite of the User and Book's key, that will give you a very simple way of making the relationship unique.\nbookuser_key_name = \"%s:%s\" % (str(book_key.id_or_name()), str(user_key.id_or_name()))\nbookuser = BookUser.get_or_insert(bookuser_key_name)\n# set your values...
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0004812832_google_app_engine_python.txt
Q: If I want to run Nginx and Django, what's the best method? A couple of questions: Should I use FastCGI or uWSGI? Should I modify the nginx.conf file or the file in /site-enabled/default? What tutorial should I use? A: The official Wiki is really helpful : http://code.djangoproject.com/wiki/ServerArrangements / ...
If I want to run Nginx and Django, what's the best method?
A couple of questions: Should I use FastCGI or uWSGI? Should I modify the nginx.conf file or the file in /site-enabled/default? What tutorial should I use?
[ "The official Wiki is really helpful : http://code.djangoproject.com/wiki/ServerArrangements / http://code.djangoproject.com/wiki/DjangoAndNginx\n" ]
[ 0 ]
[]
[]
[ "apache", "django", "http", "nginx", "python" ]
stackoverflow_0004812931_apache_django_http_nginx_python.txt
Q: Numpy: Reshaping this array in the least number of operations I have an array with 112 lines and 40 columns. The format I need to convert to is 40 sets of 56 points each with x, y. So, the first line has the x coordinates of the first point in each set. The second line has the x of the second points in the set... ...
Numpy: Reshaping this array in the least number of operations
I have an array with 112 lines and 40 columns. The format I need to convert to is 40 sets of 56 points each with x, y. So, the first line has the x coordinates of the first point in each set. The second line has the x of the second points in the set... until the 56th line. After that I have the y's. 1st line : 40 x's ...
[ "Just one idea:\n[[(data[i,j], data[i+56,j]) for i in range(56)] for j in range(40)]\n\nReturns a list of list of tuples.\nEDIT: Your edit clarifies what you want. If you want pure Numpy, then does this work?\ndata.reshape(2, 56, 40).swapaxes(0,2)\n\n", "I'll use a smaller array (8 x 5) so we can view the returne...
[ 4, 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0004812859_numpy_python.txt
Q: Django/Python Circular model reference Ok So I'm TRYING to write nice organized code and actually making seperate django apps instead of lumping everything together into 1. My problem is that I have 3 apps that each reference 1 other model from the next app. So basically I have an endless loop, App A needs to know...
Django/Python Circular model reference
Ok So I'm TRYING to write nice organized code and actually making seperate django apps instead of lumping everything together into 1. My problem is that I have 3 apps that each reference 1 other model from the next app. So basically I have an endless loop, App A needs to know about B.models.something1 , App B needs t...
[ "From the docs:\n\nTo refer to models defined in another\n application, you can explicitly\n specify a model with the full\n application label. For example, if the\n Manufacturer model above is defined in\n another application called production,\n you'd need to use:\n\nclass Car(models.Model):\n manufactu...
[ 37 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0004813293_django_django_models_python.txt
Q: I am unable to interact wih subprocess created by Popen I am using python 2.5 in windows xp. In this i am using subprocess to run my shell, now how should i has to run gdb in shell using subprocess. my code: PID = subprocess.Popen('C:/STM/STxP70_Toolset_2010.2/bin/STxP70.bat', shell=True, stdin=subprocess.PIPE, st...
I am unable to interact wih subprocess created by Popen
I am using python 2.5 in windows xp. In this i am using subprocess to run my shell, now how should i has to run gdb in shell using subprocess. my code: PID = subprocess.Popen('C:/STM/STxP70_Toolset_2010.2/bin/STxP70.bat', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE). Now shell wil...
[ "Your code:\n\nStarts STxP70.bat\nWrites string \"gdb\" (with no terminating newline) to it's standard input and closes the standard input.\nIs reading it's output until end of file. PID.communicate won't let you to interact with the subprocess any further—it writes the provided string and than collects all output ...
[ 1 ]
[]
[]
[ "gdb", "python" ]
stackoverflow_0004813029_gdb_python.txt
Q: Implementing OData JSON interface on Django (Python) We would like to have a OData JSON interface on our Django (Python 2.5.4) website. At the moment of writing there seems to be no library available. I'm thinking of writing "some" logic to handle this ourselves. Would it be a good idea to extend the Django JSON...
Implementing OData JSON interface on Django (Python)
We would like to have a OData JSON interface on our Django (Python 2.5.4) website. At the moment of writing there seems to be no library available. I'm thinking of writing "some" logic to handle this ourselves. Would it be a good idea to extend the Django JSON serializer? Where and how to store the URI's related to t...
[ "I think it would be a good idea to extend the Django JSON serializer, but have a look at django-piston this might be the better route to go.\nThe URI's will have to be defined in your urls.py for your app, and then in your models you could define a function\nget_odata_uri()\nWhich would work like the Django's get_...
[ 1 ]
[]
[]
[ "django", "json", "odata", "python" ]
stackoverflow_0004122159_django_json_odata_python.txt
Q: How do you access an authenticated Google App Engine service from a (non-web) python client? I have a Google App Engine app - http://mylovelyapp.appspot.com/ It has a page - mylovelypage For the moment, the page just does self.response.out.write('OK') If I run the following Python at my computer: import urllib2 f ...
How do you access an authenticated Google App Engine service from a (non-web) python client?
I have a Google App Engine app - http://mylovelyapp.appspot.com/ It has a page - mylovelypage For the moment, the page just does self.response.out.write('OK') If I run the following Python at my computer: import urllib2 f = urllib2.urlopen("http://mylovelyapp.appspot.com/mylovelypage") s = f.read() print s f.close() i...
[ "appcfg.py, the tool that uploads data to App Engine has to do exactly this to authenticate itself with the App Engine server. The relevant functionality is abstracted into appengine_rpc.py. In a nutshell, the solution is:\n\nUse the Google ClientLogin API to obtain an authentication token. appengine_rpc.py does th...
[ 39, 34, 1, 0 ]
[ "I'm not a python expert or a app engine expert. But did you try following the sample appl at http://code.google.com/appengine/docs/gettingstarted/usingusers.html. I created one at http://quizengine.appspot.com, it seemed to work fine with Google authentication and everything.\nJust a suggestion, but look in to the...
[ -1 ]
[ "authentication", "google_app_engine", "python", "web_services" ]
stackoverflow_0000101742_authentication_google_app_engine_python_web_services.txt