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: Problem with Python and MySQL I am trying to import a large text file into a MySQL database. The SQL statement is as follows: LOAD DATA INFILE '/tmp/epf/full/album_popularity_per_genre' INTO TABLE album_popularity_per_genre CHARACTER SET UTF8 FIELDS TERMINATED BY X'01' LINES TERMINATED BY '\n' IGNORE 45 LINES ...
Problem with Python and MySQL
I am trying to import a large text file into a MySQL database. The SQL statement is as follows: LOAD DATA INFILE '/tmp/epf/full/album_popularity_per_genre' INTO TABLE album_popularity_per_genre CHARACTER SET UTF8 FIELDS TERMINATED BY X'01' LINES TERMINATED BY '\n' IGNORE 45 LINES (export_date, storefront_id, genre_...
[ "The Python DBAPI is implicitly transactional. Try adding dbConnection.commit() after the execute.\n" ]
[ 2 ]
[]
[]
[ "load_data_infile", "mysql", "phpmyadmin", "python" ]
stackoverflow_0006112721_load_data_infile_mysql_phpmyadmin_python.txt
Q: How to recalculate IP checksum with scapy? Possible Duplicate: How to calculate a packet checksum without sending it? I've spoofed a source IP and MAC address in a captured packet, but now I need to recalculate the checksum so that it checks out once its been received (after being injected into the network of co...
How to recalculate IP checksum with scapy?
Possible Duplicate: How to calculate a packet checksum without sending it? I've spoofed a source IP and MAC address in a captured packet, but now I need to recalculate the checksum so that it checks out once its been received (after being injected into the network of course). I didn't really want to implement the ch...
[ "As shown here, you have to delete the .chksum attribute before calling the show2() method from scapy\n", "Let's say for argument's sake that we're processing an IP header and want to recalculate the checksum after the next hop:\n>>> iph = IP(import_hexcap())\n0000 4500 0064 000f 0000 fe01 3726 c0a8 0108\n0010 c0...
[ 14, 4 ]
[]
[]
[ "ip", "python", "scapy", "spoofing" ]
stackoverflow_0006112913_ip_python_scapy_spoofing.txt
Q: Object doesn't implement IField I have following piece of code to patch the Folder: ATFolderSchema = ATContentTypeSchema.copy() + \ ConstrainTypesMixinSchema.copy() + NextPreviousAwareSchema.copy() finalizeATCTSchema(ATFolderSchema, folderish=True, moveDiscussion=False) field = StringField("rafal_shortdescri...
Object doesn't implement IField
I have following piece of code to patch the Folder: ATFolderSchema = ATContentTypeSchema.copy() + \ ConstrainTypesMixinSchema.copy() + NextPreviousAwareSchema.copy() finalizeATCTSchema(ATFolderSchema, folderish=True, moveDiscussion=False) field = StringField("rafal_shortdescription", schemata = "defau...
[ "I'd advise you to use archetypes.schemaextender instead of using patches to alter Archetypes content types.\nThe package includes documentation on how to implement your additional field.\nAs for your error, you created a tuple with one element, a field:\n>>> example = 1,\n>>> print example\n(1,)\n\nDelete the trai...
[ 6 ]
[]
[]
[ "archetypes", "plone", "python", "zope" ]
stackoverflow_0006112181_archetypes_plone_python_zope.txt
Q: Which pythonIDE i can use to link with VPS django project I have Django running in my VPS . I find it very hard to ssh everytime and edit files and commands there. I know there are IDEs available like komodo , Pycharm but i want to use that IDE which link with my remote VPS . I don't know if thats exactly possible...
Which pythonIDE i can use to link with VPS django project
I have Django running in my VPS . I find it very hard to ssh everytime and edit files and commands there. I know there are IDEs available like komodo , Pycharm but i want to use that IDE which link with my remote VPS . I don't know if thats exactly possible or not.
[ "I'd recommend doing all your development locally (on localhost). Once you have a working product upload to your VPS. \nDjango has tools for this built right into it.\n", "you shoud be able to do what you are asking for using the Remote System Explorer in Eclipse (it is provided by default, it's not external a...
[ 3, 1 ]
[]
[]
[ "django", "ide", "python" ]
stackoverflow_0006113668_django_ide_python.txt
Q: app_label permission problem Django i've changed the app label doing this class Model(models.Model): pass class Meta: app_label = 'App Name' db_table = 'app_table' The table and application already existed, the problem is that when i go to the admin interface, only the superusers ca...
app_label permission problem Django
i've changed the app label doing this class Model(models.Model): pass class Meta: app_label = 'App Name' db_table = 'app_table' The table and application already existed, the problem is that when i go to the admin interface, only the superusers can view the app, and other users not, i tr...
[ "This is definitely a bug in Django. There's a conflict between the permission app_label and the contenttype app_label, result in the permission never matching in the admin. As a workaround until this is fixed, you can simply explicitly grant permission on the ModelAdmin:\nclass MyModelAdmin(admin.ModelAdmin):\n ...
[ 3, 0, 0, 0 ]
[]
[]
[ "django", "django_admin", "django_models", "django_permissions", "python" ]
stackoverflow_0004971435_django_django_admin_django_models_django_permissions_python.txt
Q: wxPython: How to fix the size of one part of a grid sizer What I want to do is create 3 column that will expand as the window expands. But I want to put limits on it so the different columns expand to different maximum amounts. What I have done here is used wxGlade to create a frame w/ a grid sizer that has 1 row...
wxPython: How to fix the size of one part of a grid sizer
What I want to do is create 3 column that will expand as the window expands. But I want to put limits on it so the different columns expand to different maximum amounts. What I have done here is used wxGlade to create a frame w/ a grid sizer that has 1 row and three columns. I want Part1 to have a fixed width of 'A',...
[ "If you're using a GridSizer I'd probably suggest you take a look at GridBagSizer instead. \nOnce you decide if that'll be usable, then you probably need to look into the sizer.AddGrowableRow(row) and sizer.AddGrowableCol(col) methods. They allow you to indicate columns or rows in the grid that expand. They don'...
[ 1 ]
[]
[]
[ "python", "sizer", "wxpython" ]
stackoverflow_0006113843_python_sizer_wxpython.txt
Q: Installing Python's libxml2dom on Ubuntu 11.04 Interested in using libxml2dom in a Python script of mine to (obviously) parse some XML. When I attempt to import "libxml2dom" I receive the error message "ImportError: No module named libxml2dom" I can't seem to find it in the apt-get repo It doesn't seem to be pres...
Installing Python's libxml2dom on Ubuntu 11.04
Interested in using libxml2dom in a Python script of mine to (obviously) parse some XML. When I attempt to import "libxml2dom" I receive the error message "ImportError: No module named libxml2dom" I can't seem to find it in the apt-get repo It doesn't seem to be present within easy_install. I already have libxml2 inst...
[ "pip install works for me on Ubuntu 11.04 (python 2.7)\n$ sudo apt-get install python-pip\n$ sudo pip install libxml2dom\n\n" ]
[ 1 ]
[]
[]
[ "libxml2", "python", "xml" ]
stackoverflow_0006114069_libxml2_python_xml.txt
Q: Is there a Java equivalent of Python's printf hash replacement? Specifically I am converting a python script into a java helper method. Here is a snippet (slightly modified for simplicity). # hash of values vals = {} vals['a'] = 'a' vals['b'] = 'b' vals['1'] = 1 output = sys.stdout file = open(filename).read() p...
Is there a Java equivalent of Python's printf hash replacement?
Specifically I am converting a python script into a java helper method. Here is a snippet (slightly modified for simplicity). # hash of values vals = {} vals['a'] = 'a' vals['b'] = 'b' vals['1'] = 1 output = sys.stdout file = open(filename).read() print >>output, file % vals, So in the file there are %(a), %(b), %(1...
[ "You can't do this directly without some additional templating library. I recommend StringTemplate. Very lightweight, easy to use, and very optimized and robust.\n", "I doubt you'll find a pure Java solution that'll do exactly what you want out of the box.\nWith this in mind, the best answer depends on the comple...
[ 1, 0 ]
[]
[]
[ "java", "python" ]
stackoverflow_0006114562_java_python.txt
Q: How to call individual form fields in Django templates that have the same name? This is how I would call a individual form field: {{ form.product }} This would display only the form element with the name "product". But what about in the case of radio buttons or checkboxes where multiple form fields have the same ...
How to call individual form fields in Django templates that have the same name?
This is how I would call a individual form field: {{ form.product }} This would display only the form element with the name "product". But what about in the case of radio buttons or checkboxes where multiple form fields have the same name. How do I call one over another then? Is there a way to use value instead of nam...
[ "I think you need to work more closely with your Python developers :-)\nBasically, if the case were to arise where there are multiple radio buttons/checkboxes with the same name, they should be easily provided to you under the form, using the same schema you're using already.\nSo, make sure your developer gives you...
[ 1 ]
[]
[]
[ "django", "python", "templates" ]
stackoverflow_0006114916_django_python_templates.txt
Q: Displaying a subset of data with Django ModelChoiceField and bound data When using ModelChoiceField in Django forms I only want a subset of the data (in my case the last 100 entries) to be rendered, since the data set is very large. At the same time I want to the user to still be able to choose from any object in ...
Displaying a subset of data with Django ModelChoiceField and bound data
When using ModelChoiceField in Django forms I only want a subset of the data (in my case the last 100 entries) to be rendered, since the data set is very large. At the same time I want to the user to still be able to choose from any object in the database, not just the ones displayed by default (I'm using AJAX to query...
[ "This is not technically a Django question. Your best bet is to store the information about the state of the list in a hidden field (not the items, necessarily, but the info you need to know how to get those items again). Then, pass that info back to the template and use your AJAX functionality to fetch it again.\n...
[ 0 ]
[]
[]
[ "django", "django_forms", "django_queryset", "forms", "python" ]
stackoverflow_0006113299_django_django_forms_django_queryset_forms_python.txt
Q: How to redirect stderr of a program that is run using os.system by a third-party python library I use external library, like this: from some_lib import runThatProgram infile = '/tmp/test' outfile = '/tmp/testout' runThatProgram(infile, outfile) while runThatProgram is: def runThatProgram(infile, outfile): o...
How to redirect stderr of a program that is run using os.system by a third-party python library
I use external library, like this: from some_lib import runThatProgram infile = '/tmp/test' outfile = '/tmp/testout' runThatProgram(infile, outfile) while runThatProgram is: def runThatProgram(infile, outfile): os.system("%s %s > %s" % ('thatProgram', infile, outfile)) The problem is that 'thatProgram' returns ...
[ "To illustrate what Rosh Oxymoron said, you can hack the code like this :\nfrom some_lib import runThatProgram\n\ninfile = '/tmp/test'\noutfile = '/tmp/testout 2>&1'\nrunThatProgram(infile, outfile)\n\nwith this, it will call \nthatProgram /tmp/test > /tmp/testout 2>&1\n\nthat will redirected stderr (2) to stdout (...
[ 2, 0 ]
[]
[]
[ "io", "python" ]
stackoverflow_0006111528_io_python.txt
Q: How to override the automatically created docstring data for Boost::Python? I am currently working developing a C++-based module for Python. I have found that Boost::Python is working quite well for what I want to accomplish. However, I am now running into some issues with the docstring that is being generated b...
How to override the automatically created docstring data for Boost::Python?
I am currently working developing a C++-based module for Python. I have found that Boost::Python is working quite well for what I want to accomplish. However, I am now running into some issues with the docstring that is being generated by Boost::Python. Given the following Boost::Python definitions: BOOST_PYTHON_MOD...
[ "\nUse the boost::python::docstring_options class to define your auto-created docstring options.\nAll def functions take a docstring as the last parameter.\nAll class_ definitions take the class docstring as the last parameter\n\nI.e.:\nusing boost::python;\nBOOST_PYTHON_MODULE(foo)\n{\n // This will enable user-d...
[ 21 ]
[]
[]
[ "boost", "boost_python", "c++", "documentation", "python" ]
stackoverflow_0006114462_boost_boost_python_c++_documentation_python.txt
Q: Python Event-Category Mapping Design I am working on some code to organize our event definition/category mapping. Our goal is to be able to define "event names" as well as associate categories, its pretty much a static process. What we want is people using constants and not a bunch of strings everywhere. We also...
Python Event-Category Mapping Design
I am working on some code to organize our event definition/category mapping. Our goal is to be able to define "event names" as well as associate categories, its pretty much a static process. What we want is people using constants and not a bunch of strings everywhere. We also need somewhere to validate events/categor...
[ "Why don't you go for something more pythonic?\nfrom collections import defaultdict\n\n\n_linked = defaultdict(set)\n\n\nclass Linkable(object):\n\n def link(self, *others):\n _linked[self].update(others)\n for each in others:\n _linked[each].add(self)\n\n def unlink(self, *others):\n...
[ 1 ]
[]
[]
[ "events", "python" ]
stackoverflow_0006110234_events_python.txt
Q: How much time is the garbage collector using? My python program has a curious performance behavior: The longer it runs, the slower it gets. Early on, it cranks out tens of work units per minute. After an hour of so it is taking tens of minutes per work unit. My suspicion is that this is cause by a congested garbag...
How much time is the garbage collector using?
My python program has a curious performance behavior: The longer it runs, the slower it gets. Early on, it cranks out tens of work units per minute. After an hour of so it is taking tens of minutes per work unit. My suspicion is that this is cause by a congested garbage collector. The catch is that my script is too mem...
[ "In Python, most garbage is collected using reference counting. One would expect this to be quick and painless, and it seems unlikely that this is what you're after. I assume you're asking about the collector referred to by the gc module, which is only used for circular references.\nThere are a few things that migh...
[ 9 ]
[]
[]
[ "garbage_collection", "profile", "python" ]
stackoverflow_0006115066_garbage_collection_profile_python.txt
Q: Python utf8 encoding problem I'm working on a Python application and having some problems handling strings. There is this string "She’s Out of My League" (without quotes). I stored it in a variable and tried to insert it into an sqlite3 database. But, I get this error: sqlite3.ProgrammingError: You must not use 8...
Python utf8 encoding problem
I'm working on a Python application and having some problems handling strings. There is this string "She’s Out of My League" (without quotes). I stored it in a variable and tried to insert it into an sqlite3 database. But, I get this error: sqlite3.ProgrammingError: You must not use 8-bit bytestrings unless you use a ...
[ "Simple. You're assuming that it's UTF-8.\n>>> print 'She\\x92s Out of My League'.decode('cp1252')\nShe’s Out of My League\n\n" ]
[ 1 ]
[]
[]
[ "encoding", "python", "unicode" ]
stackoverflow_0006115405_encoding_python_unicode.txt
Q: Quick question regarding format of if-elif statements If I wanted a group of if elif statements to execute to a single order; for example: if int(one[1]) == solution: and if int(two[1]) == solution: to execute a a single statement: print "Hello World" What would be the best format and syntaxically correct way...
Quick question regarding format of if-elif statements
If I wanted a group of if elif statements to execute to a single order; for example: if int(one[1]) == solution: and if int(two[1]) == solution: to execute a a single statement: print "Hello World" What would be the best format and syntaxically correct way to input this? I tried: if int(two[1]) == solution:: e...
[ "If you want to print it when both conditions are true you have to use and\nif (int(one[1]) == solution) and (int(two[1]) == solution):\n print \"Hello, world\"\n\nif you want to print it if one ore more condition is true you have to use or the same way \nif (int(one[1]) == solution) or (int(two[1]) == solution)...
[ 9, 2, 1, 1, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0006110601_if_statement_python.txt
Q: Problem with reading pasted text in terminal I'm reading text in terminal with description = raw_input() It works if I write the text and press enter. The problem is when I paste the text from somewhere with Ctrl+Shift+V or with right click + paste. My program immediately ends, description contains only part of th...
Problem with reading pasted text in terminal
I'm reading text in terminal with description = raw_input() It works if I write the text and press enter. The problem is when I paste the text from somewhere with Ctrl+Shift+V or with right click + paste. My program immediately ends, description contains only part of the text (I can see it in database). Do you know how...
[ "Make sure that your pasted text doesn't contain any embedded control characters (such as a newline), which could end the input.\n", "Try this, lifted it from a google search. You have to enter 3 blank lines after your paste, but of course, if there are 3 blank lines in your paste, then it won't work. The concept...
[ 3, 1 ]
[]
[]
[ "python", "terminal" ]
stackoverflow_0006115347_python_terminal.txt
Q: Django/python: loop through a dictionary and add an item to it Apologies for probably simple question, I've read the docs and still can't get this working. I'm making a raw SQL query in Django which is long so I won't post it here - suffice it to say that it works and returns results. I want to loop through my que...
Django/python: loop through a dictionary and add an item to it
Apologies for probably simple question, I've read the docs and still can't get this working. I'm making a raw SQL query in Django which is long so I won't post it here - suffice it to say that it works and returns results. I want to loop through my query results and check to see if the bandname is of the format "The [b...
[ "First, avoid raw SQL queries. They're rarely necessary. That's a separate question, however.\nYou have two ways to touch up your results.\nIn the model. If you can find a way to avoid raw SQL, you can easily add a property to your model to handle this.\nclass Media( models.Model ):\n @property\n def clean...
[ 2, 0 ]
[]
[]
[ "dictionary", "django", "python" ]
stackoverflow_0006116042_dictionary_django_python.txt
Q: Python and MySQL connection problems (mysqldb api) I have config.ini: [mysql] host=localhost port=3306 user=root passwd=abcdefgh db=testdb unix_socket=/opt/lampp/var/mysql/mysql.sock I have this class: #!/usr/bin/python import MySQLdb,ConfigParser config = ConfigParser.ConfigParser() config.read("config.ini") cl...
Python and MySQL connection problems (mysqldb api)
I have config.ini: [mysql] host=localhost port=3306 user=root passwd=abcdefgh db=testdb unix_socket=/opt/lampp/var/mysql/mysql.sock I have this class: #!/usr/bin/python import MySQLdb,ConfigParser config = ConfigParser.ConfigParser() config.read("config.ini") class MySQL( object ): def __init__( self ): ...
[ "Your __del__ method is causing confusion. Specifically, it refers to self.cursor and self.conn which may never get created if, for example, MySQLdb.Connect raises an exception (which is what seems to happen).\nI suggest you modify your class as follows:\nclass MySQL( object ):\n\n def __init__( self ):\n\n ...
[ 2, 1, 0 ]
[]
[]
[ "database_connection", "mysql", "mysql_python", "python" ]
stackoverflow_0006114064_database_connection_mysql_mysql_python_python.txt
Q: How to create a Python script that grabs text from one site and reposts it to another? I would like to create a Python script that grabs digits of Pi from this site: http://www.piday.org/million.php and reposts them to this site: http://www.freelove-forum.com/index.php I am NOT spamming or playing a prank, it is a...
How to create a Python script that grabs text from one site and reposts it to another?
I would like to create a Python script that grabs digits of Pi from this site: http://www.piday.org/million.php and reposts them to this site: http://www.freelove-forum.com/index.php I am NOT spamming or playing a prank, it is an inside joke with the creator and webmaster, a belated Pi day celebration, if you will.
[ "Import urllib2 and BeautifulSoup\nimport urllib2\nfrom BeautifulSoup import BeautifulSoup\n\nspecify the url and fetch using urllib2\nurl = 'http://www.piday.org/million.php'\nresponse = urlopen(url)\n\nand then use BeautifulSoup which uses the tags in the page to build a dictionary, and then you can query the di...
[ 1, 1, 0 ]
[]
[]
[ "python", "scripting" ]
stackoverflow_0006109897_python_scripting.txt
Q: SQLAlchemy: avoiding repetition in declarative style class definition I'm using SQLAlchemy, and many classes in my object model have the same two attributes: id and (integer & primary key), and name (a string). I'm trying to avoid declaring them in every class like so: class C1(declarative_base()): id = Column...
SQLAlchemy: avoiding repetition in declarative style class definition
I'm using SQLAlchemy, and many classes in my object model have the same two attributes: id and (integer & primary key), and name (a string). I'm trying to avoid declaring them in every class like so: class C1(declarative_base()): id = Column(Integer, primary_key = True) name = Column(String) #... class C2(...
[ "You could factor out your common attributes into a mixin class, and multiply inherit it alongside declarative_base():\nfrom sqlalchemy import Column, Integer, String\nfrom sqlalchemy.ext.declarative import declarative_base\n\nclass IdNameMixin(object):\n id = Column(Integer, primary_key=True)\n name = Column...
[ 14, 2, 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003626787_python_sqlalchemy.txt
Q: Automatic correction of python sphinx line length Usually, best practices related to sphinx says that you must limit the line length to less than 80 characters. So I want a way to automatically limit my line length to less than 80 characters (with no hyphens) and when the correction happens, it has to put the corr...
Automatic correction of python sphinx line length
Usually, best practices related to sphinx says that you must limit the line length to less than 80 characters. So I want a way to automatically limit my line length to less than 80 characters (with no hyphens) and when the correction happens, it has to put the correct indent (if possible). The only function I've seen w...
[ "\nA descent editor is what you need.\nIn vim for example this is handled by doing:\n:set textwidth=80\n\nThen all you have to do is start typing and vim will continue on the nextline.\nMarking text and doing a gq reformats the selection according to the setting of the \"textwidth\" variable.\nEx. \nIn those days s...
[ 2 ]
[]
[]
[ "python", "python_sphinx" ]
stackoverflow_0006116329_python_python_sphinx.txt
Q: Extending the Python interactive shell I'd like to extend the Python interactive shell to allow execution of non-python specific statements or commands. The idea being, if you type something on the prompt that would raise a NameError what you typed could be parsed for known external commands, and only it failing t...
Extending the Python interactive shell
I'd like to extend the Python interactive shell to allow execution of non-python specific statements or commands. The idea being, if you type something on the prompt that would raise a NameError what you typed could be parsed for known external commands, and only it failing to find an external command, raise the NameEr...
[ "Have a look at this documentation: http://ipython.scipy.org/doc/manual/html/interactive/tutorial.html \nWhen it becomes using python as a shell replacement, I think are pretty much covered.\n" ]
[ 1 ]
[]
[]
[ "interactive", "interactive_shell", "python", "readline", "shell" ]
stackoverflow_0006116907_interactive_interactive_shell_python_readline_shell.txt
Q: Python list lookup with partial match For the following list: test_list = ['one', 'two','threefour'] How would I find out if an item starts with 'three' or ends with 'four' ? For example, instead of testing membership like this: two in test_list I want to test it like this: startswith('three') in test_list. How w...
Python list lookup with partial match
For the following list: test_list = ['one', 'two','threefour'] How would I find out if an item starts with 'three' or ends with 'four' ? For example, instead of testing membership like this: two in test_list I want to test it like this: startswith('three') in test_list. How would I accomplish this?
[ "You can use any():\nany(s.startswith('three') for s in test_list)\n\n", "You could use one of these:\n>>> [e for e in test_list if e.startswith('three') or e.endswith('four')]\n['threefour']\n>>> any(e for e in test_list if e.startswith('three') or e.endswith('four'))\nTrue\n\n", "http://www.faqs.org/docs/dive...
[ 13, 9, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006117318_python.txt
Q: python constructor basic question I am trying to reuse an opened file which is declared inside the constructor instance of a class but I guess I am doing something logically wrong. For instance consider the following example class Temp: def __init__(self): self.open_file_ = open('periodic_status','r') ...
python constructor basic question
I am trying to reuse an opened file which is declared inside the constructor instance of a class but I guess I am doing something logically wrong. For instance consider the following example class Temp: def __init__(self): self.open_file_ = open('periodic_status','r') def function1(self): new_f...
[ "Because your file handle has exhausted all the lines in the file. You need to rewind it in \"function2\" using:\nf.seek(0)\n\nto start over again\nSee here docs.python.org\n", "Copying the reference does not create a new iterator; the first round of iteration consumes the entire file, leaving none for the second...
[ 3, 2, 1 ]
[]
[]
[ "constructor", "python" ]
stackoverflow_0006117497_constructor_python.txt
Q: Better way to remove a line in a file with python? I want to remove a line in a file; currently I'm creating a new file, copying every line except the one I want to remove, deleting the old file and renaming the new one as the same filename as the old one. Is there a better way to remove a line? f = open('./todo.t...
Better way to remove a line in a file with python?
I want to remove a line in a file; currently I'm creating a new file, copying every line except the one I want to remove, deleting the old file and renaming the new one as the same filename as the old one. Is there a better way to remove a line? f = open('./todo.txt', 'r') newF = open('./todo-run.txt', 'a') lines = f.r...
[ "A solution in sed, which you might call using \"subprocess\". Ex, to delete line 18 do:\nsed -i '18 d' filename\n\n", "Better in what way? You could, for instance, shuffle the data within the file then truncate it, using less memory but more seeking (particularly if you adapt it to not read the latter part in on...
[ 2, 1, 0, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0006117155_file_io_python.txt
Q: Looking for python module to help "neaten" up a server console window I'm looking for a Python module/framework/package that will assist me in making a sort of "better" console for my application. As it stands now, STDIN can be "pushed" to new lines by other messages being logged out to the console, therefore maki...
Looking for python module to help "neaten" up a server console window
I'm looking for a Python module/framework/package that will assist me in making a sort of "better" console for my application. As it stands now, STDIN can be "pushed" to new lines by other messages being logged out to the console, therefore making it difficult to read what you are trying to type into a server console i...
[ "readline module helps to build a nice prompt with history and auto-completion:\nhttp://docs.python.org/library/readline.html\ncurses module allows you to separate the console into windows that can be separately scrolled:\nhttp://docs.python.org/library/curses.html\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0006117499_python.txt
Q: Letting the User Assign List Names I am trying to write a program that will keep track of a student's grades in all of his courses. The student adds the course and also adds the different segments of the course and how they are weighted, which is why I was planning on using a dictionary. I've been using an input ...
Letting the User Assign List Names
I am trying to write a program that will keep track of a student's grades in all of his courses. The student adds the course and also adds the different segments of the course and how they are weighted, which is why I was planning on using a dictionary. I've been using an input function to allow the user to enter the ...
[ "Data structures can be nested.\n{'mylist': [], 'awesomedict': {}}\n\n" ]
[ 3 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0006117737_dictionary_list_python.txt
Q: Negation in Python I'm trying to create a directory if the path doesn't exist, but the ! (not) operator doesn't work. I'm not sure how to negate in Python... What's the correct way to do this? if (!os.path.exists("/usr/share/sounds/blues")): proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"]) ...
Negation in Python
I'm trying to create a directory if the path doesn't exist, but the ! (not) operator doesn't work. I'm not sure how to negate in Python... What's the correct way to do this? if (!os.path.exists("/usr/share/sounds/blues")): proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"]) proc.wait()
[ "The negation operator in Python is not. Therefore just replace your ! with not.\nFor your example, do this:\nif not os.path.exists(\"/usr/share/sounds/blues\") :\n proc = subprocess.Popen([\"mkdir\", \"/usr/share/sounds/blues\"])\n proc.wait()\n\n\nFor your specific example (as Neil said in the comments), yo...
[ 283, 38, 15, 3 ]
[]
[]
[ "negation", "python" ]
stackoverflow_0006117733_negation_python.txt
Q: INSERT INTO and String Concatenation with Python I have hit a major speed bump in inserting data in to my DB. You can see from the code below that I am simply building the SQL statement to pass in to the execute command. The values are correct and all is well there but the python interpreter seems to be adding and...
INSERT INTO and String Concatenation with Python
I have hit a major speed bump in inserting data in to my DB. You can see from the code below that I am simply building the SQL statement to pass in to the execute command. The values are correct and all is well there but the python interpreter seems to be adding and removing quotes from the params at runtime. This is ...
[ "You are passing the string ST_GeomFromText('POINT(..)') as a parameter, and psycopg2 is escaping it. However ST_GeomFromText(..) is a PostGIS function, not data you are inserting.\nTo fix this you need to move the ST_GeomFromText function into the static SQL. For example:\nsql = '''\n INSERT INTO foo (point_ge...
[ 18, 0 ]
[]
[]
[ "postgis", "psycopg2", "python" ]
stackoverflow_0006117646_postgis_psycopg2_python.txt
Q: JSON-RPC server via Python I need to implement a JSON-RPC server like this: http://pasha.cdemo.applicationcraft.com/service/json This server will be accessed from jQuery and I have to use Python for writing it. What library should I use? Can you also give me an example of using that library? Thanks. A: I found c...
JSON-RPC server via Python
I need to implement a JSON-RPC server like this: http://pasha.cdemo.applicationcraft.com/service/json This server will be accessed from jQuery and I have to use Python for writing it. What library should I use? Can you also give me an example of using that library? Thanks.
[ "I found cherrypy very easy to use (doesn't come with a predefined template engine or a database model, so it's IMO better than others when your server is producing json and is not a typical database).\nCoupled with nginx and memcached can also be quite performant...\n", "Python 2.6 comes with json module in the ...
[ 2, 0 ]
[]
[]
[ "json_rpc", "python" ]
stackoverflow_0005909699_json_rpc_python.txt
Q: What does this Python one-liner mean? s=p=1;exec"if s%p*s%~-~p:print`p`+','+`p+2`\ns*=p*p;p+=2\n"*999 Source. A: Here is an unraveling of the basic idea. # p = 1; s = p s=p=1 #exec"if s%p*s%~-~p:print`p`+','+`p+2`\ns*=p*p;p+=2\n"*999 for i in range(999): # s%p = remainder of s/p # ~p = 1s complement of ...
What does this Python one-liner mean?
s=p=1;exec"if s%p*s%~-~p:print`p`+','+`p+2`\ns*=p*p;p+=2\n"*999 Source.
[ "Here is an unraveling of the basic idea.\n# p = 1; s = p\ns=p=1\n#exec\"if s%p*s%~-~p:print`p`+','+`p+2`\\ns*=p*p;p+=2\\n\"*999\nfor i in range(999):\n # s%p = remainder of s/p\n # ~p = 1s complement of p\n if s%p*s%~-~p:\n # `p` = repr(p)\n print`p`+','+`p+2`\n # s = s*p*p\n s*=p*p\n ...
[ 12, 7, 3 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0004529452_python_syntax.txt
Q: Python how to read multiple inputs in a same line I want to know how can we read multiple input like ["a","b","c"] and store it in same variable. I want to store a , b ,c as a separate input to a variable. thanx A: How about this: a, b, c = ["a", "b", "c"] That assigns three new variables. If you want to opera...
Python how to read multiple inputs in a same line
I want to know how can we read multiple input like ["a","b","c"] and store it in same variable. I want to store a , b ,c as a separate input to a variable. thanx
[ "How about this:\na, b, c = [\"a\", \"b\", \"c\"]\n\nThat assigns three new variables. If you want to operate on each in turn, use this instead:\nfor character in ['a', 'b', 'c']:\n print character # prints 'a', then 'b', then 'c'.\n\n", "You can unpack iterables:\na, b, c = ['a', 'b', 'c']\n\n", "If you are ...
[ 4, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006117840_python.txt
Q: YUV subsampling chroma channels in python When halving chroma channels width and/or height, what's the correct way to subsamble? To take one chroma pixel for each 2x2 luma pixel, when sampling from a full-resolution chroma source, which chroma pixel do we take - top left? Average of all 4? Doesn't matter? This ...
YUV subsampling chroma channels in python
When halving chroma channels width and/or height, what's the correct way to subsamble? To take one chroma pixel for each 2x2 luma pixel, when sampling from a full-resolution chroma source, which chroma pixel do we take - top left? Average of all 4? Doesn't matter? This is my current code if field == 'top': i = 0...
[ "Ideally you would interpolate the data to produce the best possible image, however I think that your question is best answered with a quick overview of WHERE the luma and chroma samples are located (imagine a camera with one grid for luma and the other for chroma). For subsampling there are multiple standards for ...
[ 4, 2 ]
[]
[]
[ "python", "yuv" ]
stackoverflow_0005972698_python_yuv.txt
Q: How to make __name__ == '__main__' when running module More specifically, I have a file file file1.py: if __name__ == '__main__': a = 1 and from file file2.py, I want to do something like import file1 print file1.a without modifying file1.py A: import imp m = imp.find_module('file1') file1 = imp.load_modul...
How to make __name__ == '__main__' when running module
More specifically, I have a file file file1.py: if __name__ == '__main__': a = 1 and from file file2.py, I want to do something like import file1 print file1.a without modifying file1.py
[ "import imp\nm = imp.find_module('file1')\nfile1 = imp.load_module('__main__', *m)\n\nThat being said, you should really think about modifying file1.py instead of using this hack.\n", "from runpy import run_module\ndata = run_module(\"file1\", run_name=\"__main__\")\nprint data[\"a\"]\n\nYou don't need to mess wi...
[ 4, 4, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006114251_python.txt
Q: Twisted: Making code non-blocking I'm a bit puzzled about how to write asynchronous code in python/twisted. Suppose (for arguments sake) I am exposing a function to the world that will take a number and return True/False if it is prime/non-prime, so it looks vaguely like this: def IsPrime(numberin): for n in...
Twisted: Making code non-blocking
I'm a bit puzzled about how to write asynchronous code in python/twisted. Suppose (for arguments sake) I am exposing a function to the world that will take a number and return True/False if it is prime/non-prime, so it looks vaguely like this: def IsPrime(numberin): for n in range(2,numberin): if numberin...
[ "I think your current understanding is basically correct. Twisted is just a Python library and the Python code you write to use it executes normally as you would expect Python code to: if you have only a single thread (and a single process), then only one thing happens at a time. Almost no APIs provided by Twiste...
[ 27 ]
[]
[]
[ "asynchronous", "blocking", "python", "twisted" ]
stackoverflow_0006117587_asynchronous_blocking_python_twisted.txt
Q: Fuzzy matching a string within a large body of text in Python (url) I have a list of company names, and I have a list of url's mentioning company names. The end goal is to look into the url, and find out how many of the companies on the url are in my list. Example URL: http://www.dmx.com/about/our-clients Each UR...
Fuzzy matching a string within a large body of text in Python (url)
I have a list of company names, and I have a list of url's mentioning company names. The end goal is to look into the url, and find out how many of the companies on the url are in my list. Example URL: http://www.dmx.com/about/our-clients Each URL will be structured differently, so I don't have a good way to do a rege...
[ "It doesn't sound to me like you need any \"fuzzy\" matching. And I'm assuming that when you say \"url\" you mean \"webpage at the address pointed to by the url.\" Just use Python's built-in substring search functionality:\n>>> import urllib2\n>>> webpage = urllib2.urlopen('http://www.dmx.com/about/our-clients')\n>...
[ 5, 3 ]
[]
[]
[ "algorithm", "fuzzy_comparison", "python" ]
stackoverflow_0006118418_algorithm_fuzzy_comparison_python.txt
Q: Generating html table from list in python I currently have a list of data: list = [('ALCOA INC. CDI', 66.0), ('RIO TINTO LIMITED', 29.210000000000001), ('PLACER DOME INC CDI', 18.030000000000001), ('GUNNS LIMITED', 11.609999999999999), ('ORICA LIMITED', 10.83)] that's what's generated from my code, and I wa...
Generating html table from list in python
I currently have a list of data: list = [('ALCOA INC. CDI', 66.0), ('RIO TINTO LIMITED', 29.210000000000001), ('PLACER DOME INC CDI', 18.030000000000001), ('GUNNS LIMITED', 11.609999999999999), ('ORICA LIMITED', 10.83)] that's what's generated from my code, and I want to place it into a html table, currently I c...
[ "You can't concatenate string and float types, you need to cast the float to a string:\nprint ' <td>'+str(i[1])+'</td>'\nhttp://ideone.com/I0LJV\n", "or\nprint ' <td>%.2f</td>' % i[1]\n\nif you want to print integer part plus 2 decimals\nhttp://docs.python.org/library/stdtypes.html#string-formatting...
[ 2, 2 ]
[]
[]
[ "html", "html_lists", "html_table", "python" ]
stackoverflow_0006118566_html_html_lists_html_table_python.txt
Q: using ossaudiodev for playback I'm trying to write a streaming audio client and I'd like to use ossaudiodev functions to help me play back the audio on my local machine. Unfortunately, I'm getting an exception every time I try to run my code: Unhandled exception in thread started by <function audioplayer at 0x88e9...
using ossaudiodev for playback
I'm trying to write a streaming audio client and I'd like to use ossaudiodev functions to help me play back the audio on my local machine. Unfortunately, I'm getting an exception every time I try to run my code: Unhandled exception in thread started by <function audioplayer at 0x88e96f4> Traceback (most recent call las...
[ "Even on systems where it's available, the OSS interface is usually just a facade over ALSA. Consider using a library that supports multiple interfaces, such as pyao.\n", "your desktop manager is already using your soundcard, you may have more luck with dmix plugin for alsa, but it's often difficult\nsoundblaster...
[ 0, 0 ]
[]
[]
[ "audio", "audio_streaming", "python" ]
stackoverflow_0006118279_audio_audio_streaming_python.txt
Q: Boost::Python- possible to automatically convert from dict --> std::map? I've got a C++ class, with a member function that can take a small-to-large number of parameters. Lets name those parameters, a-f. All parameters have default values. As a part of the python project I am working on, I want to expose this c...
Boost::Python- possible to automatically convert from dict --> std::map?
I've got a C++ class, with a member function that can take a small-to-large number of parameters. Lets name those parameters, a-f. All parameters have default values. As a part of the python project I am working on, I want to expose this class to python. Currently, the member function looks something like this: cla...
[ "I think there's a couple of ways that are easier to accomplish than writing your own converter. You can use boost::python's map_indexing_suite to do the conversion for you, or you can use keyword arguments in python. I personally prefer keyword arguments, as this is the more \"Pythonic\" way to do this.\nSo this...
[ 25, 9, 0 ]
[]
[]
[ "boost", "boost_python", "c++", "python", "type_conversion" ]
stackoverflow_0006116345_boost_boost_python_c++_python_type_conversion.txt
Q: submitting a django form using javascript ok so have this snippet of code - <form id="myform" name="myform" action="." method="post"> <a href="javascript: document.forms['myform'].submit();" name="myform">Submit </a> </form> i am submitting a form using an href and some javascript to ...
submitting a django form using javascript
ok so have this snippet of code - <form id="myform" name="myform" action="." method="post"> <a href="javascript: document.forms['myform'].submit();" name="myform">Submit </a> </form> i am submitting a form using an href and some javascript to my django server. on the server i check the pos...
[ "here is the solution i used to solve my problem - (thank you very much fosco and adam!)\n <form id=\"my_form\" action=\".\" method=\"post\">\n <a href=\"#\" onclick=\"document.forms['my_form'].submit();\">Call Form</a>\n <input type=\"checkbox\" name=\"call_form\" checked style=\"visibility:hidden...
[ 3, 1, 0 ]
[]
[]
[ "djangoappengine", "forms", "html", "javascript", "python" ]
stackoverflow_0006113292_djangoappengine_forms_html_javascript_python.txt
Q: Why exactly is this error occurring when the loop executes to completion and how do I stop it? Code: http://pastie.org/1966795 Trackback: http://pastie.org/1966799 TXT File I'm using: http://pastie.org/1966800 Keep in mind the program runs, my only issue is that it displays an error message at the end (see: trackb...
Why exactly is this error occurring when the loop executes to completion and how do I stop it?
Code: http://pastie.org/1966795 Trackback: http://pastie.org/1966799 TXT File I'm using: http://pastie.org/1966800 Keep in mind the program runs, my only issue is that it displays an error message at the end (see: trackback), that I don't know how to fix.
[ "The problem happens when print_et_list is executing for the fourth time. By then you're past the end of your input file, so readline keeps returning empty strings. You should return from print_et_list early if question is blank, and correctly handle this case in main.\n", "This is the piece of code that fixed it...
[ 2, 0 ]
[]
[]
[ "debugging", "python" ]
stackoverflow_0006113350_debugging_python.txt
Q: Dynamically add member function to an instance of a class in Python When I do the following: class C: pass def f( self ): print self a = C() a.f = f a.f() I get the following error at the line a.f(): TypeError: f() takes exactly 1 argument (0 given) The problem appears to be that when f is added to the inst...
Dynamically add member function to an instance of a class in Python
When I do the following: class C: pass def f( self ): print self a = C() a.f = f a.f() I get the following error at the line a.f(): TypeError: f() takes exactly 1 argument (0 given) The problem appears to be that when f is added to the instance, a, it is treated like a function that is stored inside of a, rather...
[ "For Python 2.X you can use:\nimport types\nclass C:\n pass\n\ndef f(self):\n print self\n\na = C()\na.f = types.MethodType(f,a)\na.f()\n\nFor Python 3.X:\nimport types\nclass C(object):\n pass\n\ndef f(self):\n print(self)\n\na = C()\na.f = types.MethodType(f,a)\na.f()\n\n", "You should put f in the ...
[ 24, 5 ]
[]
[]
[ "python" ]
stackoverflow_0006118592_python.txt
Q: Inclusion of external documentation into a Sphinx project We maintain a fairly large documentation using Sphinx in SVN. As part of the generated output we would like to include the release notes of related Python modules as primary content (not as hyperlink!). The release notes of the external modules are also mai...
Inclusion of external documentation into a Sphinx project
We maintain a fairly large documentation using Sphinx in SVN. As part of the generated output we would like to include the release notes of related Python modules as primary content (not as hyperlink!). The release notes of the external modules are also maintained in SVN. Is there some Sphinx-ish way to pull in the par...
[ "The two options I can think of are:\n\nAdd an svn:externals link to the remote project (which you already know about).\nExtend Sphinx with a custom directive to include files from remote subversion repositories.\n\nI'm no expert on Sphinx internals but was able to cobble together a quick extension which embeds fil...
[ 8 ]
[]
[]
[ "python", "python_sphinx" ]
stackoverflow_0006068296_python_python_sphinx.txt
Q: How to write a bash script that enters text into programs I'm writing a bash script that fires up python and then enters some simple commands before exiting. I've got it firing up python ok, but how do I make the script simulate keyboard input in the python shell, as though a person were doing it? A: Use a "here...
How to write a bash script that enters text into programs
I'm writing a bash script that fires up python and then enters some simple commands before exiting. I've got it firing up python ok, but how do I make the script simulate keyboard input in the python shell, as though a person were doing it?
[ "Use a \"here\" document. It looks like this\ncommand << HERE\ntext that someone types in\nmore text\nHERE\n\nYou don'th have to use \"HERE\", you can use something that has a little more\nmeaning relative to the context of your code.\n", "If you really need to simulate typing into the Python interpreter, rather ...
[ 5, 4, 2, 1 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0006119038_bash_python.txt
Q: SVN: Python Pre-commit script always fails I have found an example python script and have modified it to do checks for comments in pre-commit. My problem is that the text of the comment as parsed by python always ends up blank. Env: Windows XP SVN version: svn, version 1.5.6 (r36142) compiled Mar 6 2009, 14:54:...
SVN: Python Pre-commit script always fails
I have found an example python script and have modified it to do checks for comments in pre-commit. My problem is that the text of the comment as parsed by python always ends up blank. Env: Windows XP SVN version: svn, version 1.5.6 (r36142) compiled Mar 6 2009, 14:54:47 Python 2.7 pre-commit.bat C:\Python27\python...
[ "When you run it through Python, the error code which is set by Python is ignored in the batch file; you will want to do it something like this:\nC:\\Python27\\python %1\\hooks\\pre-commit.py %1 %2\nexit %ERRORLEVEL%\n\nIt's a good idea to quote your vaules, as well, to make sure that they get through to Python int...
[ 3 ]
[]
[]
[ "python", "svn", "svn_hooks" ]
stackoverflow_0006118739_python_svn_svn_hooks.txt
Q: Help me decide what to use with Google App Engine for this practical work I'm working on a practical work for college, and I have to develop a web-app that could be used by all the teachers from my province. The application should let the users (teachers) manage some information related to their daily duties. One...
Help me decide what to use with Google App Engine for this practical work
I'm working on a practical work for college, and I have to develop a web-app that could be used by all the teachers from my province. The application should let the users (teachers) manage some information related to their daily duties. One of the requirements is that I must use Google App Engine platform for develop...
[ "I would recommend using Python + Django framework. I love Java, but for the Google App Engine there is much more documentation online for Python.\n", "I would recommend taking a look at Java + slim3. I have my own MVC framework for AppEngine (PhD thesis work), and I really wish I had started after slim3 came out...
[ 4, 0, 0 ]
[]
[]
[ "google_app_engine", "java", "python" ]
stackoverflow_0006116236_google_app_engine_java_python.txt
Q: unraring/unzipping a file using python+django I'm trying to write a distributable web app that will allow the user to upload a compressed archive (rar or zip), extract it on the server side, then do something else with the files. Is there a default library I can hook into to do this? Or is there a way to package a...
unraring/unzipping a file using python+django
I'm trying to write a distributable web app that will allow the user to upload a compressed archive (rar or zip), extract it on the server side, then do something else with the files. Is there a default library I can hook into to do this? Or is there a way to package an external library with the web app so the end user...
[ "Zip is easy. Rar, not so much.\n" ]
[ 4 ]
[]
[]
[ "archive", "compression", "django", "python", "rar" ]
stackoverflow_0006119214_archive_compression_django_python_rar.txt
Q: python GUI to build a simple typing tutor game I've never created a GUI before, just simple text based stuff. I think I'm ready to move on to building a GUI and I have a project in mind. Specifically, I'm thinking about creating a simple touch typing tutor game...nothing too fancy. Which python GUI toolkit and ...
python GUI to build a simple typing tutor game
I've never created a GUI before, just simple text based stuff. I think I'm ready to move on to building a GUI and I have a project in mind. Specifically, I'm thinking about creating a simple touch typing tutor game...nothing too fancy. Which python GUI toolkit and builder would lend itself best to a project like thi...
[ "You can use Pygame modul\nPygame site has a lot of tutorials, you can use those tutorials as a starting point.\nGood Luck!\n", "I wrote several application prototypes using the libglade library and the python bindings.\nI found the toolkit pretty easy to use, it acted just like any other GUI widget framework I'v...
[ 1, 0 ]
[]
[]
[ "python", "user_interface" ]
stackoverflow_0006119508_python_user_interface.txt
Q: Negative Lookahead Regex greed (why is .*? too greedy) I'm having trouble understanding the finer details of negative lookahead regular expressions. After reading Regex lookahead, lookbehind and atomic groups, I thought I had a good summary of negative lookaheads when I found this description: (?!REGEX_1)REGEX_2...
Negative Lookahead Regex greed (why is .*? too greedy)
I'm having trouble understanding the finer details of negative lookahead regular expressions. After reading Regex lookahead, lookbehind and atomic groups, I thought I had a good summary of negative lookaheads when I found this description: (?!REGEX_1)REGEX_2 Match only if REGEX_1 does not match; after checking REGEX_...
[ "#!/usr/bin/perl\n\nsub test_re {\n $arg = $_[0];\n $INSULTSTR = $_[1];\n $INSULTSTR =~ /(?:^|\\.\\s*)(?:(?![^.]*?$arg[^.]*\\.))([^.]*\\.)/;\n if ($1) {\n print \"neg-lookahead($arg) MATCHED: '$1'\\n\";\n } else {\n print \"Unable to match: neg-lookahead($arg) in '$INSULTSTR'\\n\";\n...
[ 3, 3, 2 ]
[]
[]
[ "perl", "python", "regex", "regex_lookarounds" ]
stackoverflow_0006119133_perl_python_regex_regex_lookarounds.txt
Q: Naming Lists Using User Input I would like to let the user define the name of a list to be used in the code, so I have been using an input function. I want the user's response to the input function to become the name of the list. I tried the following: a = input("What would you like the name of the list to be? ") ...
Naming Lists Using User Input
I would like to let the user define the name of a list to be used in the code, so I have been using an input function. I want the user's response to the input function to become the name of the list. I tried the following: a = input("What would you like the name of the list to be? ") a = [] However, this named the lis...
[ "The correct way to accomplish what you want here is a dict of lists:\n>>> lists = {}\n>>> lists['homework'] = [40, 60, 70]\n>>> lists['tests'] = [35, 99, 20]\n>>> lists\n{'tests': [35, 99, 20], 'homework': [40, 60, 70]}\n>>> \n\nWhen you can ask for input, the input function (raw_input in Python 2.x) returns a str...
[ 6, 0 ]
[]
[]
[ "input", "list", "python" ]
stackoverflow_0006119790_input_list_python.txt
Q: How can I access a function from FORTRAN which is writen in Python? Is there any way to use a python function in FORTRAN? I was given a python script that contains some functions and I need to access this function from a FORTRAN code. I've seen 'f2py' which allows a FORTRAN subroutine to be accessed from Python, ...
How can I access a function from FORTRAN which is writen in Python?
Is there any way to use a python function in FORTRAN? I was given a python script that contains some functions and I need to access this function from a FORTRAN code. I've seen 'f2py' which allows a FORTRAN subroutine to be accessed from Python, and py2exe which will compile python script to an executable. Is there an...
[ "Don't waste a lot of time compiling and translating. Do this.\n\nFortran Part 1 program writes a file of stuff for Python to do. Write to stdout. Call this F1\nPython reads a file, does the Python calculation, write the responses to a file for Fortran. Call this P.\nFortran Part 2 program reads a file of stuff...
[ 6, 4 ]
[]
[]
[ "compilation", "fortran", "object", "python" ]
stackoverflow_0002357227_compilation_fortran_object_python.txt
Q: How do I dynamically get a list of all PythonCard components in a GUI class? Here is a sample resource file for PythonCard: { 'application':{ 'type':'Application', 'name':'Test Sounds', 'backgrounds': [ { 'type':'Background', 'name':'Test Sounds', 'title':'Test Sounds', 'position':...
How do I dynamically get a list of all PythonCard components in a GUI class?
Here is a sample resource file for PythonCard: { 'application':{ 'type':'Application', 'name':'Test Sounds', 'backgrounds': [ { 'type':'Background', 'name':'Test Sounds', 'title':'Test Sounds', 'position':( 5, 5 ), 'size':( 300, 200 ), 'components': [ { 'type':'TextField...
[ "It would be much cleaner if you were able to get the list of components from elsewhere, but I think it should work if you do something like:\nfor comp_name in dir(self.components):\n if comp_name.startswith('_'): # ignore special members like __repr__\n continue\n component = getattr(self.component...
[ 0 ]
[]
[]
[ "python", "pythoncard", "user_interface", "wxpython" ]
stackoverflow_0003687561_python_pythoncard_user_interface_wxpython.txt
Q: Convert text in different languages to date I've got 3 variables which are dates, but they are string and are in different languages(polish, romananian and bulgarian). For example: 18 grudnia 1969 18 decembrie 1969 18 декември 1969 I want convert them to date but I don't know if I must write some enum with months...
Convert text in different languages to date
I've got 3 variables which are dates, but they are string and are in different languages(polish, romananian and bulgarian). For example: 18 grudnia 1969 18 decembrie 1969 18 декември 1969 I want convert them to date but I don't know if I must write some enum with months in different languages or python(3.2) offers som...
[ "If you can use Babel, then I may have a possible solution for you. See this gist. It uses your exact example.\n" ]
[ 1 ]
[]
[]
[ "date", "python" ]
stackoverflow_0006107505_date_python.txt
Q: How to send data to base.html in django? I'm looking for a way to abstract a navigation bar in django and include it in base.html; directly or through a template inclusion. The part where I'm totally lost is, how to append data to the context so the nav bar can get its contents from database. I'd like to query the...
How to send data to base.html in django?
I'm looking for a way to abstract a navigation bar in django and include it in base.html; directly or through a template inclusion. The part where I'm totally lost is, how to append data to the context so the nav bar can get its contents from database. I'd like to query the data in views.py and make it available for th...
[ "No you wouldn't. Write a custom template tag instead.\n<html>\n ...\n<div class=\"navbar\">{% navbar %}</div>\n ...\n</html>\n\n", "If you need to add information that needs to be available to all templates including base.html you should look at the context_processor.py. This can add information to the context s...
[ 7, 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006119869_django_python.txt
Q: Django model form save (multi database) question another noob Django question. The below both work for me, is there any difference or anything I should be aware of ? I'm using Django 1.2.5. Thanks. o = Staff() form = StaffForm(request.POST, instance=o) if form.is_valid(): o.save(using='dbName') o = Staff() for...
Django model form save (multi database) question
another noob Django question. The below both work for me, is there any difference or anything I should be aware of ? I'm using Django 1.2.5. Thanks. o = Staff() form = StaffForm(request.POST, instance=o) if form.is_valid(): o.save(using='dbName') o = Staff() form = StaffForm(request.POST, instance=o) if form.is_v...
[ "The first example does not work - it doesn't update the instance from the form. Use the second. \n" ]
[ 1 ]
[]
[]
[ "django", "modelform", "python" ]
stackoverflow_0006118884_django_modelform_python.txt
Q: Python Soap Server for the Quickbooks Webconnector I'm writing a Soap Server to interact with the quickbooks webconnector, and I really don't even know where to start. I have the wsdl file, and a list of all the functions and arguments that the web connector needs, but I really just don't know where to start. I co...
Python Soap Server for the Quickbooks Webconnector
I'm writing a Soap Server to interact with the quickbooks webconnector, and I really don't even know where to start. I have the wsdl file, and a list of all the functions and arguments that the web connector needs, but I really just don't know where to start. I couldn't find any real documentation on this for python, t...
[ "Well ids their some one who had hands on this cause i also try same thind with SOAPpy and proxy wsdl services but no result on this \nSample Code :\nfrom SOAPpy import WSDL \nurl='http://developer.intuit.com/uploadedFiles/Support/QBWebConnectorSvc.wsdl' \nproxy = WSDL.Proxy(url)\nprint 'Available methods:'\n...
[ 0 ]
[]
[]
[ "python", "quickbooks", "soap", "soapserver" ]
stackoverflow_0005423928_python_quickbooks_soap_soapserver.txt
Q: How to use advance mysql query in Pyramid framework Now, I'm thinking about to change pyramid from PHP. I'm using advance sql query for searching Current mysql is using SELECT * , IF( `Word` = 'sim', 1, IF( `Word` LIKE 'sim%', 2, IF( `Word` LIKE '%sim', 4, 3 ) ) ) AS `sort` FROM `dblist` WHERE `Word` LIKE '%sim%' ...
How to use advance mysql query in Pyramid framework
Now, I'm thinking about to change pyramid from PHP. I'm using advance sql query for searching Current mysql is using SELECT * , IF( `Word` = 'sim', 1, IF( `Word` LIKE 'sim%', 2, IF( `Word` LIKE '%sim', 4, 3 ) ) ) AS `sort` FROM `dblist` WHERE `Word` LIKE '%sim%' ORDER BY `sort` , `Word`; When I read pyramid, there is ...
[ "See the SQLAlchemy + URL Dispatch Wiki Tutorial for an example how to use SQLAlchemy with Pyramid: http://docs.pylonsproject.org/projects/pyramid/1.0/tutorials/wiki2/index.html\n", "Your claim is wrong!\nPyramid has no concept of backend storage and is open to every possible backend storage.\nThere are add-ons s...
[ 2, 0 ]
[]
[]
[ "pyramid", "python", "sqlalchemy" ]
stackoverflow_0006120539_pyramid_python_sqlalchemy.txt
Q: How to save an Image using URL in python/django If you were to save an Image using it's URL how would you do it ? Also how do I give the Image a unique file name while saving it. response = urllib.urlopen(image_url) file_name = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(...
How to save an Image using URL in python/django
If you were to save an Image using it's URL how would you do it ? Also how do I give the Image a unique file name while saving it. response = urllib.urlopen(image_url) file_name = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(10)) f = open('/media/images/temp/'+file_name, "w...
[ "import urllib\nimport string\nimport random\nimport os\n\nfilename_charset = string.ascii_letters + string.digits\nfilename_length = 10\nfile_save_dir = '/home/user/download/'\n\nfilename = ''.join(random.choice(filename_charset)\n for s in range(filename_length))\n\nurllib.urlretrieve (\"http://...
[ 5 ]
[]
[]
[ "django", "file_io", "python" ]
stackoverflow_0006121200_django_file_io_python.txt
Q: How to get information from facebook using python? I've looked at a lot of questions and libs and didn't found exactly what I wanted. Here's the thing, I'm developing an application in python for a user to get all sorts of things from social networks accounts. I'm having trouble with facebook. I would like, if pos...
How to get information from facebook using python?
I've looked at a lot of questions and libs and didn't found exactly what I wanted. Here's the thing, I'm developing an application in python for a user to get all sorts of things from social networks accounts. I'm having trouble with facebook. I would like, if possible, a step-by-step tutorial on the code and libs to u...
[ "I strongly encourage you to use Facebook's own APIs.\nFirst of all, check out documentation on Facebook's Graph API https://developers.facebook.com/docs/reference/api/. If you are not familiar with JSON, DO read a tutorial on it (for instance http://secretgeek.net/json_3mins.asp).\nOnce you grasp the concepts, sta...
[ 3, 1 ]
[]
[]
[ "api", "facebook", "python" ]
stackoverflow_0006117671_api_facebook_python.txt
Q: Problem with search operation I am have two lists: a= [['A', 'B', 'C', 3], ['P', 'Q', 'R', 4]] b=[['K',1,1,1,1,1], ['L',1,1,1,1,1], ['M', 1,1,0,1,1], ['J', 0,0,0,0,0], ['A', 0,0,0,1,1], ['P',0,1,0,1,1 ]] I want the output like: Output=[['A', 0,0,0,1,1], ['P',0,1,0,1,1 ]] I am trying to search the a in b using t...
Problem with search operation
I am have two lists: a= [['A', 'B', 'C', 3], ['P', 'Q', 'R', 4]] b=[['K',1,1,1,1,1], ['L',1,1,1,1,1], ['M', 1,1,0,1,1], ['J', 0,0,0,0,0], ['A', 0,0,0,1,1], ['P',0,1,0,1,1 ]] I want the output like: Output=[['A', 0,0,0,1,1], ['P',0,1,0,1,1 ]] I am trying to search the a in b using the a[idx][0]. Then I want to collec...
[ "First, convert b to a dictionary:\nb=[['K',1,1,1,1,1], ['L',1,1,1,1,1], ['M', 1,1,0,1,1], ['J', 0,0,0,0,0], ['A', 0,0,0,1,1], ['P',0,1,0,1,1 ]\n\nd = dict((i[0], i[1:]) for i in b)\n\n# d is now:\n{'A': [0, 0, 0, 1, 1],\n 'J': [0, 0, 0, 0, 0],\n 'K': [1, 1, 1, 1, 1],\n 'L': [1, 1, 1, 1, 1],\n 'M': [1, 1, 0, 1, 1],...
[ 9, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006121431_python.txt
Q: Interprocess messaging between two Python programs We have two Python programs running on two linux servers. Now we want to send messages between these Python programs. The best idea so far is to create a TCP/IP server and client architecture, but this seems like a very complicate way to do it. Is this really best...
Interprocess messaging between two Python programs
We have two Python programs running on two linux servers. Now we want to send messages between these Python programs. The best idea so far is to create a TCP/IP server and client architecture, but this seems like a very complicate way to do it. Is this really best practice for doing such a thing?
[ "I like zeromq for simple messaging, it's really lightweight and fast...very flexible as well. Using AMQP messaging isn't a bad idea either depending on the specifics of your situation, I've found kombu to be a very nice pythonic library for that. You could also use xmlrpclib or setup a simple REST API with bottle ...
[ 6, 3, 0 ]
[]
[]
[ "linux", "python", "python_3.x" ]
stackoverflow_0006121180_linux_python_python_3.x.txt
Q: Python and SOAP What is the best library that can be used to create a SOAP Server - Client with Python or implement client that can talk to SOAP Server ??? A: As for a SOAP client, my personal favourite is SUDS https://fedorahosted.org/suds/. It is very Pythonic and easy to use. Also you don't need to generate a...
Python and SOAP
What is the best library that can be used to create a SOAP Server - Client with Python or implement client that can talk to SOAP Server ???
[ "As for a SOAP client, my personal favourite is SUDS https://fedorahosted.org/suds/. It is very Pythonic and easy to use. Also you don't need to generate any code making it very useful for testing.\nA simple example from its documentation (https://fedorahosted.org/suds/wiki/Documentation):\nfrom suds.client import ...
[ 11 ]
[]
[]
[ "python", "soap" ]
stackoverflow_0006121633_python_soap.txt
Q: How to pipe the content of a variable through two chained pipes in python? I have successfully managed to pipe a variable to a command which is not piped further, in this way: from subprocess import Popen, PIPE def exec_command(command, some_input): proc = Popen(command, stdout=PIPE, stderr=PIPE, stdin=PIPE) ...
How to pipe the content of a variable through two chained pipes in python?
I have successfully managed to pipe a variable to a command which is not piped further, in this way: from subprocess import Popen, PIPE def exec_command(command, some_input): proc = Popen(command, stdout=PIPE, stderr=PIPE, stdin=PIPE) (stdout, stderr) = proc.communicate(input=some_input) ... but when trying t...
[ "One possibility would be to set up the entire command to be executed by a shell (shell=True to among the keyword args of your Popen() call ... and only .communicate() with the ends of the whole pipeline (your input going to command1's stdin, and your stdout/stderr coming from command2's stdout/stderr).\nA more com...
[ 1 ]
[]
[]
[ "pipe", "python", "subprocess" ]
stackoverflow_0006121587_pipe_python_subprocess.txt
Q: Querying in redis Recently I am learning redis and honestly very impressed and dying to use it. One of the things that keep bothering me is "how do I query redis". To be specific I am trying to resolve following Say I have a millions of hashes stored as below usage:1 = {created: 20100521, quantity:9, resource:1033...
Querying in redis
Recently I am learning redis and honestly very impressed and dying to use it. One of the things that keep bothering me is "how do I query redis". To be specific I am trying to resolve following Say I have a millions of hashes stored as below usage:1 = {created: 20100521, quantity:9, resource:1033, user:1842, ...} usage...
[ "For Redis, it's best to understand what sort of query patterns you want over your data before you decide how you're going to store it. \nFor example, if you want to do a date range query over a set of data, you can store that data as a sorted set where the keys are the data items you want to query over, and the sc...
[ 10, 7 ]
[]
[]
[ "nosql", "python", "redis" ]
stackoverflow_0003801777_nosql_python_redis.txt
Q: How to use a variable declared inside a class, outside of this class? I've got this problem with a project that involves programming in Python. I made this class with which a screen pops up and so allowing me to open a xls file. Inside this class the directory to this file is then put into this variable 'filename'...
How to use a variable declared inside a class, outside of this class?
I've got this problem with a project that involves programming in Python. I made this class with which a screen pops up and so allowing me to open a xls file. Inside this class the directory to this file is then put into this variable 'filename'. :> class OpenFile(QtGui.QMainWindow): def __init__(self): super(Ope...
[ "I will not get into details of your code, but will use it only to explain the basic concepts.\nThe variable filename in showDialog is defined as a local variable - hence, you cannot access it outside this function.\nIf you want to define the variable as an instance variable for the class OpenFile, you need to use ...
[ 6, 4 ]
[]
[]
[ "pyqt", "pyqt4", "python" ]
stackoverflow_0006122288_pyqt_pyqt4_python.txt
Q: Django How to use ManyRelatedManager I have 2 apps that are distinct and have no particular reason to talk to each other. This means I don't want to import either name in either app. All the work should be within a glue app. I would like to write a glue app that would join to particular models via a ManyToManyFie...
Django How to use ManyRelatedManager
I have 2 apps that are distinct and have no particular reason to talk to each other. This means I don't want to import either name in either app. All the work should be within a glue app. I would like to write a glue app that would join to particular models via a ManyToManyField like: In app customers, class Customer(...
[ "What if you used ManyToManyField to model pizzas sold inside Customer model?\nclass Customer(models.Model):\n pizzas_bought = models.ManyToManyField(Pizza)\n\nAlso, if you wish to add extra data to your customer -> pizza relations, specify the mapping Class with through parameter:\nclass Customer(models.Model):\...
[ 4 ]
[]
[]
[ "django", "many_to_many", "manyrelatedmanager", "python" ]
stackoverflow_0006121787_django_many_to_many_manyrelatedmanager_python.txt
Q: python.exe was crashed when I run python **.py from windows cmd if I type python in win cmd, it's ok.But when I run python main.py from cmd it crashed. The message is: python.exe has stopped working. Problem signature: Problem Event Name: APPCRASH Application Name: python.exe Application Version: 0.0.0...
python.exe was crashed when I run python **.py from windows cmd
if I type python in win cmd, it's ok.But when I run python main.py from cmd it crashed. The message is: python.exe has stopped working. Problem signature: Problem Event Name: APPCRASH Application Name: python.exe Application Version: 0.0.0.0 Application Timestamp: 4c73f7b6 Fault Module Name: pytho...
[ "Post-mortem: the problem was solved inside question comments (re-installing Python fixed the problem; I suspect the Python installation had somehow gotten corrupted). \n" ]
[ 1 ]
[]
[]
[ "cmd", "crash", "python" ]
stackoverflow_0006121577_cmd_crash_python.txt
Q: python : is decorators for method arguments possible? Is it possible to decorate method arguments? Something like: class SampleEntity (BaseEntity) : def someOperation (self, @Param(type="int", unit="MB")i, str) : pass Basically I want the developer to be able to specify metadata about the class, prope...
python : is decorators for method arguments possible?
Is it possible to decorate method arguments? Something like: class SampleEntity (BaseEntity) : def someOperation (self, @Param(type="int", unit="MB")i, str) : pass Basically I want the developer to be able to specify metadata about the class, properties, methods, arguments etc which I can process later on....
[ "No, but in Python 3 you can use annotations.\ndef func(arg: Param(type = 'int', unit = 'MB')):\n pass\n\nAnnotations can hold any information you want, language doesn't define what should go there. You can access them with func.__annotations__ dict later.\n", "If it's for documentation, you might be able to us...
[ 8, 4, 3, 1, 1 ]
[]
[]
[ "arguments", "decorator", "methods", "python" ]
stackoverflow_0006122496_arguments_decorator_methods_python.txt
Q: Clean up ugly WYSIWYG HTML code? Python or *nix utility I'm finally upgrading (rewriting ;) ) my first Django app, but I am migrating all the content. I foolishly gave users a full WYSIWYG editor for certain tasks, the HTML code produced is of course terribly ugly with more extra tags than content. Does anyone k...
Clean up ugly WYSIWYG HTML code? Python or *nix utility
I'm finally upgrading (rewriting ;) ) my first Django app, but I am migrating all the content. I foolishly gave users a full WYSIWYG editor for certain tasks, the HTML code produced is of course terribly ugly with more extra tags than content. Does anyone know of a library or external shell app I could use to clean u...
[ "You could also take a look at Bleach a white-list based HTML sanitizer. It uses html5lib to do what Kyle posted, but you'll get a lot more control over which elements and attributes are allowed in the final output.\n", "Beautiful Soup will probably get you a more complete solution, but you might be able to get s...
[ 3, 2, 0 ]
[]
[]
[ "django", "html", "python", "regex", "wysiwyg" ]
stackoverflow_0006028274_django_html_python_regex_wysiwyg.txt
Q: How to convert string to variable name? I would like to know how to convert a string input into a variable name to use into Python code. A concrete example: def insrospect(foo, bar): requested_module = makestringvariable(foo) requested_object = makestringvariable(bar) import requested_module for it...
How to convert string to variable name?
I would like to know how to convert a string input into a variable name to use into Python code. A concrete example: def insrospect(foo, bar): requested_module = makestringvariable(foo) requested_object = makestringvariable(bar) import requested_module for item in inspect.getmemebers(requested_module.re...
[ "with the __import__ function and the getattr magic, you will be able to directly write this : \nimport importlib\ndef introspect(foo, bar):\n imported_module = importlib.import_module(foo)\n imported_object = getattr(imported_module, bar)\n for item in inspect.getmembers(imported_object):\n if call...
[ 11, 6, 3 ]
[]
[]
[ "introspection", "module", "python", "string", "variables" ]
stackoverflow_0006122816_introspection_module_python_string_variables.txt
Q: SMTP AUTH extension trouble with Python I am trying to write a simple Python script to send emails through my company's SMTP server. I am using the following piece of code. #! /usr/local/bin/python import sys,re,os,datetime from smtplib import SMTP #Email function def sendEmail(message): sender="SENDERID...
SMTP AUTH extension trouble with Python
I am trying to write a simple Python script to send emails through my company's SMTP server. I am using the following piece of code. #! /usr/local/bin/python import sys,re,os,datetime from smtplib import SMTP #Email function def sendEmail(message): sender="SENDERID@COMPANY.com" receivers=['REVEIVER1@C...
[ "The error you get means the SMTP server you're talking to doesn't claim to support authentication. If you look at the debug output you'll see that none of the responses to your EHLOs contain the necessary declaration for AUTH. If it did (properly) support authentication, one of the responses would be something lik...
[ 8 ]
[]
[]
[ "authentication", "email", "python", "smtp", "smtplib" ]
stackoverflow_0006123072_authentication_email_python_smtp_smtplib.txt
Q: PyQt: how to receive keyboard events in a subclassed QWidget? Maybe this is been asked many times, but i can't find a solution. I have a dialog: class PostDialog(QtGui.QDialog): def __init__(self, parent=None): QtGui.QDialog.__init__(self, parent) self.ui = Ui_Dialog() #code from designer!! ...
PyQt: how to receive keyboard events in a subclassed QWidget?
Maybe this is been asked many times, but i can't find a solution. I have a dialog: class PostDialog(QtGui.QDialog): def __init__(self, parent=None): QtGui.QDialog.__init__(self, parent) self.ui = Ui_Dialog() #code from designer!! self.ui.setupUi(self) self.ui.plainTextEdit = Content...
[ "I recommend using installEventFilter for this purpose:\nThis would look like:\nclass PostDialog(QtGui.QDialog):\n def __init__(self, parent=None):\n QtGui.QDialog.__init__(self, parent)\n self.ui = Ui_Dialog() #code from designer!!\n self.ui.setupUi(self)\n\n self.ui.plainTextEdit.in...
[ 3, 2, 1, 0 ]
[]
[]
[ "events", "pyqt", "python", "qt", "subclass" ]
stackoverflow_0006113352_events_pyqt_python_qt_subclass.txt
Q: Sql statement with like from variable I'm executing this code in python from sqlite3 import dbapi2 as sqlite con = sqlite.connect("db.sqlite") cur = con.cursor() surname = "'%atton%'" cur.execute("select id from singers where surname like :surname", locals()) cur.close() con.close() After this code cur.rowcount ...
Sql statement with like from variable
I'm executing this code in python from sqlite3 import dbapi2 as sqlite con = sqlite.connect("db.sqlite") cur = con.cursor() surname = "'%atton%'" cur.execute("select id from singers where surname like :surname", locals()) cur.close() con.close() After this code cur.rowcount == -1 but Patton is in the database. Is my ...
[ "The DB-API parameterization you use (which you should use, don't change that) means the surname will automatically be quoted or escaped appropriately. You should remove the inner set of quotes from your surname string.\nsurname = \"%atton%\"\ncur.execute(\"select id from singers where surname like :surname\",\n ...
[ 5 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0006123590_python_sqlite.txt
Q: How to download attachment from gmail using python? How to download the attachment from gmail inbox using python program? A: With poplib in general. And there is python-gmail library: libgmail
How to download attachment from gmail using python?
How to download the attachment from gmail inbox using python program?
[ "With poplib in general.\nAnd there is python-gmail library: libgmail\n" ]
[ 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006123851_django_python.txt
Q: XML parsing problem in Python - cannot find findtext I tried to parse XML with code import urllib2 from xml.etree import ElementTree if __name__ == '__main__': print 'hello' result = urllib2.urlopen('http://localhost/conf.xml').read() xml = ElementTree.fromstring(result) print result print xm...
XML parsing problem in Python - cannot find findtext
I tried to parse XML with code import urllib2 from xml.etree import ElementTree if __name__ == '__main__': print 'hello' result = urllib2.urlopen('http://localhost/conf.xml').read() xml = ElementTree.fromstring(result) print result print xml.findtext('.//type') When I print resut I get all xml fi...
[ "It's nothing to do with namespaces.\nProblem 1: type is NOT a tag, it is an attribute of the element whose tag is datalink.\nProblem 2: xml.findtext() returns the text component of the element; that's NOT what you want.\nWhat you do want is this:\nelem = xml.find(\".//datalink\")\nprint repr(elem)\nprint elem.get(...
[ 4, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006122681_python.txt
Q: Which python project to choose for a database-heavy application I plan to develop a rather database heavy (~100 tables) web application in python. The focus is on providing a nice and task-optimized interface for people that edit or navigate through the data. Other focuses are: Handle lots of data and complex que...
Which python project to choose for a database-heavy application
I plan to develop a rather database heavy (~100 tables) web application in python. The focus is on providing a nice and task-optimized interface for people that edit or navigate through the data. Other focuses are: Handle lots of data and complex queries. Internationalization (translation, timezones, currencies) Maili...
[ "Imo the only part of django that might be \"too\" publishing orientated is the admin, but I have seen plenty of django applications doing stuff neatly. \nDjango has plenty of apps available covering what you want to do, but the only road block you might find is the part of: handle lots of data and complex queries....
[ 3, 2, 0, 0 ]
[]
[]
[ "python", "web_applications", "web_frameworks" ]
stackoverflow_0006123950_python_web_applications_web_frameworks.txt
Q: Python LinkedIn API problem (OAuth) has anyone used the pylinkedin library ? After redirection from LinkedIn when I try to get the accessToken LinkedIn returns oauth_problem=permission_unknown Any clues A: I think our fork of the Linkedin-Client-Library is much more complete (yet a bit heavy) https://github.com...
Python LinkedIn API problem (OAuth)
has anyone used the pylinkedin library ? After redirection from LinkedIn when I try to get the accessToken LinkedIn returns oauth_problem=permission_unknown Any clues
[ "I think our fork of the Linkedin-Client-Library is much more complete (yet a bit heavy)\nhttps://github.com/PhilGo20/LinkedIn-Client-Library\n" ]
[ 0 ]
[]
[]
[ "linkedin", "oauth", "python" ]
stackoverflow_0002330376_linkedin_oauth_python.txt
Q: Django class problem first excuse me for my english it isn't the best one. I'm pretty new to django and python and i try to programm a user authentification. I used the django documentation and everything works fine with these code below: def anges(request): username = [] password = [] if...
Django class problem
first excuse me for my english it isn't the best one. I'm pretty new to django and python and i try to programm a user authentification. I used the django documentation and everything works fine with these code below: def anges(request): username = [] password = [] if request.method == "POST":...
[ "Quite obvious that you can't use the request variable in __init__ in the einloggen class, because, quite frankly, you don't send the request variable in to the constructor.\nI can't see you making a einloggen object anywhere in your view either, but you should probably to something like:\nclass einloggen:\n def...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006124187_django_python.txt
Q: How to uncompress gzipped data in a byte array? I have a byte array containing data that is compressed by gzip. Now I need to uncompress this data. How can this be achieved? A: zlib.decompress(data, 15 + 32) should autodetect whether you have gzip data or zlib data. zlib.decompress(data, 15 + 16) should work if...
How to uncompress gzipped data in a byte array?
I have a byte array containing data that is compressed by gzip. Now I need to uncompress this data. How can this be achieved?
[ "zlib.decompress(data, 15 + 32) should autodetect whether you have gzip data or zlib data. \nzlib.decompress(data, 15 + 16) should work if gzip and barf if zlib.\nHere it is with Python 2.7.1, creating a little gz file, reading it back, and decompressing it:\n>>> import gzip, zlib\n>>> f = gzip.open('foo.gz', 'wb')...
[ 38, 6 ]
[]
[]
[ "python" ]
stackoverflow_0006123223_python.txt
Q: Screenscaping aspx with Python Mechanize - Javascript form submission I'm trying to scrape UK Food Ratings Agency data aspx seach results pages (e.,g http://ratings.food.gov.uk/QuickSearch.aspx?q=po30 ) using Mechanize/Python on scraperwiki ( http://scraperwiki.com/scrapers/food_standards_agency/ ) but coming up w...
Screenscaping aspx with Python Mechanize - Javascript form submission
I'm trying to scrape UK Food Ratings Agency data aspx seach results pages (e.,g http://ratings.food.gov.uk/QuickSearch.aspx?q=po30 ) using Mechanize/Python on scraperwiki ( http://scraperwiki.com/scrapers/food_standards_agency/ ) but coming up with a problem when trying to follow "next" page links which have the form: ...
[ "Mechanize doesn´t handle javascript, but for this particular case it isn´t needed.\nFirst we open the result page with mechanize\nurl = 'http://ratings.food.gov.uk/QuickSearch.aspx?q=po30'\nbr = mechanize.Browser()\nbr.set_handle_robots(False)\nbr.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-U...
[ 8, 2 ]
[]
[]
[ "asp.net", "mechanize", "python", "scraperwiki" ]
stackoverflow_0006116023_asp.net_mechanize_python_scraperwiki.txt
Q: Need to reverse File but last line has no Carriage Return, so first item of Reversed List has 2 lines in it Here is the file 303620.43,6187793.62 303663.61,6187757.08 303652.22,6187702.51 303580.10,6187685.43 303551.63,6187737.15 303574.88,6187775.11 303610.94,6187773.69 When it is reversed I get 303610.94,618777...
Need to reverse File but last line has no Carriage Return, so first item of Reversed List has 2 lines in it
Here is the file 303620.43,6187793.62 303663.61,6187757.08 303652.22,6187702.51 303580.10,6187685.43 303551.63,6187737.15 303574.88,6187775.11 303610.94,6187773.69 When it is reversed I get 303610.94,6187773.69303574.88,6187775.11 303551.63,6187737.15 303580.10,6187685.43 303652.22,6187702.51 303663.61,6187757.08 3036...
[ "Use rstrip to remove the newline (and other trailing whitespace) off all lines, then rely on print to put it back in.\na = [ln.rstrip() for ln in open('datafile.txt')]\na.reverse()\nfor ln in a:\n print(ln)\n\n", "In your code, after you've read a line, check that it ends in '\\n'. If it doesn't, append a '\\...
[ 5, 1, 0 ]
[]
[]
[ "file", "line", "python", "return", "reverse" ]
stackoverflow_0006124000_file_line_python_return_reverse.txt
Q: Python BFS with collections I came across a BFS code which involves collections and deques but I could not understand it much. I hope some of the pythonistas here can help a n00b out. from collections import deque def bfs(g, start): queue, enqueued = deque([(None, start)]), set([start]) while queue: ...
Python BFS with collections
I came across a BFS code which involves collections and deques but I could not understand it much. I hope some of the pythonistas here can help a n00b out. from collections import deque def bfs(g, start): queue, enqueued = deque([(None, start)]), set([start]) while queue: parent, n = queue.popleft() ...
[ "\na |= b for sets is the same\nas a = a.union(b).\npopleft() does indeed return\nonly one element, which happens to\nbe a 2-tuple, and therefore can be\nunpacked into two values.\nnew is the set of not yet\nvisited nodes.\n\n", "Just to answer your last question: the piece of code you have there is a generator, ...
[ 2, 1, 0 ]
[]
[]
[ "breadth_first_search", "graph", "python" ]
stackoverflow_0006124402_breadth_first_search_graph_python.txt
Q: Python sending command over a socket I'm having a bit of trouble. I want to create a simple program that connects to the server and executes a command using subprocess then returns the result to the client. It's simple but I can't get it to work. Right now this is what I have: client: import sys, socket, subproce...
Python sending command over a socket
I'm having a bit of trouble. I want to create a simple program that connects to the server and executes a command using subprocess then returns the result to the client. It's simple but I can't get it to work. Right now this is what I have: client: import sys, socket, subprocess conn = socket.socket(socket.AF_INET, so...
[ "Danger, Will Robinson!!! \nDo you really want to send commands in clear text without authentication over the network? It is very, very dangerous.\nDo it over SSH with paramiko.\n\nAlright I've heard this answer too many times. I don't want to use SSH I'm just building it to learn more about sockets. I'm not going ...
[ 7, 3, 1, 0 ]
[]
[]
[ "client", "execution", "python", "subprocess" ]
stackoverflow_0004987077_client_execution_python_subprocess.txt
Q: Python failing to encode bad unicode to ascii I have some Python code that's receiving a string with bad unicode in it. When I try to ignore the bad characters, Python still chokes (version 2.6.1). Here's how to reproduce it: s = 'ad\xc2-ven\xc2-ture' s.encode('utf8', 'ignore') It throws UnicodeDecodeError: 'as...
Python failing to encode bad unicode to ascii
I have some Python code that's receiving a string with bad unicode in it. When I try to ignore the bad characters, Python still chokes (version 2.6.1). Here's how to reproduce it: s = 'ad\xc2-ven\xc2-ture' s.encode('utf8', 'ignore') It throws UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 2: or...
[ "Converting a string to a unicode instance is str.decode() in Python 2.x:\n >>> s.decode(\"ascii\", \"ignore\")\n u'ad-ven-ture'\n\n", "You are confusing \"unicode\" and \"utf-8\". Your string s is not unicode; it's a bytestring in a particular encoding (but not UTF-8, more likely iso-8859-1 or such.) Going from ...
[ 10, 8 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0006124897_python_unicode.txt
Q: Data manipulation by users I've got a Django Web app that (potentially) processes millions of records per user. In a nutshell, users upload files which are mapped to database fields/tables and the data is ultimately loaded into one of 5 MySQL tables. I'm using the awesome DataTables library to display the data b...
Data manipulation by users
I've got a Django Web app that (potentially) processes millions of records per user. In a nutshell, users upload files which are mapped to database fields/tables and the data is ultimately loaded into one of 5 MySQL tables. I'm using the awesome DataTables library to display the data back to the user. In many insta...
[ "Who are you're users, and how much do you trust them?\n\nIf your trust is low, you will need to expose some sort of API.\nIf your trust is high, take suggestions for an admin command such as \"transpose names\" and give them access to that table in Django admin. then they can select batches of records to apply thi...
[ 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0006116705_django_mysql_python.txt
Q: Implementing render-to-vertex-array, glReadPixels fails (invalid operation) I'm trying to copy vertex data from a texture to a vertex buffer, and then draw the vertex buffer. As far as I know the best way to do this is to bind the texture to a fbo, and use glReadPixels to copy it to a vbo. However, I can't seem to...
Implementing render-to-vertex-array, glReadPixels fails (invalid operation)
I'm trying to copy vertex data from a texture to a vertex buffer, and then draw the vertex buffer. As far as I know the best way to do this is to bind the texture to a fbo, and use glReadPixels to copy it to a vbo. However, I can't seem to get this working: glReadPixels fails with the error "invalid operation". Correct...
[ "I've solved the issue myself. \nThe last argument to ReadPixels is used as an offset instead of a pointer in this case, and is not automatically cast by pyopengl, use:\nglReadPixels(0, 0, w, h, GL_RGBA, GL_FLOAT, c_void_p(0)) # works!\n\n" ]
[ 1 ]
[]
[]
[ "glreadpixels", "opengl", "pyopengl", "python", "vbo" ]
stackoverflow_0005755478_glreadpixels_opengl_pyopengl_python_vbo.txt
Q: calling python __init__ on a class I have a class (say called Account) saved a as a variable (say cur_class) and I want to initialize an instance of the class. I thought cur_class.__init__() would work but it is giving me 'unbound method init() must be called with Account instance as first argument (got nothing...
calling python __init__ on a class
I have a class (say called Account) saved a as a variable (say cur_class) and I want to initialize an instance of the class. I thought cur_class.__init__() would work but it is giving me 'unbound method init() must be called with Account instance as first argument (got nothing instead)'. Obviously I'm doing somethin...
[ "Try cur_class(). For example:\nIn [1]: class C(object): pass\n ...: \n\nIn [2]: cur_class = C\n\nIn [3]: obj = cur_class()\n\nIn [4]: obj\nOut[4]: <__main__.C object at 0x1953c50>\n\nA slightly longer explanation is that Python classes are callable. Calling a class returns a new instance.\n" ]
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0006125761_python.txt
Q: Common File on Server I created an app. Its copy will be in two different computers. But a sqlite database file needs to be common for these two apps. I mean, both computers will be able to read and write this database file. For this purpose, I will put this file in a folder on our server which both computers are ...
Common File on Server
I created an app. Its copy will be in two different computers. But a sqlite database file needs to be common for these two apps. I mean, both computers will be able to read and write this database file. For this purpose, I will put this file in a folder on our server which both computers are connected to. How can I get...
[ "Sqlite over a network share [stackoverflow.com]\nI'd recommend against database files on a network drive. The network filesystem usually isn't robust enough to handle random updates like a DB. \nAs a previous answer suggested, you'd be better off creating a simple client/server model. A server process has sole acc...
[ 3, 0 ]
[]
[]
[ "python", "sqlite", "windows" ]
stackoverflow_0006125430_python_sqlite_windows.txt
Q: What is the correct way to retrieve timezone aware datetime objects from a cx_oracle cursor? cx_oracle returns datetime instances for columns of the TIMESTAMP or TIMESTAMP WITH TIME ZONE types, but these datetime instances are not timezone aware. For example: SELECT column_name, data_type FROM ALL_TAB_COLUMNS WHER...
What is the correct way to retrieve timezone aware datetime objects from a cx_oracle cursor?
cx_oracle returns datetime instances for columns of the TIMESTAMP or TIMESTAMP WITH TIME ZONE types, but these datetime instances are not timezone aware. For example: SELECT column_name, data_type FROM ALL_TAB_COLUMNS WHERE table_name = 'mytable'; column_name data_type ----------- --------------------------- MYCOL ...
[ "Here I see the following: For TIMESTAMP WITH TIME ZONE data, the datetime value is always in UTC, so no conversion is necessary.\nSo if you get the datetime object timezone unaware, I understand it is in UTC. So you can do:\ndt = pytz.utc.localize(row['mycol'])\n\nOr try the function SYS_EXTRACT_UTC (Extracts the ...
[ 3 ]
[]
[]
[ "cx_oracle", "internationalization", "oracle", "python" ]
stackoverflow_0006125698_cx_oracle_internationalization_oracle_python.txt
Q: Using Amazon's API to find a product's UPC (Python) I've been trying to create a python script that uses a product's ASIN to return (via Amazon's API) its UPC. The module I've attempted to use thusfar is python-amazon-product-api (http://packages.python.org/python-amazon-product-api/), but it doesn't appear that t...
Using Amazon's API to find a product's UPC (Python)
I've been trying to create a python script that uses a product's ASIN to return (via Amazon's API) its UPC. The module I've attempted to use thusfar is python-amazon-product-api (http://packages.python.org/python-amazon-product-api/), but it doesn't appear that this module supplies the UPC (or, at least, I can't find i...
[ "The item_lookup call only gets basic information. You will need to use the ResponseGroup parameter to specify what information you want Amazon to return (see Amazon's ItemLookup Documentation for more information). If you want to get additional product attributes, you should request the \"Medium\" response group....
[ 4 ]
[]
[]
[ "amazon", "amazon_product_api", "amazon_web_services", "api", "python" ]
stackoverflow_0006103772_amazon_amazon_product_api_amazon_web_services_api_python.txt
Q: Displaying date from string in Python Possible Duplicate: Parse date and format it using python? I have the following string in python: 2011-05-25T02:11:04Z How can I convert it to May, 25th 2:11 A: datetime.datetime.strptime('2011-05-25T02:11:04Z', '%Y-%m-%dT%H:%M:%SZ') gives you a datetime.datetime object ...
Displaying date from string in Python
Possible Duplicate: Parse date and format it using python? I have the following string in python: 2011-05-25T02:11:04Z How can I convert it to May, 25th 2:11
[ "datetime.datetime.strptime('2011-05-25T02:11:04Z', '%Y-%m-%dT%H:%M:%SZ') gives you a datetime.datetime object with the correct date / time.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0006125826_python.txt
Q: How do you assign an exception to a local variable in Python 2.5? In Python 2.6+, you can handle exceptions like this: try: # stuff except Exception as e: return 'exception %s' % type(e) What is the equivalent in 2.5? A: Like this : try: # stuff except Exception, e: return 'exception %s' % typ...
How do you assign an exception to a local variable in Python 2.5?
In Python 2.6+, you can handle exceptions like this: try: # stuff except Exception as e: return 'exception %s' % type(e) What is the equivalent in 2.5?
[ "Like this :\ntry:\n # stuff\nexcept Exception, e:\n return 'exception %s' % type(e)\n\n" ]
[ 13 ]
[]
[]
[ "python", "python_2.5" ]
stackoverflow_0006126107_python_python_2.5.txt
Q: Strange reduce behaviour When I execute this code in python 2.6 reduce(lambda x,y: x+[y], [1,2,3],[]) I get [1, 2, 3] as expected. But when I execute this one (I think it is equivalent to previous) reduce(lambda x,y: x.append(y), [1,2,3],[]) I get an error message Traceback (most recent call last): File "<stdin...
Strange reduce behaviour
When I execute this code in python 2.6 reduce(lambda x,y: x+[y], [1,2,3],[]) I get [1, 2, 3] as expected. But when I execute this one (I think it is equivalent to previous) reduce(lambda x,y: x.append(y), [1,2,3],[]) I get an error message Traceback (most recent call last): File "<stdin>", line 1, in <module> File...
[ "x.append(y) is not equivalent to x+[y]; append modifies a list in place and returns nothing, while x+[y] is an expression that returns the result.\n", "reduce calls the function and uses the return value as the new result. append returns None, and therefore the next append invocation fails. You could write\ndef ...
[ 16, 7, 6, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006124586_python.txt
Q: How to reference the same Model twice from another one? The following code class Translation(db.Model): origin = db.ReferenceProperty(Expression, required=True) target = db.ReferenceProperty(Expression, required=True) produces the following error: Traceback (most recent call last): File "C:\Program F...
How to reference the same Model twice from another one?
The following code class Translation(db.Model): origin = db.ReferenceProperty(Expression, required=True) target = db.ReferenceProperty(Expression, required=True) produces the following error: Traceback (most recent call last): File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev...
[ "Give distinct collection names\nclass Translation(db.Model):\n origin = db.ReferenceProperty(Expression, required=True,collection_name='origin_translation_set')\n target = db.ReferenceProperty(Expression, required=True,collection_name='target_translation_set')\n\nevery db.ReferenceProperty by default creates...
[ 11, 6, 5 ]
[]
[]
[ "foreign_keys", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0006126045_foreign_keys_google_app_engine_google_cloud_datastore_python.txt
Q: Translate various inconsistent date strings into a valid 'date'; Python I have a variety of text input files containing line-based records (csv/tsv etc.) that need to be processed; each row in each file typically has a date field, and the date formats vary wildly. My first instinct is to (manually) try to identify...
Translate various inconsistent date strings into a valid 'date'; Python
I have a variety of text input files containing line-based records (csv/tsv etc.) that need to be processed; each row in each file typically has a date field, and the date formats vary wildly. My first instinct is to (manually) try to identify each date format, and then for each row use regular expressions to identify ...
[ "Use the python-dateutil module, it's parse method can detect and parse many different date formats.\nNote that python-dateutil is quite specific in how it'll deal with ambiguous dates (year, month or day first) and let's you tweak how you parse these. This of course depends on what your data looks like; you may ha...
[ 1, 0 ]
[]
[]
[ "date", "python" ]
stackoverflow_0006126576_date_python.txt
Q: Retrieving newest object for persons So, I have a Person model and then I have a model name Carusage. The relevant part of Carusage is this: class Carusage(models.Model): person = models.ForeignKey(Person) start = models.DateTimeField() end = models.DateTimeField(null=True, blank=True) A Person can ta...
Retrieving newest object for persons
So, I have a Person model and then I have a model name Carusage. The relevant part of Carusage is this: class Carusage(models.Model): person = models.ForeignKey(Person) start = models.DateTimeField() end = models.DateTimeField(null=True, blank=True) A Person can take a car and then the system creates a new...
[ "By using exceptions that way, you are GUARANTEED to get slow code. Exceptions are horribly expensive and potentially slow down your code a lot (up to 5-10x slower with exceptions). Instead of raising and catching an exception, simply use else:\nif latest.end<time_now:\n time=latest.end\nelse:\n time=latest.sta...
[ 2, 2 ]
[]
[]
[ "django", "django_models", "django_queryset", "python" ]
stackoverflow_0006124485_django_django_models_django_queryset_python.txt
Q: Why are replies to my SMTP-sent gmail messages not threaded? I'm sending lots of similar emails out via SMTP using the following Python snippet: def send(from_, to, body): server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() server.ehlo() server.login('michael@gmail.com', password)...
Why are replies to my SMTP-sent gmail messages not threaded?
I'm sending lots of similar emails out via SMTP using the following Python snippet: def send(from_, to, body): server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() server.ehlo() server.login('michael@gmail.com', password) msg = '''\ From: %s To: %s Subject: %s %s''' % (from_, to.enco...
[ "Look at the References: header. It contains a chain of the previous Message-ID: headers in the thread, and is typically used for threading. It's usually a good idea to specify the Message-ID: yourself, and if you keep track of your previously used ones, you can use them in the References: header to enforce threa...
[ 6 ]
[]
[]
[ "gmail", "imap", "imaplib", "python" ]
stackoverflow_0006126718_gmail_imap_imaplib_python.txt
Q: python relative import weirdness I have a file: STARTDIR/module/submodule/config.py I have another file: STARDIR/utils/filesys/getAbsPath.py Why does this line work, in config.py? from ..utils.filesys import getAbsPath It seems like .. refers to module, not STARTDIR. There is no utils in module at all. In fact,...
python relative import weirdness
I have a file: STARTDIR/module/submodule/config.py I have another file: STARDIR/utils/filesys/getAbsPath.py Why does this line work, in config.py? from ..utils.filesys import getAbsPath It seems like .. refers to module, not STARTDIR. There is no utils in module at all. In fact, doing from .. import utils yields Im...
[ "This should work:\nfrom ...utils.filesystem import getAbsPath\n\nThis is because:\n\nfrom . import … imports from STARTDIR/module/submodule/\nfrom .. import … imports from STARTDIR/module/\nfrom ... import … imports from STARTDIR/\n\n" ]
[ 5 ]
[]
[]
[ "import", "python" ]
stackoverflow_0006126628_import_python.txt
Q: In PyGTK, what's a good way of displaying an image in a GUI? I have a PyGTK GUI that has a gtk.Table. Pressing one button will generate a PNG file. I can show the PNG file in the GUI by adding it somewhere in the table and calling the main window's show_all method again. Is there a better way? What if I want to sh...
In PyGTK, what's a good way of displaying an image in a GUI?
I have a PyGTK GUI that has a gtk.Table. Pressing one button will generate a PNG file. I can show the PNG file in the GUI by adding it somewhere in the table and calling the main window's show_all method again. Is there a better way? What if I want to show more than one PNG file at a time?
[ "You can use a combination of gtk.Image, gtk.HBox (or VBox), and maybe gtk.ScrolledWindow if you plan on showing a lot of images. Just create a new gtk.Image, set the image using set_from_file, then call pack_end on the box to display it.\n" ]
[ 0 ]
[]
[]
[ "gtk", "png", "pygtk", "python" ]
stackoverflow_0006126044_gtk_png_pygtk_python.txt