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: ImportError with Pylons/SQLAlchemy and MySQL Firstly, I should say I'm completely new to Pylons, trying to learn web development with Python after coming from a PHP/MySQL background. I've seen similar questions to this problem, but mine is kind of a reverse version. I've been following the Pylons book (pylonsbook....
ImportError with Pylons/SQLAlchemy and MySQL
Firstly, I should say I'm completely new to Pylons, trying to learn web development with Python after coming from a PHP/MySQL background. I've seen similar questions to this problem, but mine is kind of a reverse version. I've been following the Pylons book (pylonsbook.com) to setup my application and get the following...
[ "Either install the .so.15 version of the library, or find or build MySQLdb against .so.16.\n", "I had the same error, although I was working with Django. I'm using Ubuntu Lucid (10.04) and a solution that worked for me was to delete (or rename) the MySQL_python-1.2.3c1-py2.6-linux-i686.egg directory and install ...
[ 2, 0 ]
[]
[]
[ "mysql", "pylons", "python", "sqlalchemy" ]
stackoverflow_0002649262_mysql_pylons_python_sqlalchemy.txt
Q: How much faster is Python 2.7's new IO library compared to earlier versions? The Python 2.7 update note says: A new version of the io library, rewritten in C for performance. I've played with Python 2.7 a bit, but I don't see any performance gain: >>> from timeit import Timer >>> t = Timer('f = open("E:\\db.txt"...
How much faster is Python 2.7's new IO library compared to earlier versions?
The Python 2.7 update note says: A new version of the io library, rewritten in C for performance. I've played with Python 2.7 a bit, but I don't see any performance gain: >>> from timeit import Timer >>> t = Timer('f = open("E:\\db.txt", "r"); f.read(); f.close()') >>> t.timeit(10000) And the result: Python 2.6....
[ "If you look at http://docs.python.org/library/io.html, the open() method in the io module isn't used by default for opening files in python 2.x. It was only in python 3.x which makes open() use io.open(). Try:\nfrom timeit import Timer\nt = Timer('f = io.open(\"E:\\\\db.txt\", \"r\"); f.read(); f.close()', 'import...
[ 4 ]
[]
[]
[ "io", "python", "python_2.7" ]
stackoverflow_0003412931_io_python_python_2.7.txt
Q: Dynamic linking and Python SWIG (C++) works in C++ fails in python I have a library for which I have created a python wrapper using SWIG. The library itself accepts user provided functions which are in an .so file that is dynamically linked. At the moment I'm dealing with one that I have created myself and have ma...
Dynamic linking and Python SWIG (C++) works in C++ fails in python
I have a library for which I have created a python wrapper using SWIG. The library itself accepts user provided functions which are in an .so file that is dynamically linked. At the moment I'm dealing with one that I have created myself and have managed to get the dynamic linking working... in C++. When I attempt to ru...
[ "A solution is to make sure that python is preloading the C++ main library in the global scope.\nThis is not a very elegant solution, and I don't want to do it, but it makes it work for the moment.\nAfter a little poking around here and recognising the LD_LIBRARY_PATH environment variable that I have to set every t...
[ 2, 1 ]
[]
[]
[ "c++", "dynamic_linking", "python", "swig" ]
stackoverflow_0003396966_c++_dynamic_linking_python_swig.txt
Q: Controlling a C# Winforms GUI with IronPython So I made a Winforms GUI in Visual Studio using C#, but for the project I am working on I want the majority of the code to be written in Python. I am hoping to have the "engine" written in python (for portability), and then have the application interface be something I...
Controlling a C# Winforms GUI with IronPython
So I made a Winforms GUI in Visual Studio using C#, but for the project I am working on I want the majority of the code to be written in Python. I am hoping to have the "engine" written in python (for portability), and then have the application interface be something I can swap out. I made the C# project compile to a ....
[ "Put everything after the call to Program.RunGUI() in an event handler.\nC#:\npublic static void RunGUI(EventHandler onLoad)\n{ \n ...\n\n window = new MainWindow();\n window.Load += onLoad;\n Application.Run(window);\n window.Load -= onLoad; //removes handler in case RunGUI() is called again\n}\n\...
[ 3, 1, 0 ]
[]
[]
[ "c#", "ironpython", "python", "winforms" ]
stackoverflow_0003402366_c#_ironpython_python_winforms.txt
Q: Forms not getting submitted with MECHANIZE in PYTHON! from mechanize import * import cookielib from BeautifulSoup import BeautifulSoup br = Browser() br.open('http://casesearch.courts.state.md.us/inquiry/inquiry-index.jsp') br.select_form(name="main") br.find_control(name="disclaimer").selected = True reponse = ...
Forms not getting submitted with MECHANIZE in PYTHON!
from mechanize import * import cookielib from BeautifulSoup import BeautifulSoup br = Browser() br.open('http://casesearch.courts.state.md.us/inquiry/inquiry-index.jsp') br.select_form(name="main") br.find_control(name="disclaimer").selected = True reponse = br.submit() print reponse.read() The Above is my code. Now...
[ "Add .items[0]:\nbr.find_control(name=\"disclaimer\").items[0].selected\n\nA fuller code snippet looks like this:\nimport mechanize\n\nbr = mechanize.Browser()\nbr.open('http://casesearch.courts.state.md.us/inquiry/inquiry-index.jsp')\nbr.select_form(name=\"main\")\nbr.find_control(name=\"disclaimer\").items[0].sel...
[ 1, 0 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0003413585_mechanize_python.txt
Q: What's Python equivalent to or equals expression, to get return foo or foo = 'bar' working? I'd like to do something like: def get_foo(): return self._foo or self._foo = Bar() I am looking for the cleanest way to do it. Is it possible with or equals? My attempts failed: >>> foo = None >>> foo or 'bar' 'bar'...
What's Python equivalent to or equals expression, to get return foo or foo = 'bar' working?
I'd like to do something like: def get_foo(): return self._foo or self._foo = Bar() I am looking for the cleanest way to do it. Is it possible with or equals? My attempts failed: >>> foo = None >>> foo or 'bar' 'bar' >>> foo >>> foo or foo = 'bar' File "<stdin>", line 1 SyntaxError: can't assign to operator >>...
[ "In Python, you cannot use assignments in expressions. So you have to do the assignment and the return statement on two different lines:\ndef get_foo(self):\n self._foo = self._foo or Bar()\n return self._foo\n\nBut in general, it's better to write it out:\ndef get_foo(self):\n if not self._foo:\n ...
[ 6, 4 ]
[ "I might be wrong, but this looks like a job for the ||= operator.\ndef get_foo():\n return self._foo |= Bar()\n\nMy Perl is rusty at best, but ||= seems to return an R-value, so the return should work.\nEdit: Woopsie, this is Python. It doesn't have a ||=. Bummer.\nThen I'd use the simulated ternary operator:\nde...
[ -2 ]
[ "python" ]
stackoverflow_0003413702_python.txt
Q: Postgres raises a "ACTIVE SQL TRANSACTION" (Errcode: 25001) I use psycopg2 for accessing my postgres database in python. My function should create a new database, the code looks like this: def createDB(host, username, dbname): adminuser = settings.DB_ADMIN_USER adminpass = settings.DB_ADMIN_PASS try: co...
Postgres raises a "ACTIVE SQL TRANSACTION" (Errcode: 25001)
I use psycopg2 for accessing my postgres database in python. My function should create a new database, the code looks like this: def createDB(host, username, dbname): adminuser = settings.DB_ADMIN_USER adminpass = settings.DB_ADMIN_PASS try: conn=psycopg2.connect(user=adminuser, password=adminpass, host=host...
[ "It looks like your cursor() is actually a transaction:\nhttp://initd.org/psycopg/docs/cursor.html#cursor\n\nCursors created from the same\n connection are not isolated, i.e., any\n changes done to the database by a\n cursor are immediately visible by the\n other cursors. Cursors created from\n different conne...
[ 3 ]
[]
[]
[ "postgresql", "psycopg2", "python" ]
stackoverflow_0003413646_postgresql_psycopg2_python.txt
Q: Escaping [ in Python Regular Expressions This reg exp search correctly checks to see if a string contains the text harry: re.search(r'\bharry\b', '[harry] blah', re.IGNORECASE) However, I need to ensure that the string contains [harry]. I have tried escaping with various numbers of back-slashes: re.search(r'\b\[h...
Escaping [ in Python Regular Expressions
This reg exp search correctly checks to see if a string contains the text harry: re.search(r'\bharry\b', '[harry] blah', re.IGNORECASE) However, I need to ensure that the string contains [harry]. I have tried escaping with various numbers of back-slashes: re.search(r'\b\[harry\]\b', '[harry] blah', re.IGNORECASE) re.s...
[ "The first one is correct:\nr'\\b\\[harry\\]\\b'\n\nBut this won’t match [harry] blah as [ is not a word character and so there is no word boundary. It would only match if there were a word character in front of [ like in foobar[harry] blah.\n", "You escape it the way you escape most regex metacharacter: precedin...
[ 7, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003413838_python_regex.txt
Q: regular expression - incremental replacement Is there any way to do integer incremental replacement only with regex. Here is the problem, I have text file containing 1 000 000 lines all starting with % I would like to have replace # by integer incrementally using regex. input: % line one % line two % line thre...
regular expression - incremental replacement
Is there any way to do integer incremental replacement only with regex. Here is the problem, I have text file containing 1 000 000 lines all starting with % I would like to have replace # by integer incrementally using regex. input: % line one % line two % line three ... output: 1 line one 2 line two 3 line th...
[ "n = 1\nwith open('sourcefile.txt') as input:\n with open('destination.txt', 'w') as output:\n for line in input:\n if line.startswith('%'):\n line = str(n) + line[1:]\n n += 1\n output.write(line)\n\n", "Here's a way to do it in Python\nimport re\nfro...
[ 5, 4, 4, 0, 0, 0, 0, 0 ]
[]
[]
[ "c#", "java", "php", "python", "regex" ]
stackoverflow_0003185669_c#_java_php_python_regex.txt
Q: Best way to generate CRC8/16 when input is odd number of BITS (not byte)? C or Python So I'm stuck with a protocol that adds a CRC8/CRC16 over odd number of bits. (ie. it's not divisible by 8) What's the best method to generate the CRC for it in software? There are plenty of CRC algorithm that uses table, but th...
Best way to generate CRC8/16 when input is odd number of BITS (not byte)? C or Python
So I'm stuck with a protocol that adds a CRC8/CRC16 over odd number of bits. (ie. it's not divisible by 8) What's the best method to generate the CRC for it in software? There are plenty of CRC algorithm that uses table, but they are lookup per byte. Of course, there's the "fail-safe" of doing it one bit at a time. ...
[ "Padding with zeros at the front should not change the result. Computing the CRC is essentially binary long division. Unfortunately this involves splitting each byte. This is easy to with shift operators and bitwise or.\nZero padding at the end is, much easier, and depending on your reason for computing the CRC, a...
[ 8 ]
[]
[]
[ "algorithm", "c", "python" ]
stackoverflow_0003411654_algorithm_c_python.txt
Q: sharing a string between two objects I want two objects to share a single string object. How do I pass the string object from the first to the second such that any changes applied by one will be visible to the other? I am guessing that I would have to wrap the string in a sort of buffer object and do all sorts o...
sharing a string between two objects
I want two objects to share a single string object. How do I pass the string object from the first to the second such that any changes applied by one will be visible to the other? I am guessing that I would have to wrap the string in a sort of buffer object and do all sorts of complexity to get it to work. However,...
[ "\nI want two objects to share a single\n string object.\n\nThey will, if you simply pass the string -- Python doesn't copy unless you tell it to copy.\n\nHow do I pass the string object from\n the first to the second such that any\n changes applied by one will be visible\n to the other?\n\nThere can never be a...
[ 2, 2, 1 ]
[]
[]
[ "object", "python", "string" ]
stackoverflow_0003411614_object_python_string.txt
Q: Pythonic way to iterate over sequence, 4 items at a time Possible Duplicate: What is the most “pythonic” way to iterate over a list in chunks? I am reading in some PNG data, which has 4 channels per pixel. I would like to iterate over the data 1 pixel at a time (meaning every 4 elements = 1 pixel, rgba). red_ch...
Pythonic way to iterate over sequence, 4 items at a time
Possible Duplicate: What is the most “pythonic” way to iterate over a list in chunks? I am reading in some PNG data, which has 4 channels per pixel. I would like to iterate over the data 1 pixel at a time (meaning every 4 elements = 1 pixel, rgba). red_channel = 0 while red_channel < len(raw_png_data): green_ch...
[ "(Python's itertools should really make all recipes as standard functions...)\nYou could use the grouper function:\nfrom itertools import zip_longest\ndef grouper(n, iterable, fillvalue=None):\n \"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return izip_longest(fillvalue=fil...
[ 38, 34, 9, 3 ]
[ "Try something like this:\nfor red, green, blue, alpha in raw_png_data:\n #do something\n\nYou can pull out multiple items and never have to use an iterator. :)\nEdit: This would mean that raw_png_data needs to be a list of 4 value tuples. It would be most pythonic to put each rgba group into a tuple and then ap...
[ -4 ]
[ "iteration", "python" ]
stackoverflow_0003415072_iteration_python.txt
Q: testing assertion error in python I'm doing a test suite in python based on the code provided by selenium and i get strange assertion errors when checking for the actual page like this: sel.click("link=Overview") sel.wait_for_page_to_load("30000") self.assertEqual("Naaya testing - Subtitlu testare", sel.get_title(...
testing assertion error in python
I'm doing a test suite in python based on the code provided by selenium and i get strange assertion errors when checking for the actual page like this: sel.click("link=Overview") sel.wait_for_page_to_load("30000") self.assertEqual("Naaya testing - Subtitlu testare", sel.get_title()) sel.click("link=Portal properties")...
[ "In python when you use == operator order may make difference. Try \"Your strng\" == title and check result. Also assertEqual may check type, so correct code will be:\nself.assertEqual(\"Naaya testing - Subtitlu testare\", str(sel.get_title()))\n\nor:\nself.assertEqual(u\"Naaya testing - Subtitlu testare\", sel.get...
[ 2 ]
[]
[]
[ "python", "selenium", "unit_testing" ]
stackoverflow_0003414335_python_selenium_unit_testing.txt
Q: Python submodule internal references -- are they just crazy? Apologies in advange for the newbie question. I can't get my head around this, and the docs don't help! Consider the following directory structure: spam.py foo / __init__.py ham.py eggs.py with the following code: # __init__.py #...
Python submodule internal references -- are they just crazy?
Apologies in advange for the newbie question. I can't get my head around this, and the docs don't help! Consider the following directory structure: spam.py foo / __init__.py ham.py eggs.py with the following code: # __init__.py # blank # ham.py print( "got ham!" ) # eggs.py print( "got eggs, ...
[ "The parent directory for foo needs to be in the python's path:\n$ ls foo\neggs.py ham.py ham.pyc __init__.py __init__.pyc\n$ python foo/ham.py\ngot ham!\n$ python foo/eggs.py\ngot eggs, importing ham!\nTraceback (most recent call last):\n File \"foo/eggs.py\", line 2, in <module>\n import foo.ham\nImportEr...
[ 1, 1, 0 ]
[]
[]
[ "module", "package", "python" ]
stackoverflow_0003414901_module_package_python.txt
Q: How to test if a dictionary contains certain keys Is there a nice approach to test if a dictionary contains multiple keys? A short version of: d = {} if 'a' in d and 'b' in d and 'c' in d: pass #do something Thanks. Edit: I can only use python2.4 -.- A: You can use set.issubset(...), like so: >>> d = {'a': ...
How to test if a dictionary contains certain keys
Is there a nice approach to test if a dictionary contains multiple keys? A short version of: d = {} if 'a' in d and 'b' in d and 'c' in d: pass #do something Thanks. Edit: I can only use python2.4 -.-
[ "You can use set.issubset(...), like so:\n>>> d = {'a': 1, 'b': 2, 'c': 3}\n>>> set(['a', 'b']).issubset(d)\nTrue\n>>> set(['a', 'x']).issubset(d)\nFalse\n\n\nPython 3 has introduced a set literal syntax which has been backported to Python 2.7, so these days the above can be written:\n>>> d = {'a': 1, 'b': 2, 'c': ...
[ 22, 20, 6, 1, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003415347_dictionary_python.txt
Q: How to use multiple Sessions in a pylons app? I've read "Multiple database connections with Python + Pylons + SQLAlchemy" and I get how to create multiple engines using that technique, but now I'm looking for advice on how to handle the creation of Sessions for these engines. Right now, the Session in my project i...
How to use multiple Sessions in a pylons app?
I've read "Multiple database connections with Python + Pylons + SQLAlchemy" and I get how to create multiple engines using that technique, but now I'm looking for advice on how to handle the creation of Sessions for these engines. Right now, the Session in my project is defined as per Pylons convention: myapp.model.met...
[ "If you want choose the database backend per one request, a good option is to call meta.Session(bind=get_engine_for_this_request()) as the first thing. That will create the session with the specified parameters. You can stick that into the BaseController if it makes sense in your case.\nFor multiple backends per on...
[ 1, 0 ]
[]
[]
[ "pylons", "python", "sqlalchemy" ]
stackoverflow_0003398507_pylons_python_sqlalchemy.txt
Q: web.py: How to selectively hide resources with 404s for any HTTP method? I want to selectively hide some resources based on some form of authentication in web.py, but their existence is revealed by 405 responses to any HTTP method that I haven't implemented. Here's an example: import web urls = ( '/secret', '...
web.py: How to selectively hide resources with 404s for any HTTP method?
I want to selectively hide some resources based on some form of authentication in web.py, but their existence is revealed by 405 responses to any HTTP method that I haven't implemented. Here's an example: import web urls = ( '/secret', 'secret', ) app = web.application(urls, globals()) class secret(): de...
[ "Enlightened by Daniel Kluev's answer, I ended up deriving from web.application to add support for a default method in the _delegate method:\nimport types\n\nclass application(web.application):\n def _delegate(self, f, fvars, args=[]):\n def handle_class(cls):\n meth = web.ctx.method\n ...
[ 3, 1, 0 ]
[]
[]
[ "http", "python", "web.py" ]
stackoverflow_0003382419_http_python_web.py.txt
Q: Asymmetric behavior for __getattr__, newstyle vs oldstyle classes this is the first time I write here, sorry if the message is unfocuessed or too long. I was interested in understanding more about how objects'attributes are fetched when needed. So I read the Python 2.7 documentation titled "Data Model" here, I me...
Asymmetric behavior for __getattr__, newstyle vs oldstyle classes
this is the first time I write here, sorry if the message is unfocuessed or too long. I was interested in understanding more about how objects'attributes are fetched when needed. So I read the Python 2.7 documentation titled "Data Model" here, I met __getattr__ and, in order to check whether I understood or not its be...
[ "See Special method lookup for new-style classes. \nSpecial methods are directly looked up in the class object, the instance objects and consequently __getattr__() and __getattribute__() are bypassed. For precisely the same reason, instance.__add__ = foobar doesn't work.\nThis is done to speed up attribute access...
[ 5, 1, 0 ]
[]
[]
[ "coding_style", "getattr", "new_operator", "python" ]
stackoverflow_0003415816_coding_style_getattr_new_operator_python.txt
Q: How to alternate colors in stacked bar graph in matplotlib? I want to alternate colors in a stacked bar graph in matplotlib..so as I can get different colors for the graphs depending on their type. I have two types except that they do not alternate regularly. so I need to check their type before I choose the color...
How to alternate colors in stacked bar graph in matplotlib?
I want to alternate colors in a stacked bar graph in matplotlib..so as I can get different colors for the graphs depending on their type. I have two types except that they do not alternate regularly. so I need to check their type before I choose the colors. The problem is that it is conditional. I provide the type in a...
[ "I'm confused when you say that self.__a is a list - when I try plotting a list:\nIn [19]: plt.bar(1,[1,2,3], 0.1, color='#ffcc00')\n\nI get\nAssertionError: incompatible sizes: argument 'height' must be length 1 or scalar\n\nHowever, what you can do is plot your values in a loop:\n# Setup code here...\n\nindices =...
[ 5 ]
[]
[]
[ "bar_chart", "matplotlib", "python" ]
stackoverflow_0003415775_bar_chart_matplotlib_python.txt
Q: How can I kill off a Python web app on GAE early following a redirect? Disclaimer: completely new to Python from a PHP background Ok I'm using Python on Google App Engine with Google's webapp framework. I have a function which I import as it contains things which need to be processed on each page. def some_functio...
How can I kill off a Python web app on GAE early following a redirect?
Disclaimer: completely new to Python from a PHP background Ok I'm using Python on Google App Engine with Google's webapp framework. I have a function which I import as it contains things which need to be processed on each page. def some_function(self): if data['user'].new_user and not self.request.path == '/main/ne...
[ "I suggest you return a boolean from some_function() based on whether the caller should continue execution or not. Example:\ndef some_function(self):\n if data['user'].new_user and not self.request.path == '/main/new':\n self.redirect('/main/new')\n return True\n return False\n\nclass Dashboard...
[ 4, 4, 0 ]
[]
[]
[ "google_app_engine", "python", "web_applications" ]
stackoverflow_0003002233_google_app_engine_python_web_applications.txt
Q: python: function that will call itself i was wondering if i can get your help with the stucture.logic of a function that will need to call itself def populate_frequency5(d,data,total_compare): freq=[] prev = None for row in d: if prev is None or prev==row[11]: freq.append(row[16]) doctor=row[...
python: function that will call itself
i was wondering if i can get your help with the stucture.logic of a function that will need to call itself def populate_frequency5(d,data,total_compare): freq=[] prev = None for row in d: if prev is None or prev==row[11]: freq.append(row[16]) doctor=row[10] drug=row[11][:row[11].find(' ')].c...
[ "Your current logic is faulty and will lead to runaway recursion. If you ever make a recursive call, you'll pass it a total_compare of True; but then within that recursive call it will not be set to False again, so when checked it will be true and yet another recursive call (with the same defect) will inevitably r...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003416844_python.txt
Q: How to include python compiler dependencies in maven web project? I have a simple website that has some related python scripts that I use for maintenance of that website (note, the python code are util scripts that we execute manually for various tasks). I need to be able to share it with other developers who may...
How to include python compiler dependencies in maven web project?
I have a simple website that has some related python scripts that I use for maintenance of that website (note, the python code are util scripts that we execute manually for various tasks). I need to be able to share it with other developers who may want to edit it. What Maven dependencies do I need to include so that ...
[ "I'm not sure I understood the question but Jython includes a compiler:\n<dependency>\n <groupId>org.python</groupId>\n <artifactId>jython</artifactId>\n <version>2.5.0</version>\n</dependency>\n\n" ]
[ 0 ]
[]
[]
[ "buildpath", "maven_2", "python" ]
stackoverflow_0003415928_buildpath_maven_2_python.txt
Q: Python - threaded pyinotify output. Better to write to file or to a string I have a pyinotify watcher running threaded, called as a separate class, at the moment it just prints its discoveries in a terminal window, if I wanted my script to make an action based on those changes am I better to: A) modify an array wi...
Python - threaded pyinotify output. Better to write to file or to a string
I have a pyinotify watcher running threaded, called as a separate class, at the moment it just prints its discoveries in a terminal window, if I wanted my script to make an action based on those changes am I better to: A) modify an array with each notification B) write to a file in /tmp and fetch it from my main script...
[ "import Queue\nchanges = Queue.Queue()\n\nand now use changes.put in the thread that discover the changes, changes.get in the thread that is supposed to act on those changes (there are several other useful methods in Queue\n that you should check -- also note, per the docs, that the module's renamed to queue, all l...
[ 1 ]
[]
[]
[ "inotify", "python", "theory" ]
stackoverflow_0003416876_inotify_python_theory.txt
Q: Set connection settings with Pyodbc + UnixODBC + FreeTDS I have a setup using Pyodbc, UnixODBC and FreeTDS, but somewhere in there some options are being set and I don't know where. According to SQL Server Management Studio, my program is sending some settings when it opens the connection: set quoted_identifier of...
Set connection settings with Pyodbc + UnixODBC + FreeTDS
I have a setup using Pyodbc, UnixODBC and FreeTDS, but somewhere in there some options are being set and I don't know where. According to SQL Server Management Studio, my program is sending some settings when it opens the connection: set quoted_identifier off set ansi_padding off set ansi_nulls off ... But I need a di...
[ "According to MSDN you should be able to set these in the connection string:\ncnxn = pyodbc.connect(\"DSN=someDSN;UID=someUser;PWD=somePass;QuotedID=Yes;AnsiNPW=Yes\")\n\n" ]
[ 3 ]
[]
[]
[ "odbc", "pyodbc", "python", "sql_server", "unixodbc" ]
stackoverflow_0003416814_odbc_pyodbc_python_sql_server_unixodbc.txt
Q: Easy way to delete a shelve .dat file left behind by my Python program? So I have a python program that ends up leaving a .dat file from the shelve function behind after execution. I would like my program to delete or clear that file once it is done. My textbook only mentions how to create a .dat file but not how ...
Easy way to delete a shelve .dat file left behind by my Python program?
So I have a python program that ends up leaving a .dat file from the shelve function behind after execution. I would like my program to delete or clear that file once it is done. My textbook only mentions how to create a .dat file but not how to clear it. Any good commands out there to take care of this? I don't need t...
[ "Register an atexit handler to do the cleanup for you (as described in the documentation here).\n", "This is easy:\nimport sys, os\nsys.atexit.register( os.remove, path_to_file )\n\nruns os.remove( path_to_file ) when the Python interpreter exists in a normal (not killed/crashed) way. But you need to make sure th...
[ 2, 2 ]
[]
[]
[ "python", "shelve" ]
stackoverflow_0003417290_python_shelve.txt
Q: Plural of words using Open Office API for Python (UNO) I would like to retrieve the plural words in different languages in Python. I know that openoffice has an API called uno (import uno) and it should give me this ability using openoffice's language dictionaries, but I could not find any reference to it. As a co...
Plural of words using Open Office API for Python (UNO)
I would like to retrieve the plural words in different languages in Python. I know that openoffice has an API called uno (import uno) and it should give me this ability using openoffice's language dictionaries, but I could not find any reference to it. As a concrete example, I would something like this: >>> print getPl...
[ "You can introspect the module with dir(uno) and then try dir() on uno.XXX, with whatever looks helpful. You can also use help() on uno and its members. I've never used it and I don't have access to OO on this computer so I can't help more than that...\n", "Nodebox Linguistics includes a convenient function for p...
[ 0, 0 ]
[]
[]
[ "nlp", "openoffice.org", "python", "pyuno" ]
stackoverflow_0003414702_nlp_openoffice.org_python_pyuno.txt
Q: python: can i set a variable to equal a function of itself? Can I do this? var1 = some_function(var1) When I tried to do this I got errors, but perhaps I was doing something wrong. A: If the variable has been previously defined, you can do that yes. Example: def f(x): return x+1 var1 = 5 var1 = f(var1) # v...
python: can i set a variable to equal a function of itself?
Can I do this? var1 = some_function(var1) When I tried to do this I got errors, but perhaps I was doing something wrong.
[ "If the variable has been previously defined, you can do that yes.\nExample:\ndef f(x):\n return x+1\n\nvar1 = 5\nvar1 = f(var1)\n# var1 is now 6\n\nIf the variable has not been defined previously, you can't do that, simply because there is no value that could be passed to the function.\n", "def myfun(param):\...
[ 11, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003417488_python.txt
Q: python: a shorter way to append values results_histogram_total=list(numpy.histogram(freq,bins=numpy.arange(0,6.1,.1))[0]) sum_total=sum(results_histogram_total) big_set=[] for i in results_histogram_total: big_set.append(100*(i/sum_total) is there a shorter way i can write the for loop to append the v...
python: a shorter way to append values
results_histogram_total=list(numpy.histogram(freq,bins=numpy.arange(0,6.1,.1))[0]) sum_total=sum(results_histogram_total) big_set=[] for i in results_histogram_total: big_set.append(100*(i/sum_total) is there a shorter way i can write the for loop to append the values?
[ "For appending, replace the loop with:\nbig_set.extend(100.0 * i / sum_total for i in results_histogram_total)\n\nhowever, it's best to replace all the last three lines with just:\nbig_set = [100.0 * i / sum_total for i in results_histogram_total]\n\nAlso, I would advise to not call a list \"something set\" -- it's...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0003417593_python.txt
Q: How to find all files in current directory with filenames that match a certain pattern in python? I am trying to find all the files in the same directory as my script that has a filename matching a certain pattern. Ideally, I would like to store it in an array once I get them. The pattern I need to match is someth...
How to find all files in current directory with filenames that match a certain pattern in python?
I am trying to find all the files in the same directory as my script that has a filename matching a certain pattern. Ideally, I would like to store it in an array once I get them. The pattern I need to match is something like: testing.JUNK.08-05.txt. All the filenames have the testing in the front and end with the date...
[ "Use the glob module:\nimport glob\nfor name in glob.glob('testing*08-05.txt'):\n print name\n\n" ]
[ 14 ]
[]
[]
[ "python" ]
stackoverflow_0003417745_python.txt
Q: py2exe access 'other_resources' So with py2exe you can add additional data inside the library zip file, now I was wondering, how do you access this data, do you need to read it out from the zipfile or can you just access it like any other file ? or perhaps there's another way to access it. A: I personally never ...
py2exe access 'other_resources'
So with py2exe you can add additional data inside the library zip file, now I was wondering, how do you access this data, do you need to read it out from the zipfile or can you just access it like any other file ? or perhaps there's another way to access it.
[ "I personally never used the zipfile. Instead, I pass the data files my program used in the setup method and use the bundle_files option (as described at the bottom of this page). For instance, the program I create using this call\nsetup(name = \"Urban Planning\",\n windows = [{'script': \"main.py\", \"dest_ba...
[ 1 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0003414616_py2exe_python.txt
Q: Writing only part of a line to a file I want to clean up my output and only write part of the line that I need to a new file and not the whole entire line. This is the relevent coding section: counter = 1 for line in completedataset: print counter counter +=1 for t in matchedLines: if t in lin...
Writing only part of a line to a file
I want to clean up my output and only write part of the line that I need to a new file and not the whole entire line. This is the relevent coding section: counter = 1 for line in completedataset: print counter counter +=1 for t in matchedLines: if t in line[:line.find(',')]: smallerdata...
[ "It should be as simple as this...\nfor line in infile:\n line = line.strip().split(',')\n outfile.write(','.join(line[:3]) + '\\n')\n\n", "for line in infile:\n line = line.strip().split(',',3)\n outfile.write(','.join(line[:-1]) + '\\n')\n\nIf there is a possibility of ',' showing up in any of the f...
[ 4, 1 ]
[]
[]
[ "line", "python" ]
stackoverflow_0003417813_line_python.txt
Q: Can I skip an indeterminate amount of steps for an enclosing loop? (Python) This is perhaps a result of bad design, but here it goes. I wasn't quite sure how to explain this problem. So I have code that iterates over a list of words. (This list does not change.) The code then parses and combines certain words toge...
Can I skip an indeterminate amount of steps for an enclosing loop? (Python)
This is perhaps a result of bad design, but here it goes. I wasn't quite sure how to explain this problem. So I have code that iterates over a list of words. (This list does not change.) The code then parses and combines certain words together, depending on a set of criteria, storing them in a new list. The master loop...
[ "you could try to use the itertools module and espacially the dropwhile function.\n", "Am I missing something?\nword_list = [\"apple\", \"banana\", \"penguin\"]\nskip_list = {}\n\nfor word in self.word_list:\n if word in skip_list:\n continue\n\n # Do word-pairing logic; if word paired, skip_list[wor...
[ 0, 0, 0 ]
[]
[]
[ "continue", "python" ]
stackoverflow_0003417908_continue_python.txt
Q: python: appends only '0' big_set=[] for i in results_histogram_total: big_set.append(100*(i/sum_total)) big_set returns [0,0,0,0,0,0,0,0........,0] this wrong because i checked i and it is >0 what am i doing wrong? A: In Python 2.x, use from __future__ import division to get sane division behavior. A: ...
python: appends only '0'
big_set=[] for i in results_histogram_total: big_set.append(100*(i/sum_total)) big_set returns [0,0,0,0,0,0,0,0........,0] this wrong because i checked i and it is >0 what am i doing wrong?
[ "In Python 2.x, use from __future__ import division to get sane division behavior.\n", "try this list comprehension instead\nbig_set = [100*i/sum_total for i in results_histogram_total]\n\nnote that / truncates in Python2, so you may wish to use\nbig_set = [100.0*i/sum_total for i in results_histogram_total]\n\n"...
[ 5, 3, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003418060_python.txt
Q: py. 'decimal' mod.: why flags on context rather than numbers Here is an example to explain what I'm on about: c = Decimal(10) / Decimal(3) c = Decimal(10) / Decimal(2) If I do this, then print c, the inexact and rounded flags are raised. Even though the result is accurate. Shouldn't flags therefore be attributes ...
py. 'decimal' mod.: why flags on context rather than numbers
Here is an example to explain what I'm on about: c = Decimal(10) / Decimal(3) c = Decimal(10) / Decimal(2) If I do this, then print c, the inexact and rounded flags are raised. Even though the result is accurate. Shouldn't flags therefore be attributes of numbers rather than the context? This problem is especially app...
[ "Read this: http://docs.python.org/library/decimal.html#context-objects\nYou have context objects that you can save and restore so that you don't lose flag values.\n" ]
[ 0 ]
[]
[]
[ "decimal", "python" ]
stackoverflow_0003418483_decimal_python.txt
Q: python: open unfocused tab with webbrowser I would like to open a new tab in my web browser using python's webbrowser. However, now my browser is brought to the top and I am directly moved to the opened tab. I haven't found any information about this in documentation, but maybe there is some hidden api. Can I open...
python: open unfocused tab with webbrowser
I would like to open a new tab in my web browser using python's webbrowser. However, now my browser is brought to the top and I am directly moved to the opened tab. I haven't found any information about this in documentation, but maybe there is some hidden api. Can I open this tab in the possible most unobtrusive way, ...
[ "On WinXP, at least, it appears that this is not possible (from my tests with IE).\nFrom what I can see, webbrowser is a fairly simple convenience module that creates (probably ) a subprocess-style call to the browser executable. \nIf you want that sort of granularity you'll have to see if your browser accepts comm...
[ 0 ]
[]
[]
[ "python", "python_webbrowser", "tabs" ]
stackoverflow_0003417756_python_python_webbrowser_tabs.txt
Q: device behind firewall connect via ssh There have been a few questions like this around the place but none have really answered my question specifically.(for example Connecting to device behind firewall ) What I want is a central server, that receives a heartbeat from multiple ( say 100's) embedded devices behind ...
device behind firewall connect via ssh
There have been a few questions like this around the place but none have really answered my question specifically.(for example Connecting to device behind firewall ) What I want is a central server, that receives a heartbeat from multiple ( say 100's) embedded devices behind personal firewalls. These devices need to be...
[ "You can setup ssh tunnel (from python script or from console):\nssh -NR10022:localhost:22 foo@mainserver.com\n\nThen you can simply login to main server and then ssh bar@localhost -p 10022\nYou should have ssh keys, so you don't have to put password (google about \"ssh without password\").\n", "A more elaborate ...
[ 2, 0 ]
[]
[]
[ "device", "embedded", "linux", "python", "ssh" ]
stackoverflow_0003412203_device_embedded_linux_python_ssh.txt
Q: Django Template Headings Is there a way in Django templates to show a heading for a field (name of the field) only if the field has a value. For instance if one of the fields was called Year Established it might look something like this. Year Established: 1985 But if the field was empty then it wouldn't show Year ...
Django Template Headings
Is there a way in Django templates to show a heading for a field (name of the field) only if the field has a value. For instance if one of the fields was called Year Established it might look something like this. Year Established: 1985 But if the field was empty then it wouldn't show Year Established like this. Year Es...
[ "@register.filter\ndef labeled(value, label):\n if value:\n return label + value\n else:\n return \"\"\n\nthen you can:\n{{ year_est|labeled:\"Year Established: \" }}\n\n" ]
[ 3 ]
[]
[]
[ "django", "python", "templates" ]
stackoverflow_0003418339_django_python_templates.txt
Q: FreeTDS translating MS SQL money type to python float, not Decimal I am connecting to an MS SQL Server db from Python in Linux. I am connecting via pyodbc using the FreeTDS driver. When I return a money field from MSSQL it comes through as a float, rather than a Python Decimal. The problem is with FreeTDS. If I...
FreeTDS translating MS SQL money type to python float, not Decimal
I am connecting to an MS SQL Server db from Python in Linux. I am connecting via pyodbc using the FreeTDS driver. When I return a money field from MSSQL it comes through as a float, rather than a Python Decimal. The problem is with FreeTDS. If I run the exact same Python code from Windows (where I do not need to use...
[ "You could always just convert it to Decimal when it comes back...\n", "It was a bug in FreeTDS. The bug has been fixed in the CVS head of FreeTDS as of August 4, 2010 (thanks Freddy Ziglio). See my post on the web2py message board for more info.\n" ]
[ 1, 0 ]
[]
[]
[ "freetds", "pyodbc", "python", "sql_server" ]
stackoverflow_0003371795_freetds_pyodbc_python_sql_server.txt
Q: Writing a Shell in Python? Why is this such a bad idea? (According to many people) A: I don't think it's a bad idea. Lots of people use IPython which is a shell written in Python :) In fact you may want to base your effort around IPython. scipy does this, for example A: I've always thought it was quite a cool ...
Writing a Shell in Python?
Why is this such a bad idea? (According to many people)
[ "I don't think it's a bad idea. Lots of people use IPython which is a shell written in Python :)\nIn fact you may want to base your effort around IPython. scipy does this, for example\n", "I've always thought it was quite a cool idea. Last time I got the urge to give it a go I was thinking about a maple-style wor...
[ 3, 0, 0 ]
[]
[]
[ "python", "shell" ]
stackoverflow_0003410296_python_shell.txt
Q: Vector algebra in functional How to implement vector sum, using functional programming in python. This code work for n <100, but not for n > 1000. from itertools import * #n=10000 # do not try!!! n=100 twin=((i,i**2,i**3) for i in xrange(1,n+1)) def sum(x=0,y=0): return x+y def dubsum(x,y): return (redu...
Vector algebra in functional
How to implement vector sum, using functional programming in python. This code work for n <100, but not for n > 1000. from itertools import * #n=10000 # do not try!!! n=100 twin=((i,i**2,i**3) for i in xrange(1,n+1)) def sum(x=0,y=0): return x+y def dubsum(x,y): return (reduce(sum,i) for i in izip(x,y) ) pr...
[ "Like this:\nprint [sum(e) for e in izip(*twin)]\n\nOr even more functionally:\nprint map(sum, izip(*twin))\n\nNote that zipping is very much like transposing a two-dimensional array.\n>>> zip([1, 2, 3, 4],\n... [5, 6, 7, 8]) == [(1, 5),\n... (2, 6),\n... (3, 7)...
[ 2, 0 ]
[]
[]
[ "function", "python", "vector" ]
stackoverflow_0003419202_function_python_vector.txt
Q: Python method overload based on argument count? If I call QApplication's init without arguments i get TypeError: arguments did not match any overloaded call: QApplication(list-of-str): not enough arguments QApplication(list-of-str, bool): not enough arguments QApplication(list-of-str, QApplication.Type): no...
Python method overload based on argument count?
If I call QApplication's init without arguments i get TypeError: arguments did not match any overloaded call: QApplication(list-of-str): not enough arguments QApplication(list-of-str, bool): not enough arguments QApplication(list-of-str, QApplication.Type): not enough arguments QApplication(Display, int visual...
[ "TypeError is just another Exception. You can take *args **kwargs, check those, and raise a TypeError yourself, specify the text displayed - e.g. listing the expected call.\nThat being said, PyQt is a bunch of .pyd == native python extension, written in C or C++ (using Boost::Python). At least the latter supports \...
[ 3, 0 ]
[]
[]
[ "overloading", "python" ]
stackoverflow_0003419282_overloading_python.txt
Q: Visualize high dimensional field arrows? I have a big list of tuples (a, b), where both a and b are 9-dimensional vectors from the same space. This essentially encodes states of a system and some transitions. I would like to visualize the field described by these tuples, as arrows pointing from a->b, either in 2D ...
Visualize high dimensional field arrows?
I have a big list of tuples (a, b), where both a and b are 9-dimensional vectors from the same space. This essentially encodes states of a system and some transitions. I would like to visualize the field described by these tuples, as arrows pointing from a->b, either in 2D or 3D. One of my problems however is that this...
[ "I'm not 100% sure if this answers your question or not, but you may want to look at Recurrence Plots. If this is what you're after, then you wont need any additional Matlab toolboxes.\n", "Okay, turns out MATLAB can do this but it's not very pretty.\nIt basically boils down to doing PCA, and then using the quive...
[ 1, 1, 1 ]
[]
[]
[ "matlab", "multidimensional_array", "python", "vector", "visualization" ]
stackoverflow_0003191834_matlab_multidimensional_array_python_vector_visualization.txt
Q: Generator in if-statement in python Or How to if-statement in a modified list. I've been reading StackOverflow for a while (thanks to everyone). I love it. I also seen that you can post a question and answer it yourself. Sorry if I duplicate, but I didn't found this particular answer on StackOverflow. How do you ...
Generator in if-statement in python
Or How to if-statement in a modified list. I've been reading StackOverflow for a while (thanks to everyone). I love it. I also seen that you can post a question and answer it yourself. Sorry if I duplicate, but I didn't found this particular answer on StackOverflow. How do you verify if a element is in a list but mod...
[ "if any(s.lower() == \"foo\" for s in list): print \"found\"\n\n", "List comprehensions:\nmylist = [\"Foo\", \"Bar\"]\nlowerList = [item.lower() for item in mylist]\n\nThen you can do something like if \"foo\" in lowerlist or bypass the temporary variable entirely with if \"foo\" in [item.lower() for item in myli...
[ 8, 1, 0, 0, 0 ]
[]
[]
[ "generator", "if_statement", "list", "list_comprehension", "python" ]
stackoverflow_0003419528_generator_if_statement_list_list_comprehension_python.txt
Q: How do you delete a file (located in the same directory that your script is running in) in Python? I'm trying to delete a certain file within the directory that I'm running my Python program in. def erase_custom_file(): directory=os.listdir(os.getcwd()) for somefile in directory: if somefile=...
How do you delete a file (located in the same directory that your script is running in) in Python?
I'm trying to delete a certain file within the directory that I'm running my Python program in. def erase_custom_file(): directory=os.listdir(os.getcwd()) for somefile in directory: if somefile=="file.csv": os.remove(???) I'm not sure what my next step should be. I know that os.remove ...
[ "Use unlink() and path.join()\n>>> try:\n... os.unlink(os.path.join(os.getcwd(),'file.csv'))\n... except OSError, e:\n... print e #file does not exist or you don't have permission\n\n", "This should work:\nos.remove( os.path.join( directory, somefile ) )\n\n", "If you are trying to delete a scratch file you m...
[ 6, 2, 0 ]
[]
[]
[ "delete_file", "python" ]
stackoverflow_0003419457_delete_file_python.txt
Q: How to write a simple server-push implementation in Python using django? I would like to write a simple server-push implementation either using long pooling or comet that integrates into the server. I don't want to use a networking framework like twisted because I want to learn how everything is done internally. W...
How to write a simple server-push implementation in Python using django?
I would like to write a simple server-push implementation either using long pooling or comet that integrates into the server. I don't want to use a networking framework like twisted because I want to learn how everything is done internally. What exactly should I learn? What specifications should I look at? I prefer som...
[ "Using Django it is not possible, because django works behind standard http server. To push you need to write a server supporting large number of paralell connections. To start with, I recommend reading Orbited source code. Read both server (python) and client (javascript) code. \n" ]
[ 0 ]
[]
[]
[ "comet", "django", "long_polling", "python", "server_push" ]
stackoverflow_0003417836_comet_django_long_polling_python_server_push.txt
Q: python or database? i am reading a csv file into a list of a list in python. it is around 100mb right now. in a couple of years that file will go to 2-5gigs. i am doing lots of log calculations on the data. the 100mb file is taking the script around 1 minute to do. after the script does a lot of fiddling with the ...
python or database?
i am reading a csv file into a list of a list in python. it is around 100mb right now. in a couple of years that file will go to 2-5gigs. i am doing lots of log calculations on the data. the 100mb file is taking the script around 1 minute to do. after the script does a lot of fiddling with the data, it creates URL's th...
[ "I'd only put it into a relational database if:\n\nThe data is actually relational and expressing it that way helps shrink the size of the data set by normalizing it.\nYou can take advantage of triggers and stored procedures to offload some of the calculations that your Python code is performing now.\nYou can take ...
[ 4, 4, 4, 2, 1 ]
[]
[]
[ "python", "sql" ]
stackoverflow_0003419624_python_sql.txt
Q: In class definition inherited from dict why is there a difference in defining attributes? In a class inherited from dict, why don't the two ways of defining an attribute produce the same result? Why do I see attr1 but not attr2? class my_dict(dict): def __init__(self): dict.__init__(self) self['at...
In class definition inherited from dict why is there a difference in defining attributes?
In a class inherited from dict, why don't the two ways of defining an attribute produce the same result? Why do I see attr1 but not attr2? class my_dict(dict): def __init__(self): dict.__init__(self) self['attr1'] = 'seen' setattr(self, 'attr2', 'unseen') In [1]: x = my_dict() In [2]: x Out[2]...
[ "For the same reason that:\nx = {}\nx.foo = 34\n\ndoesn't work. dicts don't work by defining attributes.\n", "x.attr2\n# => 'unseen'\n\n" ]
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003419921_python.txt
Q: traceback.print_exc() python question I am using the following line of code in IDLE to print out my traceback in an eception: traceback.print_exc() For some reason I get the red text error message, but then it is followed by a blue text of "None". Not sure what that None is about, any ideas? A: print_exc() print...
traceback.print_exc() python question
I am using the following line of code in IDLE to print out my traceback in an eception: traceback.print_exc() For some reason I get the red text error message, but then it is followed by a blue text of "None". Not sure what that None is about, any ideas?
[ "print_exc() prints formatted exception to stderr. If you need string value, call format_exc()\n", "print_exc() doesn't return anything, which in Python is actually returning None. Looks like IDLE is showing you the None it returned.\n" ]
[ 7, 5 ]
[]
[]
[ "exception_handling", "python" ]
stackoverflow_0003418834_exception_handling_python.txt
Q: In-place dictionary inversion in Python I need to invert a dictionary of lists, I don't know how to explain it in English exactly, so here is some code that does what I want. It just takes too much memory. def invert(oldDict): invertedDict = {} for key,valuelist in oldDict.iteritems(): for value in...
In-place dictionary inversion in Python
I need to invert a dictionary of lists, I don't know how to explain it in English exactly, so here is some code that does what I want. It just takes too much memory. def invert(oldDict): invertedDict = {} for key,valuelist in oldDict.iteritems(): for value in valuelist: try: ...
[ "This doesn't do it in place, but consumes oldDict by using popitem()\nfrom collections import defaultdict\ndef invert(oldDict):\n invertedDict = defaultdict(list)\n while oldDict:\n key, valuelist = oldDict.popitem()\n for value in valuelist:\n invertedDict[value].append(key)\n re...
[ 5, 2, 1, 0 ]
[]
[]
[ "generator", "hashtable", "list", "python" ]
stackoverflow_0003418189_generator_hashtable_list_python.txt
Q: wxPython: How to make a TextCtrl fill a Panel How do I set the size of a multi-line TextCtrl to always fill its parent panel? A: Use a boxSizer. When you add your textCtrl to the sizer set the proportion to 1 and pass the wx.EXPAND flag, that way your textCtrl should fill the panel even when the panel is resized...
wxPython: How to make a TextCtrl fill a Panel
How do I set the size of a multi-line TextCtrl to always fill its parent panel?
[ "Use a boxSizer.\nWhen you add your textCtrl to the sizer set the proportion to 1 and pass the wx.EXPAND flag, that way your textCtrl should fill the panel even when the panel is resized \nbsizer = wx.BoxSizer()\nbsizer.Add(yourTxtCtrl, 1, wx.EXPAND)\n\nPut the following at the end of your panels initialization to ...
[ 11 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003420021_python_wxpython.txt
Q: Confusion about string find? I have a list of data that I want to search through. This new list of data is structured like so. name, address dob family members age height etc.. I want to search through the lines of data so that I stop the search at the ',' that appears after the name to optimize the search. I beli...
Confusion about string find?
I have a list of data that I want to search through. This new list of data is structured like so. name, address dob family members age height etc.. I want to search through the lines of data so that I stop the search at the ',' that appears after the name to optimize the search. I believe I want to use this command: st...
[ "You can do it quite directly:\ns = 'Bennet, John, 17054099\",\"5\",\"156323558\",\"-\",\"0\", 714 //'\nprint s.find('John', 0, s.index(',')) # find the index of ',' and stop there\n\n", "If I understand your specs correctly,\nfor thestring in listdata:\n firstcomma = thestring.find(',')\n havename = thestr...
[ 5, 3, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003406892_python.txt
Q: networking program crashes i got this code from http://www.evolt.org/node/60276 and modified it to listen for a single "1" coming from the other side but whenever i run this program it stops and python IDLE goes to non-responding on "data1,addr = UDPSock.recvfrom(1024)" def get1(): # Server program, receives 1 if ...
networking program crashes
i got this code from http://www.evolt.org/node/60276 and modified it to listen for a single "1" coming from the other side but whenever i run this program it stops and python IDLE goes to non-responding on "data1,addr = UDPSock.recvfrom(1024)" def get1(): # Server program, receives 1 if ball found # ff1 is file w/ rece...
[ "As a second guess (I replaced my first guess with this) I suspect that you are running the receiver in IDLE and then IDLE is hanging so you can't run the client. I don't know exactly how IDLE works as I never use it, but the line containing recvfrom will stop the Python thread its running in until data is sent. ...
[ 0 ]
[]
[]
[ "networking", "python" ]
stackoverflow_0003420062_networking_python.txt
Q: Minimize to gnome panel I have an application written in python, I would like it to be able to "minimize" to the gnome panel, much like how gnome's rhytmbox minimizes to the panel. Is it easily possible to do this? I've run the examples from here but failed to get any of them working and those don't seem to be ex...
Minimize to gnome panel
I have an application written in python, I would like it to be able to "minimize" to the gnome panel, much like how gnome's rhytmbox minimizes to the panel. Is it easily possible to do this? I've run the examples from here but failed to get any of them working and those don't seem to be exactly what I'm looking for. A...
[ "The examples linked show how to write panel applets, which have been somewhat discouraged for a while now. Instead, you probably want to create a gtk.StatusIcon. Status icons require the user to have a system tray, but given their widespread use that covers just about everyone.\nOnce you've got your status icon, m...
[ 3 ]
[]
[]
[ "applet", "gnome", "python" ]
stackoverflow_0003419512_applet_gnome_python.txt
Q: What is a good django library for logging in users with Twitter, Facebook or an OpenID provider? I want to create an application that allows a user to register and login to a django application with an external provider. In addition, I then want the user to be able to associate additional accounts with that initia...
What is a good django library for logging in users with Twitter, Facebook or an OpenID provider?
I want to create an application that allows a user to register and login to a django application with an external provider. In addition, I then want the user to be able to associate additional accounts with that initial account. Finally, I would like the user to be able to login to the application with one of the other...
[ "The perfect solution for you seems to be Django-SocialAuth. See here. From the page:\nHere is an app to allow logging in via twitter, facebook, openid, yahoo, google, which should work transparently with Django authentication system. (@login_required, User and other infrastructure work as expected.) Demo and Code\...
[ 1 ]
[]
[]
[ "facebook", "oauth", "openid", "python" ]
stackoverflow_0003420540_facebook_oauth_openid_python.txt
Q: Django MySql setup I set up Mysql5, mysql5-server and py26-mysql using Macports. I then started the mysql server and was able to start the prompt with mysql5 In my settings.py i changed database_engine to "mysql" and put "dev.db" in database_name. I left the username and password blank as the database doesnt exist...
Django MySql setup
I set up Mysql5, mysql5-server and py26-mysql using Macports. I then started the mysql server and was able to start the prompt with mysql5 In my settings.py i changed database_engine to "mysql" and put "dev.db" in database_name. I left the username and password blank as the database doesnt exist yet. When I ran python ...
[ "syncdb will not create a database for you -- it only creates tables that don't already exist in your schema. You need to:\n\nCreate a user to 'own' the database (root is a bad choice).\nCreate the database with that user.\nUpdate the Django database settings with the correct database name, user, and password.\n\n...
[ 1, 1 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0003376673_django_mysql_python.txt
Q: How can I assign names to some numbers to feed them into a random number generator as variables I need some assistance here. import urllib2 pen = urllib2.Request("http://silasanio.appspot.com/mean_stdev") response = urllib2.urlopen(pen) f = response.read() print f -0.0011935729005 0.0313498454115 ............... ...
How can I assign names to some numbers to feed them into a random number generator as variables
I need some assistance here. import urllib2 pen = urllib2.Request("http://silasanio.appspot.com/mean_stdev") response = urllib2.urlopen(pen) f = response.read() print f -0.0011935729005 0.0313498454115 ............... .............. the numbers above were returned together with some other texts. My problem is I want...
[ "If you can avoid making f, you can just use:\nlines = response.readlines()\nmean = float(lines[0])\nstddev = float(lines[1])\n\nIf you need f for other purposes, replace the first of these statements with\nlines = f.splitlines()\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003420786_python.txt
Q: Issues with time.sleep and Multithreading in Python I am having an issue with the time.sleep() function in python. I am running a script that needs to wait for another program to generate txt files. Although, this is a terribly old machine, so when I sleep the python script, I run into issues with the other progra...
Issues with time.sleep and Multithreading in Python
I am having an issue with the time.sleep() function in python. I am running a script that needs to wait for another program to generate txt files. Although, this is a terribly old machine, so when I sleep the python script, I run into issues with the other program not generating files. Is there any alternatives to usin...
[ "One way to do a non-blocking wait is to use threading.Event:\nimport threading\ndummy_event = threading.Event()\ndummy_event.wait(timeout=1)\n\nThis can be set() from another thread to indicate that something has completed. But if you are doing stuff in another thread, you could avoid the timeout and event altoget...
[ 7 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003416160_multithreading_python.txt
Q: Anyone know a better way do write this login function in django Hay I was wondering if anyone knew a better way to do this. def login_user(request): username = request.POST.get('username') password = request.POST.get('password') user = User.objects.filter(username=username) if user: user ...
Anyone know a better way do write this login function in django
Hay I was wondering if anyone knew a better way to do this. def login_user(request): username = request.POST.get('username') password = request.POST.get('password') user = User.objects.filter(username=username) if user: user = user[0] if user.password == generate_password(password): ...
[ "Why don't use Django auth default views ?\n", "the only amelioration i see is use get instead of filter (it will save you one line)\nuser = User.objects.get(username=username)\n\n", "Looking at the level of control you want to have, you'll want to make use of the authenticate and maybe login functions in djang...
[ 5, 1, 1, 0 ]
[]
[]
[ "authentication", "django", "python" ]
stackoverflow_0003416182_authentication_django_python.txt
Q: Porting Quartz 2d python demo to pure Core Graphics C let me first off noting that I have absolutely no idea what I'm doing with objective-c and mac development (though I'm fine with c). I made a wonderfully simple graphics utility on leopard with the Quartz-2d binding for python: http://developer.apple.com/graph...
Porting Quartz 2d python demo to pure Core Graphics C
let me first off noting that I have absolutely no idea what I'm doing with objective-c and mac development (though I'm fine with c). I made a wonderfully simple graphics utility on leopard with the Quartz-2d binding for python: http://developer.apple.com/graphicsimaging/pythonandquartz.html that basically inputs a tex...
[ "\nCGImageRef myImage = CGBitmapContextCreateImage (myBitmapContext);// 5\n\nCGContextDrawImage(myBitmapContext, myBoundingBox, myImage);// 6\n\n\nWhat? Why would you capture the contents of the context as an image, and then draw that image back into the context you got it from?\n\n// I'd like to write to a file he...
[ 1 ]
[]
[]
[ "c", "core_graphics", "objective_c", "python", "quartz_2d" ]
stackoverflow_0003420471_c_core_graphics_objective_c_python_quartz_2d.txt
Q: How to handle undecodable filenames in Python? I'd really like to have my Python application deal exclusively with Unicode strings internally. This has been going well for me lately, but I've run into an issue with handling paths. The POSIX API for filesystems isn't Unicode, so it's possible (and actually somewhat...
How to handle undecodable filenames in Python?
I'd really like to have my Python application deal exclusively with Unicode strings internally. This has been going well for me lately, but I've run into an issue with handling paths. The POSIX API for filesystems isn't Unicode, so it's possible (and actually somewhat common) for files to have "undecodable" names: file...
[ "Python does have a solution to the problem, if you're willing to switch to Python 3.1 or later:\nPEP 383 - Non-decodable Bytes in System Character Interfaces.\n", "If you need to store bytestrings in a DB that is geared for UNICODE then it is probably easier to record the bytestrings encoded in hex. That way, th...
[ 5, 2 ]
[]
[]
[ "character_encoding", "filenames", "path", "python", "unicode" ]
stackoverflow_0003409381_character_encoding_filenames_path_python_unicode.txt
Q: What exactly does a non-shallow filecmp.cmp do? I'm using Python 2.6.2. The docs for the filecmp module say: The filecmp module defines functions to compare files and directories, with various optional time/correctness trade-offs. and, of the filecmp.cmp function: filecmp.cmp(f1, f2[, shallow]) Compare the file...
What exactly does a non-shallow filecmp.cmp do?
I'm using Python 2.6.2. The docs for the filecmp module say: The filecmp module defines functions to compare files and directories, with various optional time/correctness trade-offs. and, of the filecmp.cmp function: filecmp.cmp(f1, f2[, shallow]) Compare the files named f1 and f2, returning True if they seem equal,...
[ "Consulting the source filecmp.py reveals that if shallow=False, filecmp.cmp first checks a few select properties of os.stat(), regardless of whether shallow is True or False. If the stat properties that are examined are the same, it returns True. Else, it checks its internal cache to see if the files have already ...
[ 13 ]
[]
[]
[ "filecompare", "python" ]
stackoverflow_0003421523_filecompare_python.txt
Q: How to remove duplicates in Links genrated using mechnize in Python? Here is my code in python which Genrates a list of link objects. I want to remove duplicates form them. cb = list() for link in br.links(url_regex="inquiry-results.jsp"): cb.append(link) print set(cb) But It returns the error unhashable ...
How to remove duplicates in Links genrated using mechnize in Python?
Here is my code in python which Genrates a list of link objects. I want to remove duplicates form them. cb = list() for link in br.links(url_regex="inquiry-results.jsp"): cb.append(link) print set(cb) But It returns the error unhashable instance. link is something like this - Link( base_url='http://casesea...
[ "You can construct a dictionary using URLs as keys and the get its values:\ncb = {}\nfor link in br.links(url_regex=\"inquiry-results.jsp\"):\n cb[link.url] = link\nprint cb.values()\n\n" ]
[ 3 ]
[]
[]
[ "duplicate_removal", "mechanize", "python", "set" ]
stackoverflow_0003421737_duplicate_removal_mechanize_python_set.txt
Q: AttributeError - type object 'Services' has no attribute 'service_price' I'm trying to create something like an invoice program, to create invoices and calculate prices. I am still on the models part and I am trying to calculate all the services includes in a single invoice and update them in Invoices.subtotal. My...
AttributeError - type object 'Services' has no attribute 'service_price'
I'm trying to create something like an invoice program, to create invoices and calculate prices. I am still on the models part and I am trying to calculate all the services includes in a single invoice and update them in Invoices.subtotal. My problem is that I cannot pass the summary value of Services.service_price to ...
[ "You haven't got a summary value anywhere. Services.service_price makes no sense in this context - it's a reference to the model field itself, at the class level, rather than to the value of any particular instance of it.\nYou need some code to calculate the actual value. Bear in mind that you have a ForeignKey fro...
[ 4 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0003422342_django_django_admin_python.txt
Q: Perform an action over 2 and 2 elements in a list I have a list of numbers, say data = [45,34,33,20,16,13,12,3] I'd like to compute the difference between 2 and 2 items, (that is, for the above data I want to compute 45-34,33-20,16-13 and 12-3, what's the python way of doing that ? Also, more generally, how shoul...
Perform an action over 2 and 2 elements in a list
I have a list of numbers, say data = [45,34,33,20,16,13,12,3] I'd like to compute the difference between 2 and 2 items, (that is, for the above data I want to compute 45-34,33-20,16-13 and 12-3, what's the python way of doing that ? Also, more generally, how should I apply a function to 2 and 2 of these elements, that...
[ "Try slicing the list:\nfrom itertools import izip\n[myfunc(a, b) for a, b in izip(data[::2], data[1::2])]\n\nor you can use the fact that izip guarantees the order in which it consumes its arguments:\nidata = iter(data)\n[myfunc(a, b) for a, b in izip(idata, idata)]\n\n", "You could create your own iterator to i...
[ 6, 2, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003422322_python.txt
Q: git server side hooks I am running into a problem when running the follow python script on the server looking for commit information for the push making sure it follows a particular syntax, I am unable to get input from the user which is why the username and password are hard coded. I am now also unable to get the...
git server side hooks
I am running into a problem when running the follow python script on the server looking for commit information for the push making sure it follows a particular syntax, I am unable to get input from the user which is why the username and password are hard coded. I am now also unable to get the list of commit message tha...
[ "I suggest that you have a look at gitorious (http://gitorious.org/gitorious).\nThey use ssh to handle authentication and rights management (getting the username given by ssh).\nThey also have some hooks on git repositories. I guess it could help to see how they are processing git hooks using ruby.\n", "By the ti...
[ 2, 1 ]
[]
[]
[ "git", "githooks", "jira", "python", "ssh" ]
stackoverflow_0003375283_git_githooks_jira_python_ssh.txt
Q: Extracting a tag value in BeautifulSoup when unable to match by position or attributes I'm using BS to scrape a web page and i'm a little stuck with a small problem. Here's a snippet of HTML from the page. <span style="font-family: arial;"><span style="font-weight: bold;">Artist:</span> M.I.A.<br> </span> Once I'...
Extracting a tag value in BeautifulSoup when unable to match by position or attributes
I'm using BS to scrape a web page and i'm a little stuck with a small problem. Here's a snippet of HTML from the page. <span style="font-family: arial;"><span style="font-weight: bold;">Artist:</span> M.I.A.<br> </span> Once I've got the soup, how can I find this tag and get the artist name i.e. M.I.A. I cannot match ...
[ "BeautifulSoup is kind of dead, since SGMLParser is deprecated. I suggest you use the better lxml library -- It even has xpath support!!\nfrom lxml import html\n\ntext = '''\n<span style=\"font-family: arial;\">\n <span style=\"font-weight: bold;\">Artist:</span>M.I.A.<br>\n</span>\n'''\n\ndoc = html.fromstring(...
[ 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003422770_beautifulsoup_python.txt
Q: Comparing local file with remote file I have the following problem: I have a local .zip file and a .zip file located on a server. I need to check if the .zip file on the server is different from the local one; if they are not I need to pull the new one from the server. My question is how do I compare them without ...
Comparing local file with remote file
I have the following problem: I have a local .zip file and a .zip file located on a server. I need to check if the .zip file on the server is different from the local one; if they are not I need to pull the new one from the server. My question is how do I compare them without downloading the file from the server and co...
[ "Short answer: You can't.\nLong answer: To compare with the zip file on the server, someone has to read that file. Either you can do that locally, which would involve pulling it, or you can ask the server to do it for you. Can you run code on the server?\nEdit\nIf you can run Python on the server, why not hash the ...
[ 2, 0, 0 ]
[]
[]
[ "comparison", "md5", "python" ]
stackoverflow_0003423510_comparison_md5_python.txt
Q: Adding same text to two different lists How can I add the same text(s) to two or more different lists? For example, this is what I am doing: >>> msg = 'Do it' >>> first = list() >>> second = list() >>> first.append(msg) >>> second.append(msg) Not only this is causing redundancy, I think it makes for poor code. Is...
Adding same text to two different lists
How can I add the same text(s) to two or more different lists? For example, this is what I am doing: >>> msg = 'Do it' >>> first = list() >>> second = list() >>> first.append(msg) >>> second.append(msg) Not only this is causing redundancy, I think it makes for poor code. Is there any way I can add the same text to two...
[ "first, second = [], []\nfor lst in (first, second):\n lst.append(msg)\n\nBut it would be better if you'd tell us what problem are you solving.\n", "This is inefficient. Why not make one list and then copy() it when you need to differentiate the two?\nmsg = 'Do it'\ntheList = [ ]\ntheList.append( msg )\n# Late...
[ 4, 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003422962_python.txt
Q: python 2.7 / exec / what is wrong? I have this code which runs fine in Python 2.5 but not in 2.7: import sys import traceback try: from io import StringIO except: from StringIO import StringIO def CaptureExec(stmt): oldio = (sys.stdin, sys.stdout, sys.stderr) sio = StringIO() sys.stdout = sys....
python 2.7 / exec / what is wrong?
I have this code which runs fine in Python 2.5 but not in 2.7: import sys import traceback try: from io import StringIO except: from StringIO import StringIO def CaptureExec(stmt): oldio = (sys.stdin, sys.stdout, sys.stderr) sio = StringIO() sys.stdout = sys.stderr = sio try: exec(stmt,...
[ "io.StringIO is confusing in Python 2.7 because it's backported from the 3.x bytes/string world. This code gets the same error as yours:\nfrom io import StringIO\nsio = StringIO()\nsio.write(\"Hello\\n\")\n\ncauses:\nTraceback (most recent call last):\n File \"so2.py\", line 3, in <module>\n sio.write(\"Hello\...
[ 15, 2 ]
[]
[]
[ "exec", "python", "redirect", "stdio", "stringio" ]
stackoverflow_0003423601_exec_python_redirect_stdio_stringio.txt
Q: Dynamic class field creation before metaclass machinery I'm trying to get rid of exec in a code similar to this: class A(object): for field in ['one', 'two', 'three']: exec '%s = "%s value"' % (field, field) ...so that: >>> A.one 'one value' >>> A.two 'two value' >>> A.three 'three value' EDIT: and a...
Dynamic class field creation before metaclass machinery
I'm trying to get rid of exec in a code similar to this: class A(object): for field in ['one', 'two', 'three']: exec '%s = "%s value"' % (field, field) ...so that: >>> A.one 'one value' >>> A.two 'two value' >>> A.three 'three value' EDIT: and also the requirement mentioned in the subject is met i.e. A.on...
[ "Use the setattr function.\nclass A(object):\n pass\n\nfor field in ['one', 'two', 'three']:\n setattr(A, field, field + ' value')\n\n", "I'd just inherit from the metaclass and do it there\nclass MyMetaClass(MetaClass):\n def __new__(meta, classname, baseclasses, classdict):\n fields = classdict['__m...
[ 2, 2, 2, 1, 1, 0 ]
[]
[]
[ "dynamic", "python" ]
stackoverflow_0003423361_dynamic_python.txt
Q: Python: how to change (last) element of tuple? The question is a bit misleading, because a tuple is immutable. What I want is: Having a tuple a = (1, 2, 3, 4) get a tuple b that is exactly like a except for the last argument which is, say, twice the last element of a. => b == (1, 2, 3, 8) A: b = a[:-1] + (a[-1]...
Python: how to change (last) element of tuple?
The question is a bit misleading, because a tuple is immutable. What I want is: Having a tuple a = (1, 2, 3, 4) get a tuple b that is exactly like a except for the last argument which is, say, twice the last element of a. => b == (1, 2, 3, 8)
[ "b = a[:-1] + (a[-1]*2,)\n\nWhat I'm doing here is concatenation of two tuples, the first containing everything but the last element, and a new tuple containing the mutation of the final element. The result is a new tuple containing what you want.\nNote that for + to return a tuple, both operands must be a tuple.\...
[ 22, 8, 5 ]
[]
[]
[ "python" ]
stackoverflow_0003424507_python.txt
Q: python url regexp I have a regexp and i want to add output of regexp to my url for exmaple url = 'blabla.com' r = re.findall(r'<p>(.*?</a>)) r output - /any_string/on/any/server/ but a dont know how to make get-request with regexp output blabla.com/any_string/on/any/server/ A: Don't use regex to parse html. Us...
python url regexp
I have a regexp and i want to add output of regexp to my url for exmaple url = 'blabla.com' r = re.findall(r'<p>(.*?</a>)) r output - /any_string/on/any/server/ but a dont know how to make get-request with regexp output blabla.com/any_string/on/any/server/
[ "Don't use regex to parse html. Use a real parser.\nI suggest using the lxml.html parser. lxml supports xpath, which is a very powerful way of querying structured documents. There's a ready-to-use make_links_absolute() method that does what you ask. It's also very fast.\nAs an example, in this question's page HTML ...
[ 2, 0 ]
[]
[]
[ "python", "regex", "urllib2" ]
stackoverflow_0003423822_python_regex_urllib2.txt
Q: Getting ready to convert from Python 2.x to 3.x As we all know by now (I hope), Python 3 is slowly beginning to replace Python 2.x. Of course it will be many MANY years before most of the existing code is finally ported, but there are things we can do right now in our version 2.x code to make the switch easier. Ob...
Getting ready to convert from Python 2.x to 3.x
As we all know by now (I hope), Python 3 is slowly beginning to replace Python 2.x. Of course it will be many MANY years before most of the existing code is finally ported, but there are things we can do right now in our version 2.x code to make the switch easier. Obviously taking a look at what's new in 3.x will be he...
[ "The biggest problem that cannot be adequately addressed by micro-level changes and 2to3 is the change of the default string type from bytes to Unicode.\nIf your code needs to do anything with encodings and byte I/O, it's going to need a bunch of manual effort to convert correctly, so that things that have to be by...
[ 12, 5 ]
[]
[]
[ "python", "python_2.x", "python_3.x", "upgrade" ]
stackoverflow_0003424292_python_python_2.x_python_3.x_upgrade.txt
Q: Is twisted.internet.reactor global? For example, if one application does from twisted.internet import reactor, and another application does the same, are those reactors the same? I am asking because Deluge, an application that uses twisted, looks like it uses the reactor to connect their UI (gtk) to the rest of th...
Is twisted.internet.reactor global?
For example, if one application does from twisted.internet import reactor, and another application does the same, are those reactors the same? I am asking because Deluge, an application that uses twisted, looks like it uses the reactor to connect their UI (gtk) to the rest of the application being driven by twisted (I ...
[ "Yes, every module in Python is always global, or, to put it better, a singleton: when you do from twisted.internet import reactor, Python's import mechanism first checks sys.modules['twisted.internet.reactor'], and, if that exists, returns said value; only if it doesn't exist (i.e., the first time a module is impo...
[ 14, 2 ]
[]
[]
[ "networking", "python", "reactor", "twisted" ]
stackoverflow_0003424825_networking_python_reactor_twisted.txt
Q: Cherokee + uWSGI + Pylons I have successfully deployed a Django app with uWSGI + Cherokee. However, I want to experiment with Pylons before I go decide on Django. So far I have followed the instructions/recommendations here: Deploying Pylons with uWSGI Paster serve works without a hitch. But when I try to serve vi...
Cherokee + uWSGI + Pylons
I have successfully deployed a Django app with uWSGI + Cherokee. However, I want to experiment with Pylons before I go decide on Django. So far I have followed the instructions/recommendations here: Deploying Pylons with uWSGI Paster serve works without a hitch. But when I try to serve via uWSGI, I get nowhere: /usr/bi...
[ "You should not visit http://localhost:5000. 5000 it's the port use for the communication between Cherokee and uWSGI. So you're trying to access uWSGI directly. You need to configure Cherokee and then go to the address:port you have configured in Cherokee to see your website.\nDocs:\n\nCherokee-uWSGI\nuWSGI\n\n" ]
[ 5 ]
[]
[]
[ "cherokee", "pylons", "python", "uwsgi" ]
stackoverflow_0003423860_cherokee_pylons_python_uwsgi.txt
Q: Problem using MySQLdb on OSX: symbol not found _mysql_affected_rows This is related to a previous question. However, the main posted solution there is not working for me. I'm on Snow Leopard, using the 32-bit 5.1.49 MySQL dmg install. I'm using the built in python (apparently, as noted in the comments, my Python v...
Problem using MySQLdb on OSX: symbol not found _mysql_affected_rows
This is related to a previous question. However, the main posted solution there is not working for me. I'm on Snow Leopard, using the 32-bit 5.1.49 MySQL dmg install. I'm using the built in python (apparently, as noted in the comments, my Python version is different), which appears to be 2.6.5 32-bit: Python 2.6.5 (r2...
[ "The only (admittedly kludgy) solution that I ended up getting to work was to use MySQL-python-1.2.2 after applying this patch, cobbled together from advice found here (http://www.mangoorange.com/2008/08/01/installing-python-mysqldb-122-on-mac-os-x/) and here (http://flo.nigsch.com/?p=62). Sorry for the lack of lin...
[ 0 ]
[]
[]
[ "macos", "mysql", "python" ]
stackoverflow_0003423289_macos_mysql_python.txt
Q: using Python to import a CSV (lookup table) and add GPS coordinates to another output CSV So I have already imported one XML-ish file with 3000 elements and parsed them into a CSV for output. But I also need to import a second CSV file with 'keyword','latitude','longitude' as columns and use it to add the GPS coor...
using Python to import a CSV (lookup table) and add GPS coordinates to another output CSV
So I have already imported one XML-ish file with 3000 elements and parsed them into a CSV for output. But I also need to import a second CSV file with 'keyword','latitude','longitude' as columns and use it to add the GPS coordinates to additional columns on the first file. Reading the python tutorial, it seems like {di...
[ "\nReading the python tutorial, it seems\n like {dictionary} is what I need,\n although I've read on here that tuples\n might be better. I don't know.\n\nThey're both fine choices for this task.\n\nprint row.keys() The output look\n like:\n{'LATITUDE': '-1.311467078',\n\nNo it doesn't! This is the output from ...
[ 1, 0, 0 ]
[]
[]
[ "csv", "dictionary", "geocoding", "gps", "python" ]
stackoverflow_0003424741_csv_dictionary_geocoding_gps_python.txt
Q: Finding the last group in a regular expression Three underscore separated elements make my strings : - first (letters and digits) - middle (letters, digits and underscore) - last (letters and digits) The last element is optional. Note : I need to access my groups by their names, not their indices. Examples : Strin...
Finding the last group in a regular expression
Three underscore separated elements make my strings : - first (letters and digits) - middle (letters, digits and underscore) - last (letters and digits) The last element is optional. Note : I need to access my groups by their names, not their indices. Examples : String : abc_def first : abc middle : def last : None S...
[ "Change the middle group to be non-greedy, and add beginning and end-of-string anchors:\n^(?P<first>[a-z]+)_(?P<middle>\\w+?)(_(?P<last>[a-z]+))?$\n\nBy default, the \\w+will match as much as possible, which eats the rest of the string. Adding the ? tells it to match as little as possible.\nThanks to Tim Pietzcker ...
[ 4, 1, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003425330_python_regex.txt
Q: Python script to convert po file to localized json I need python script to convert po file to localized json. A: you might start here http://docs.python.org/library/gettext.html and here http://docs.python.org/library/json.html A: http://jsgettext.berlios.de/ contains a .po to json converter (p.erl) - for pyth...
Python script to convert po file to localized json
I need python script to convert po file to localized json.
[ "you might start here http://docs.python.org/library/gettext.html and here http://docs.python.org/library/json.html\n", "http://jsgettext.berlios.de/ contains a .po to json converter (p.erl) - for python you can use polib to access .po file contents and transform as desired\n" ]
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002696119_python.txt
Q: A simpler i18n for Python/Django My question is regarding i18n in Python. From what I understand, it involves: Create a messages file per language (ONLY ONE?!). in this file, each message will be of the format English message here Message en Francais ici (yea crappy french..) then have this file compiled into ...
A simpler i18n for Python/Django
My question is regarding i18n in Python. From what I understand, it involves: Create a messages file per language (ONLY ONE?!). in this file, each message will be of the format English message here Message en Francais ici (yea crappy french..) then have this file compiled into another faster binary format repeat f...
[ "While you could do this fairly simply, I would question why. \nAs is:\n\nDjango's i18n is based around gettext, which has never given me any performance problems.\nYou don't have to create the message file, Django will do it for you.\nThe messages files Django creates can be sent as a text file to just about anyo...
[ 13 ]
[]
[]
[ "django", "internationalization", "python" ]
stackoverflow_0003424939_django_internationalization_python.txt
Q: Simple protocols (like twisted.pb) vs messaging (AMQP/JMS) vs web services (REST/SOAP) I'm currently using twisted's perspective broker on python and I have considered in the past switching to something like RabbitMQ but I'm not sure it could just replace pb - I feel like I might be comparing apples to oranges her...
Simple protocols (like twisted.pb) vs messaging (AMQP/JMS) vs web services (REST/SOAP)
I'm currently using twisted's perspective broker on python and I have considered in the past switching to something like RabbitMQ but I'm not sure it could just replace pb - I feel like I might be comparing apples to oranges here. I've been reading a lot about REST lately and the inevitable debate with SOAP, which led ...
[ "As always, \"it depends\". First, let's clear up the terminology.\nTwisted's Perspective Broker basically is a system you can use when you have control over both ends of a distributed action (both client and server ends). It provides a way to copy objects from one end to the other and to call methods on remote obj...
[ 12 ]
[]
[]
[ "amqp", "network_protocols", "python", "twisted", "web_services" ]
stackoverflow_0003421200_amqp_network_protocols_python_twisted_web_services.txt
Q: PYTHONPATH storage location Where is my pythonpath stored? When I write import sys sys.path Where does Python get that data? A: Python gets that data from the path attribute of the sys module. This path is a list, and if you want to add a new directory to the path, just use the append method. For instance, to ...
PYTHONPATH storage location
Where is my pythonpath stored? When I write import sys sys.path Where does Python get that data?
[ "Python gets that data from the path attribute of the sys module. This path is a list, and if you want to add a new directory to the path, just use the append method.\nFor instance, to add the directory /home/me/mypy to the path, just do:\nimport sys\nsys.path.append(\"/home/me/mypy\")\n\n" ]
[ 2 ]
[]
[]
[ "python", "pythonpath" ]
stackoverflow_0003414287_python_pythonpath.txt
Q: Deleting lines in python after I write them Ok here is my existing code: ////////////// = [] for line in datafile: splitline = line.split() for item in splitline: if not item.endswith("JAX"): if item.startswith("STF") or item.startswith("BRACKER"): //////////.append( ite...
Deleting lines in python after I write them
Ok here is my existing code: ////////////// = [] for line in datafile: splitline = line.split() for item in splitline: if not item.endswith("JAX"): if item.startswith("STF") or item.startswith("BRACKER"): //////////.append( item ) for line in ////////// print //////////...
[ "You cannot delete lines in a text file - it would require moving all the data after the deleted line up to fill the gap, and would be massively inefficient.\nOne way to do it is to write a temp file with all the lines you want to keep in bigfile.txt, and when you have finished processing delete bigfile.txt and ren...
[ 1, 0 ]
[]
[]
[ "lines", "python" ]
stackoverflow_0003418310_lines_python.txt
Q: Trying to call readline() on a file object in python but it's pausing I'm using the readline() function to read data from a file object obtained through the subprocess module: proc = subprocess.Popen(cmd, bufsize=0, stdout=subprocess.PIPE). This allows me to use proc.stdout as a file-like object with proc.stdout....
Trying to call readline() on a file object in python but it's pausing
I'm using the readline() function to read data from a file object obtained through the subprocess module: proc = subprocess.Popen(cmd, bufsize=0, stdout=subprocess.PIPE). This allows me to use proc.stdout as a file-like object with proc.stdout.readline(). My issue is that this pauses waiting for input and I'd like i...
[ "On a posix-y platform (basically any popular platform except Windows), the select module offers the right tools for this purpose. Unfortunately, on Windows, select only works on sockets (not on pipes, which is what subprocess.Popen will be using), so the situation is not quite as clear there. Do you need to run ...
[ 3 ]
[]
[]
[ "file", "python", "subprocess", "wait" ]
stackoverflow_0003426250_file_python_subprocess_wait.txt
Q: py-appscript is starting a new Finder instance i have a py2app application, which runs an appscript using py-appscript. the Applescript code is this one line: app('Finder').update(<file alias of a certain file>) What this normally does is update a file's preview in Finder. It works most of the time, except for Leo...
py-appscript is starting a new Finder instance
i have a py2app application, which runs an appscript using py-appscript. the Applescript code is this one line: app('Finder').update(<file alias of a certain file>) What this normally does is update a file's preview in Finder. It works most of the time, except for Leopard. In Leopard, everytime that script is executed,...
[ "Seeing as how py-appscript is a layer between python and the application you are scripting via Applescript, I would suggest porting the statement to pure Applescript and see if it works there. There are a lot of things that can go wrong with Applescript (and your statement alone) to begin with and it's not obvious...
[ 1 ]
[]
[]
[ "applescript", "python" ]
stackoverflow_0003425643_applescript_python.txt
Q: Deploying python executables- PyInstaller, cx-freeze, etc I'm looking to find a way to bundle a python app into stand-alone executables so my windows and mac using friends can use it without installing ugly dependencies. Looking online I've found a few utilities to help do this, including py2exe for windows and py...
Deploying python executables- PyInstaller, cx-freeze, etc
I'm looking to find a way to bundle a python app into stand-alone executables so my windows and mac using friends can use it without installing ugly dependencies. Looking online I've found a few utilities to help do this, including py2exe for windows and py2app for mac, as well as PyInstaller, cx-freeze, and bbfreeze. ...
[ "I've been building a python app with PyQt and PyQwt for the past few weeks and have had the same problem. I found py2app completely impossible to use, I kept running into so many problems constantly that I gave up. A few days later found PyInstaller which is fantastic. It understands both PyQt and PyQwt out of the...
[ 1, 0 ]
[]
[]
[ "deployment", "python" ]
stackoverflow_0003426381_deployment_python.txt
Q: Python/feedparser script won't display on CGI/ character coding #!/usr/bin/python # -*- coding: utf-8 -*- import sys import os import cgi import string import feedparser count = 0 print "Content-Type: text/html\n\n" print """<PRE><B>WORK MAINTENANCE/B></PRE>""" d = feedparser.parse("http://www.hep.hr/ods/rss/rad...
Python/feedparser script won't display on CGI/ character coding
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import os import cgi import string import feedparser count = 0 print "Content-Type: text/html\n\n" print """<PRE><B>WORK MAINTENANCE/B></PRE>""" d = feedparser.parse("http://www.hep.hr/ods/rss/radovi.aspx?dp=zagreb") for opis in d: try: print """<B...
[ "\nfor opis in d:\n try:\n print \"\"\"<B>Place/Time:</B> %s<br>\"\"\" % d.entries[count].title\n\n\nYou're not using 'opis' in your output.\nTry something like this:\nfor entry in d.entries:\n try:\n print \"\"\"<B>Place/Time:</B> %s<br>\"\"\" % entry.title\n ....\n\n", "Oke had anot...
[ 0, 0 ]
[]
[]
[ "cgi", "character_encoding", "feedparser", "python", "ubuntu" ]
stackoverflow_0003393414_cgi_character_encoding_feedparser_python_ubuntu.txt
Q: Simple problem with dicT in Python I have this dicT in my code that contain some positions. position = ['712,352', '712,390', '622,522'] when I'm trying to run this part def MouseMove(x,y): ctypes.windll.user32.SetCursorPos(x,y) with MouseMove(position[0]), the compiler says to me ...
Simple problem with dicT in Python
I have this dicT in my code that contain some positions. position = ['712,352', '712,390', '622,522'] when I'm trying to run this part def MouseMove(x,y): ctypes.windll.user32.SetCursorPos(x,y) with MouseMove(position[0]), the compiler says to me that I need 2 arguments on this command....
[ "It's not a dictionary but a list. Perhaps you mean to do something like this:\nposition = [(712,352), \n (712,390), \n (622,522)]\n\nMouseMove(*position[0])\n\n" ]
[ 5 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003426677_dictionary_python.txt
Q: python regexp help Good day. Little question about reg exp. I have a string look like http://servercom/smth/Age=&amp;Filter=2&amp; How can i cut &amp; with regexp from url? After regexp url-string must be http://server.com/smth/Age=1&Filter=2& A: You don't need regex for that: changed = str.replace('&amp;', '&'...
python regexp help
Good day. Little question about reg exp. I have a string look like http://servercom/smth/Age=&amp;Filter=2&amp; How can i cut &amp; with regexp from url? After regexp url-string must be http://server.com/smth/Age=1&Filter=2&
[ "You don't need regex for that:\nchanged = str.replace('&amp;', '&');\n\nhttp://docs.python.org/library/string.html#string.replace\n", "You are translating XML escaped special characters. Use the standard lib:\n>>> u = \"http://servercom/smth/Age=&amp;Filter=2&amp;\n>>> import xml.sax.saxutils\n>>> xml.sax.saxuti...
[ 5, 2 ]
[]
[]
[ "python", "regex", "url" ]
stackoverflow_0003426675_python_regex_url.txt
Q: What is the Python 'buffer' type for? There is a buffer type in Python, but how can I use it? In the Python documentation about buffer(), the description is: buffer(object[, offset[, size]]) The object argument must be an object that supports the buffer call interface (such as strings, arrays, and buffers). A ne...
What is the Python 'buffer' type for?
There is a buffer type in Python, but how can I use it? In the Python documentation about buffer(), the description is: buffer(object[, offset[, size]]) The object argument must be an object that supports the buffer call interface (such as strings, arrays, and buffers). A new buffer object will be created which refer...
[ "An example usage:\n>>> s = 'Hello world'\n>>> t = buffer(s, 6, 5)\n>>> t\n<read-only buffer for 0x10064a4b0, size 5, offset 6 at 0x100634ab0>\n>>> print t\nworld\n\nThe buffer in this case is a sub-string, starting at position 6 with length 5, and it doesn't take extra storage space - it references a slice of the ...
[ 159, 30 ]
[]
[]
[ "python", "python_2.7" ]
stackoverflow_0003422685_python_python_2.7.txt
Q: All possible combinations of a list of a list I am in desperate need for some algorithm help when combining lists inside lists. Assuming that I have the following data structure: fields = [ ['a1', 'a2', 'a3'], ['b1', 'b2', 'b3'], ['c1', 'c2', 'c3'], ['d1', 'd2', 'd3'] ] I am...
All possible combinations of a list of a list
I am in desperate need for some algorithm help when combining lists inside lists. Assuming that I have the following data structure: fields = [ ['a1', 'a2', 'a3'], ['b1', 'b2', 'b3'], ['c1', 'c2', 'c3'], ['d1', 'd2', 'd3'] ] I am trying to write a generator (Python) that will yie...
[ "Just use itertools.product, it does exactly what you're trying to do. If you're interested in the algorithm, you can always look at the source code.\n", "itertools.product(*fields)\n\n" ]
[ 10, 3 ]
[]
[]
[ "algorithm", "data_structures", "permutation", "python" ]
stackoverflow_0003427232_algorithm_data_structures_permutation_python.txt
Q: How to remove 'None' from an Appended Multidimensional Array using numpy I need to take a csv file and import this data into a multi-dimensional array in python, but I am not sure how to strip the 'None' values out of the array after I have appended my data to the empty array. I first created a structure like this...
How to remove 'None' from an Appended Multidimensional Array using numpy
I need to take a csv file and import this data into a multi-dimensional array in python, but I am not sure how to strip the 'None' values out of the array after I have appended my data to the empty array. I first created a structure like this: storecoeffs = numpy.empty((5,11), dtype='object') This returns an 5 row by...
[ "Why are you allocating an entire array of Nones and appending to that? Is coeffsarray not the array you want?\nEdit\nOh. Use numpy.reshape.\nimport numpy\ncoeffsarray = numpy.reshape( coeffsarray, ( 5, 11 ) )\n\n", "Start with an empty array?\nstorecoeffs = numpy.empty((5,0), dtype='object')\n\n", "why not sim...
[ 1, 1, 1, 1 ]
[]
[]
[ "extract", "multidimensional_array", "numpy", "python", "slice" ]
stackoverflow_0003427036_extract_multidimensional_array_numpy_python_slice.txt
Q: How does Pythonic garbage collection with numpy array appends and deletes? I am trying to adapt the underlying structure of plotting code (matplotlib) that is updated on a timer to go from using Python lists for the plot data to using numpy arrays. I want to be able to lower the time step for the plot as much as p...
How does Pythonic garbage collection with numpy array appends and deletes?
I am trying to adapt the underlying structure of plotting code (matplotlib) that is updated on a timer to go from using Python lists for the plot data to using numpy arrays. I want to be able to lower the time step for the plot as much as possible, and since the data may get up into the thousands of points, I start to ...
[ "The point of automatic memory management is that you don't think about it. In the code that you wrote, the copies will be garbage-collected fine (it's nigh on impossible to confuse Python's memory management). However, because np.append is not in-place, the code will create a new array in memory (containing the co...
[ 10 ]
[]
[]
[ "arrays", "garbage_collection", "memory_management", "numpy", "python" ]
stackoverflow_0003427632_arrays_garbage_collection_memory_management_numpy_python.txt
Q: is there a better way to hold this data then a dictionary of dictionaries of dictionaries? python I am creating a data structure dynamically that holds car information. The dictionary looks something like this: cars = {'toyota': {'prius': {'transmission':'automatic', 'mpg':30, 'misc':[]}}} The outermost dictionar...
is there a better way to hold this data then a dictionary of dictionaries of dictionaries? python
I am creating a data structure dynamically that holds car information. The dictionary looks something like this: cars = {'toyota': {'prius': {'transmission':'automatic', 'mpg':30, 'misc':[]}}} The outermost dictionary contains car brand (toyota, bmw, etc.), the second dictionary contains model (prius, m5, etc.) and th...
[ "As Justin suggested, classes would be ideal.\nYou could easily do something like this:\nclass Car(object):\n def __init__(self, make, model=None, trans=None, mpg=None, misc=None):\n if make == 'Toyta' and model is None:\n model = 'Prius'\n self.make = make\n self.model = model\n ...
[ 12, 5, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003427198_dictionary_python.txt
Q: Where to manually install python files I'm having trouble with setuptools in a larger project where a python package has to be "constructed" from several debian packages (each containing a subpackage of the "main" package). Thus we decided to install the files manully instead of using "setup.py install", but we ar...
Where to manually install python files
I'm having trouble with setuptools in a larger project where a python package has to be "constructed" from several debian packages (each containing a subpackage of the "main" package). Thus we decided to install the files manully instead of using "setup.py install", but we are unsure of the location to use. We first us...
[ "It is kind of hard to say where you need to install your Python packages taking into account that, in fact, you can install it anywhere you want. The best place in my opinion is to put them into /usr/local/share/YOURPACKAGENAME in case it was not installed by apt-get (aptitude etc...). In either case, you have to ...
[ 2 ]
[]
[]
[ "debian", "packaging", "python", "setuptools", "ubuntu" ]
stackoverflow_0003424323_debian_packaging_python_setuptools_ubuntu.txt
Q: What does the unary operator ~ do in numpy? I came across a line of code using Python's numpy that looked like this: ~array([0,1,2,3,4,5,4,3,2,1,0,-1,-2]) And it gave the output: array([-1, -2, -3, -4, -5, -6, -5, -4, -3, -2, -1, 0, 1]) Does the unary operator (~) take an array and apply A -> -(A+1) If so, wh...
What does the unary operator ~ do in numpy?
I came across a line of code using Python's numpy that looked like this: ~array([0,1,2,3,4,5,4,3,2,1,0,-1,-2]) And it gave the output: array([-1, -2, -3, -4, -5, -6, -5, -4, -3, -2, -1, 0, 1]) Does the unary operator (~) take an array and apply A -> -(A+1) If so, whats the point?
[ "Chris Lutz' comment is correct.\n~ is the bitwise negation operator\nIt looks like it turns A to -(A+1) because on many modern computers, negative numbers are represented as the Two's Complement of the corresponding positive integer, where the number is subtracted from 2^(bit length) (that's \"two to the power of ...
[ 14, 4, 2, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0003428014_numpy_python.txt
Q: django shell triggering Postgres idle transaction problems It's not the fault of the django (iPython) shell, actually. The problem is developers who open the django shell ./manage.py shell run through some queries (it often only generates selects), and then either leave the shell running or somehow kill their (ssh...
django shell triggering Postgres idle transaction problems
It's not the fault of the django (iPython) shell, actually. The problem is developers who open the django shell ./manage.py shell run through some queries (it often only generates selects), and then either leave the shell running or somehow kill their (ssh) session (actually, I'm not sure if the latter case leaves the ...
[ "You may always run a cron job, that will call pg_cancel_backend() within the database, for the backends that are idle for longer than e.g. 1 day (of course that depends on the nagios settings).\n" ]
[ 1 ]
[]
[]
[ "django", "ipython", "postgresql", "python" ]
stackoverflow_0003427505_django_ipython_postgresql_python.txt
Q: Pygments in wxPython? Is it at all possible to use Pygments inside of wxPython to provide syntax highlighting? A: Positive. While pygments is originally aimed at CSS output, you can define a pygments formatter to define styles for a wx.StyledTextCtrl for example. I happen to have done that just recently: http://...
Pygments in wxPython?
Is it at all possible to use Pygments inside of wxPython to provide syntax highlighting?
[ "Positive. While pygments is originally aimed at CSS output, you can define a pygments formatter to define styles for a wx.StyledTextCtrl for example. I happen to have done that just recently:\nhttp://relet.net/frog/archives/170\n" ]
[ 4 ]
[]
[]
[ "highlighting", "pygments", "python", "syntax", "wxpython" ]
stackoverflow_0003428193_highlighting_pygments_python_syntax_wxpython.txt
Q: Python os.system() - does it leave history (bash_history,etc.)? I'm using os.system() to invoke some openssl command from my ubuntu box. I specify password in line so it looks like: //python code os.system("openssl enc -aes-256-cbc ... -k password") I need to know if is possible to track this command in some shel...
Python os.system() - does it leave history (bash_history,etc.)?
I'm using os.system() to invoke some openssl command from my ubuntu box. I specify password in line so it looks like: //python code os.system("openssl enc -aes-256-cbc ... -k password") I need to know if is possible to track this command in some shell / bash history file (as it is possible if I type this command into ...
[ "No, bash only logs commands that are entered interactively.\nCommands executed through os.system are not logged anywhere.\n", "No, it does not, however on a multiuser box, passing passwords via command-line parameters is considered bad for security, as other users can (in principle) see them via \"ps\" etc.\nPas...
[ 1, 1, 1 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0003423542_linux_python.txt
Q: Extracting a set of words with the Python/NLTK, then comparing it to a standard English dictionary I have: from __future__ import division import nltk, re, pprint f = open('/home/a/Desktop/Projects/FinnegansWake/JamesJoyce-FinnegansWake.txt') raw = f.read() tokens = nltk.wordpunct_tokenize(raw) text = nltk.Text(to...
Extracting a set of words with the Python/NLTK, then comparing it to a standard English dictionary
I have: from __future__ import division import nltk, re, pprint f = open('/home/a/Desktop/Projects/FinnegansWake/JamesJoyce-FinnegansWake.txt') raw = f.read() tokens = nltk.wordpunct_tokenize(raw) text = nltk.Text(tokens) words = [w.lower() for w in text] f2 = open('/home/a/Desktop/Projects/FinnegansWake/catted-severa...
[ "If your English dictionary is indeed a set (hopefully of lowercased words),\nset(vocab) - english_dictionary\n\ngives you the set of words which are in the vocab set but not in the english_dictionary one. (It's a pity that you turned vocab into a list by that sorted, since you need to turn it back into a set to p...
[ 4 ]
[]
[]
[ "nlp", "nltk", "python", "set", "text" ]
stackoverflow_0003428131_nlp_nltk_python_set_text.txt