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: Why is my data not being represented properly in my SQLAchemy model? I have a peculiar SQLAlchemy ORM problem. This is occurring in a Pylons application, against a Postgresql 8.2 database using psycopg2 as my database driver under SQLAlchemy 0.6.0 (and tried with 0.6.4 as well) I have defined a User model object t...
Why is my data not being represented properly in my SQLAchemy model?
I have a peculiar SQLAlchemy ORM problem. This is occurring in a Pylons application, against a Postgresql 8.2 database using psycopg2 as my database driver under SQLAlchemy 0.6.0 (and tried with 0.6.4 as well) I have defined a User model object that has (at minimum) the following properties: class User(Base): __tab...
[ "I'm not familiar with pylons, but your database returns seem OK (since the email column isn't empty). Is there some sort of caching with pylons?\n", "This is a stab in the dark, but try using Session.commit() instead of self._commit().\n" ]
[ 0, 0 ]
[]
[]
[ "orm", "pylons", "python", "sqlalchemy" ]
stackoverflow_0003752674_orm_pylons_python_sqlalchemy.txt
Q: Print info about exception in python 2.5? Python 2.5 won't let me use this syntax: try: code_that_raises_exception() except Exception as e: print e raise So how should I print information about an exception? Thanks EDIT: I'm writing a plugin for a program that includes kind of a pseudo python interpret...
Print info about exception in python 2.5?
Python 2.5 won't let me use this syntax: try: code_that_raises_exception() except Exception as e: print e raise So how should I print information about an exception? Thanks EDIT: I'm writing a plugin for a program that includes kind of a pseudo python interpreter. It prints print statements but doesn't show...
[ "the 'as' keyword is a python 3 (introduced in 2.6) addition, you need to use a comma:\ntry:\n code_that_raises_exception()\nexcept Exception, e:\n print e\n raise\n\n", "try:\n codethatraises()\nexcept Exception, e:\n print e\n raise\n\nnot as easy to read as the latest and greatest syntax, but ident...
[ 9, 2 ]
[]
[]
[ "exception", "exception_handling", "printing", "python" ]
stackoverflow_0003808812_exception_exception_handling_printing_python.txt
Q: decorator inside class & decorated classmethod without 'self' gives strange results Example code: # -*- coding: utf-8 -*- from functools import wraps class MyClass(object): def __init__(self): pass #decorator inside class def call(f): @wraps(f) def wrapper(*args): print 'Wrapper: ', args ...
decorator inside class & decorated classmethod without 'self' gives strange results
Example code: # -*- coding: utf-8 -*- from functools import wraps class MyClass(object): def __init__(self): pass #decorator inside class def call(f): @wraps(f) def wrapper(*args): print 'Wrapper: ', args return wrapper #decorated 'method' without self @call def myfunc(a): pass...
[ "This is perfectly normal.\nThe function myfunc is replacecd by an instance of wrapper. The signature of wrapper is (*args). because it is a bound method, the first argument is the instance of MyClass which is printed out after the string `Wrapper: '.\nWhat's confusing you?\nIt's worth noting that if you use call a...
[ 1, 1 ]
[]
[]
[ "class", "decorator", "python" ]
stackoverflow_0003808967_class_decorator_python.txt
Q: Jinja2 PackageLoader on google app engine I want to use jinja2.PackageLoader on Google App engine, but that appears to depend on pkg_resources, which wasn't added until Python 2.6. Am I Out of luck? A: You should be able to include pkg_resources.py in your application directory (or elsewhere in sys.path if you'...
Jinja2 PackageLoader on google app engine
I want to use jinja2.PackageLoader on Google App engine, but that appears to depend on pkg_resources, which wasn't added until Python 2.6. Am I Out of luck?
[ "You should be able to include pkg_resources.py in your application directory (or elsewhere in sys.path if you're modifying it in your scripts); according to Guido it should work since App Engine 1.2.1.\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "jinja2", "python" ]
stackoverflow_0003809304_google_app_engine_jinja2_python.txt
Q: Is the Python standard library really standard? Is the Python standard library standard in the sense that if Python is installed, then the standard library is installed too? The documentation reads For Unix-like operating systems Python is normally provided as a collection of packages, so it may be necessary to u...
Is the Python standard library really standard?
Is the Python standard library standard in the sense that if Python is installed, then the standard library is installed too? The documentation reads For Unix-like operating systems Python is normally provided as a collection of packages, so it may be necessary to use the packaging tools provided with the operating sy...
[ "It's not a Python issue. You can teach that the batteries are included. They are.\nIt's the distributions that are incomplete.\nWe've been unhappy with the Red Hat Enterprise Linux having old versions of Python. However, there are recipes for upgrades.\nIt's a common security practice to turn off all developer ...
[ 8, 6, 2 ]
[]
[]
[ "python", "standard_library" ]
stackoverflow_0003807111_python_standard_library.txt
Q: Best data structure for dictionary in Java (and also Python) Here is my requirement: Input: Random String of sufficiently long ex: fdjhkajajkfdj Output: fdj has a 2 occurences and separated by x chars I want to put all three letter words in an array and check if they are the same Eg: a[0] = fdj a[1] = djh a[2]...
Best data structure for dictionary in Java (and also Python)
Here is my requirement: Input: Random String of sufficiently long ex: fdjhkajajkfdj Output: fdj has a 2 occurences and separated by x chars I want to put all three letter words in an array and check if they are the same Eg: a[0] = fdj a[1] = djh a[2] = jhk a[3] = hka a[4] = kaj . . . a[n] =fdj My answer is a[0] an...
[ "In Java you could use the Map interface ( http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.html )\nI would use HashMap so that the key is the 3 letter word and the value is the count of occurances. Here's some sample pseudo code\nHashMap<String, int> wordCountMap = new HashMap<String, int>();\nfor(.....
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "java", "python" ]
stackoverflow_0003809308_java_python.txt
Q: How to configure ipy_user_conf.py to get IPython to to start with the right IDLE set as editor? 64-bit Vista Python 2.6 IPython 0.10 Also have Python 2.7 and 3.1 My ipy_user_conf.py has example lines showing how to set an editor. I've tried ipy_editors.idle() but [C:Python26/Scripts] |4>ed xxx.py Editing... > C:...
How to configure ipy_user_conf.py to get IPython to to start with the right IDLE set as editor?
64-bit Vista Python 2.6 IPython 0.10 Also have Python 2.7 and 3.1 My ipy_user_conf.py has example lines showing how to set an editor. I've tried ipy_editors.idle() but [C:Python26/Scripts] |4>ed xxx.py Editing... > C:\Python26\lib\idlelib/idle.py "xxx.py" opens the IDLE for Python 3.1, and doesn't open xxx.py. I next...
[ "The most likely cause is Windows' file name extension associations. I'm guessing Python 3.1 was the last version of python that you installed, so by default, .py and .pyw are now associated with the 3.1 executable. (One way you can verify which python version is associated with the .py/.pyw extensions is to run as...
[ 1 ]
[]
[]
[ "ipython", "python", "vista64" ]
stackoverflow_0003809703_ipython_python_vista64.txt
Q: Python; reading file and finding desired text Need to create a function with two params, a filename to open and a pattern. The pattern will be a search string. Eg. the function will open sentence.txt that has something like "The quick brown fox" (can possibly be more than one line) The pattern will be "brown fox" ...
Python; reading file and finding desired text
Need to create a function with two params, a filename to open and a pattern. The pattern will be a search string. Eg. the function will open sentence.txt that has something like "The quick brown fox" (can possibly be more than one line) The pattern will be "brown fox" So if found, as this will be, it should return a li...
[ "you can simulate simple \"grep\" with the \"in\" operator\ndef grep(filename, pattern):\n for n,line in enumerate(open(filename)):\n if pattern in line:\n print line, n\n\nTo get index, you can use str.index() or str.find()\n", "Here's a very simple grep. You could hack it out to use regula...
[ 3, 1 ]
[]
[]
[ "file", "python", "search" ]
stackoverflow_0003809373_file_python_search.txt
Q: Mac Ports Python 2.6.6 and Tkinter I apologize if this has been asked but does Tkinter work in Python 2.6.6 when installed with Mac Ports? Or do I need to pass the no_tkinter variant? Thanks for any help! A: As of MacPorts python26 @2.6.6_0 and tk @8.5.8_0, Tkinter appears to only work if you don't mind using an...
Mac Ports Python 2.6.6 and Tkinter
I apologize if this has been asked but does Tkinter work in Python 2.6.6 when installed with Mac Ports? Or do I need to pass the no_tkinter variant? Thanks for any help!
[ "As of MacPorts python26 @2.6.6_0 and tk @8.5.8_0, Tkinter appears to only work if you don't mind using an X11-based Tk. There is a +quartz variant for the Tk port which does not require X11 but it is not yet supported in 64-bit mode, the preferred build and execution architecture on OS X 10.6, and at the moment i...
[ 2, 0 ]
[]
[]
[ "macports", "python", "tkinter" ]
stackoverflow_0003808807_macports_python_tkinter.txt
Q: Python for indexing and searching using a cluster? After an unfortunate misadventure with MySQL, I finally gave up on using it. What I have? Large set of files in the following format: ID1: String String String String ID2: String String String String ID3: String String String String ID4: String String String Stri...
Python for indexing and searching using a cluster?
After an unfortunate misadventure with MySQL, I finally gave up on using it. What I have? Large set of files in the following format: ID1: String String String String ID2: String String String String ID3: String String String String ID4: String String String String What I did? Used MySQL on a powerful machine to impo...
[ "For the requirement of looking up which IDs are associated with a given string, I suggest inverting the ID/string relation so the records are keyed by unique strings and the associated data is a sequence of IDs. A string lookup can the be implemented by either a binary search if sorted, or a hash algorithm. This ...
[ 1, 0 ]
[]
[]
[ "cluster_computing", "distributed", "indexing", "python", "search" ]
stackoverflow_0003809891_cluster_computing_distributed_indexing_python_search.txt
Q: Most efficient way to add new keys or append to old keys in a dictionary during iteration in Python? Here's a common situation when compiling data in dictionaries from different sources: Say you have a dictionary that stores lists of things, such as things I like: likes = { 'colors': ['blue','red','purple'], ...
Most efficient way to add new keys or append to old keys in a dictionary during iteration in Python?
Here's a common situation when compiling data in dictionaries from different sources: Say you have a dictionary that stores lists of things, such as things I like: likes = { 'colors': ['blue','red','purple'], 'foods': ['apples', 'oranges'] } and a second dictionary with some related values in it: favorites = ...
[ "Use collections.defaultdict, where the default value is a new list instance.\n>>> import collections\n>>> mydict = collections.defaultdict(list)\n\nIn this way calling .append(...) will always succeed, because in case of a non-existing key append will be called on a fresh empty list.\nYou can instantiate the defau...
[ 5, 3, 2, 1, 1 ]
[]
[]
[ "iteration", "python" ]
stackoverflow_0001553467_iteration_python.txt
Q: Appengine - Reportlab (Get Photo from Model) I´m using Reportlab to generate a PDF. Can´t retrieve a photo from a model. #Personal Info p.drawImage('myPhoto.jpg', 40, 730) p.drawString(50, 670, 'Your name:' + '%s' % user.name) p.drawImage (50, 640, 'Photo: %s' % (user.photo)) When i create on...
Appengine - Reportlab (Get Photo from Model)
I´m using Reportlab to generate a PDF. Can´t retrieve a photo from a model. #Personal Info p.drawImage('myPhoto.jpg', 40, 730) p.drawString(50, 670, 'Your name:' + '%s' % user.name) p.drawImage (50, 640, 'Photo: %s' % (user.photo)) When i create on generate PDF, i got this error: Traceback (most r...
[ "According to the ReportLab API reference, drawImage() has arguments 'image, x, y', whereas it looks as though you are passing 'x, y, string'.\nThe image argument to drawImage() requires a filename or ImageReader.\nAccording to this post, the ImageReader constructor can take several types of arguments.\nUpdate:\nIn...
[ 12 ]
[]
[]
[ "django_models", "google_app_engine", "python", "reportlab" ]
stackoverflow_0003798885_django_models_google_app_engine_python_reportlab.txt
Q: Python unicode popen or Popen error reading unicode I have a program that generates the following output: ┌───────────────────────┐ │10 day weather forecast│ └───────────────────────┘ ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ Tonight Sep 27 Clear ...
Python unicode popen or Popen error reading unicode
I have a program that generates the following output: ┌───────────────────────┐ │10 day weather forecast│ └───────────────────────┘ ▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁ Tonight Sep 27 Clear 54 0 % Tue Sep 28 Sunny 85/61...
[ "I'd say running your program from the console should work correctly because Python can guess the console encoding of the terminal window (cp437 on US Windows), but when run through a pipe Python uses the default of ascii. Try changing your program to encode all Unicode output to an explicit encoding, such as:\npr...
[ 2 ]
[]
[]
[ "popen", "python", "shell", "unicode" ]
stackoverflow_0003810302_popen_python_shell_unicode.txt
Q: Using python in android to interface to sql I know you can use python and other scripting languages in android. But I haven't seen weather or not it was possible to use python as an interface to sqlite in android. Is this possible? This is the first android app where I've needed sqlite, and using the java api's is...
Using python in android to interface to sql
I know you can use python and other scripting languages in android. But I haven't seen weather or not it was possible to use python as an interface to sqlite in android. Is this possible? This is the first android app where I've needed sqlite, and using the java api's is retarded. If this isn't possible, can someone po...
[ "Actually you just need 3 classes:\nA ContentProvider, as found here: http://developer.android.com/guide/topics/providers/content-providers.html\nSecond you need is a SQLiteOpenHelper and last but not least a Cursor\nEdit: Just noticed it's not obvious from the snippets what the db variable is. It's the SQLiteOpenH...
[ 1 ]
[]
[]
[ "android", "android_scripting", "python", "sqlite" ]
stackoverflow_0003800944_android_android_scripting_python_sqlite.txt
Q: Optimizing mean in python I have a function which updates the centroid (mean) in a K-means algoritm. I ran a profiler and noticed that this function uses a lot of computing time. It looks like: def updateCentroid(self, label): X=[]; Y=[] for point in self.clusters[label].points: X.append(point.x) ...
Optimizing mean in python
I have a function which updates the centroid (mean) in a K-means algoritm. I ran a profiler and noticed that this function uses a lot of computing time. It looks like: def updateCentroid(self, label): X=[]; Y=[] for point in self.clusters[label].points: X.append(point.x) Y.append(point.y) se...
[ "A K-means algorithm is already implemented in scipy.cluster.vq. If there is something about that implementation that you are trying to change, then I'd suggest start by studying the code there:\nIn [62]: import scipy.cluster.vq as scv\nIn [64]: scv.__file__\nOut[64]: '/usr/lib/python2.6/dist-packages/scipy/cluster...
[ 5, 3, 3, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "numpy", "optimization", "python" ]
stackoverflow_0003803673_numpy_optimization_python.txt
Q: Regular expression for string between two strings? Sorry, I know this is probably a duplicate but having searched for 'python regular expression match between' I haven't found anything that answers my question! The document (which to make clear, is a long HTML page) I'm searching has a whole bunch of strings in i...
Regular expression for string between two strings?
Sorry, I know this is probably a duplicate but having searched for 'python regular expression match between' I haven't found anything that answers my question! The document (which to make clear, is a long HTML page) I'm searching has a whole bunch of strings in it (inside a JavaScript function) that look like this: li...
[ "The answer to your question depends on how the rest of the string may look like. If they are all like this link: '<URL>'}; then you can do it very simple using simple string manipulation:\nmyString = \"link: '/Hidden/SidebySideGreen/dei1=1204970159862'};\"\nprint( myString[7:-3] )\n\n(If you just have one string w...
[ 3, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003811064_python_regex.txt
Q: Error when the Email formencode validator I wanted to create an IDN-aware formencode validator to use in one of my projects. I used a portion of code from the Django project (http://code.djangoproject.com/svn/django/trunk/django/core/validators.py) to do that, but there must be a trivial error in my code I can't f...
Error when the Email formencode validator
I wanted to create an IDN-aware formencode validator to use in one of my projects. I used a portion of code from the Django project (http://code.djangoproject.com/svn/django/trunk/django/core/validators.py) to do that, but there must be a trivial error in my code I can't find : class Email(formencode.validators.Email):...
[ "Okay, found the answer. I was overloading _to_python instead of validate_python. The class now looks like :\nclass Email(formencode.validators.Email):\n def validate_python(self, value, state):\n try:\n super(Email, self).validate_python(value, state)\n except formencode.Invalid as e:\n...
[ 0 ]
[]
[]
[ "formencode", "python" ]
stackoverflow_0003808698_formencode_python.txt
Q: executemany problem, MySQLdb I'm using MySQLdb and run into the following problem: STMT="""INSERT INTO test_table VALUES (%s, %s, %s, %s, %s)""" rows=[('Wed Apr 14 14:00:00 2010', 23L, -2.3, 4.41, 0.83923)] conn.cursor().executemay(STMT, rows) results in: Traceback (most recent call last): File "run.py", line ...
executemany problem, MySQLdb
I'm using MySQLdb and run into the following problem: STMT="""INSERT INTO test_table VALUES (%s, %s, %s, %s, %s)""" rows=[('Wed Apr 14 14:00:00 2010', 23L, -2.3, 4.41, 0.83923)] conn.cursor().executemay(STMT, rows) results in: Traceback (most recent call last): File "run.py", line 122, in <module> File "C:\Python...
[ "Try to write all columns in your INSERT explicitly:\nSTMT = 'INSERT INTO test_table (col1, col2, col3, col4, col5) VALUES (%s, %s, %s, %s, %s)'\n\n", "How many columns are there altogether in test_table? Probably not 5, judging from the error. Try running SHOW CREATE TABLE test_table to see how the table is defi...
[ 2, 1 ]
[]
[]
[ "api", "database", "mysql", "python", "sql" ]
stackoverflow_0003811431_api_database_mysql_python_sql.txt
Q: Running Python-script in thread and redirecting std.out/std.err to wx.TextCtrl in GUI I'm trying to write a GUI that reads in settings for a python-script, then generates the script and runs it. The script can take dozens of minutes to run so in order to not block the GUI and frustrate the user I'm running it in a...
Running Python-script in thread and redirecting std.out/std.err to wx.TextCtrl in GUI
I'm trying to write a GUI that reads in settings for a python-script, then generates the script and runs it. The script can take dozens of minutes to run so in order to not block the GUI and frustrate the user I'm running it in a separate thread. Before I did this I used a separate class to redirect the std.out and std...
[ "Yeah. From the thread, use wx.CallAfter to send the text to the GUI to a thread-safe way. Then it can take the text and display it. Another way to do it would be to use subprocess and communicate with that. There's an example of that here:\nhttp://www.blog.pythonlibrary.org/2010/06/05/python-running-ping-tracerout...
[ 2, 2 ]
[]
[]
[ "multithreading", "python", "redirect", "user_interface", "wxpython" ]
stackoverflow_0003556290_multithreading_python_redirect_user_interface_wxpython.txt
Q: Buildout + Nose failing with passed options options After running a buildout operation on my project, I can run nose with the following command: # ./bin/nosetests ---------------------------------------------------------------------- Ran 0 tests in 0.310s However, when I try to pass options (such as -w for the b...
Buildout + Nose failing with passed options options
After running a buildout operation on my project, I can run nose with the following command: # ./bin/nosetests ---------------------------------------------------------------------- Ran 0 tests in 0.310s However, when I try to pass options (such as -w for the base directory, I get the following: # ./bin/nosetests -vv...
[ "You can use noserunner buildout recipe\nHere is example buildout.cfg:\n[buildout]\nparts = test\nindex = http://download.zope.org/simple\n\n[test]\nrecipe = pbp.recipe.noserunner\neggs = pbp.recipe.noserunner\nworking-directory = ${buildout:directory}\n\nThis will create script test in bin directory. Runner will r...
[ 5 ]
[]
[]
[ "buildout", "nose", "python" ]
stackoverflow_0003557865_buildout_nose_python.txt
Q: Creating a website to communicate with an embedded device I'm currently working on a project where I'm trying to control an embedded device through an Internet facing website. The idea is is that a user can go to a website and tell this device to preform some kind of action. An action on the website would be trans...
Creating a website to communicate with an embedded device
I'm currently working on a project where I'm trying to control an embedded device through an Internet facing website. The idea is is that a user can go to a website and tell this device to preform some kind of action. An action on the website would be translated into a series of CLI commands and then sent to the device...
[ "You can simply register a dynamic host name using a provider like DynDNS and have the device update it's IP on that website so the dynamic hostname always points to the device IP - there are plenty of clients, scripts etc. available for Linux that do just that.\n", "If the server is going to be static, you could...
[ 3, 3, 2, 0 ]
[]
[]
[ "apache", "beagleboard", "embedded", "python" ]
stackoverflow_0003808581_apache_beagleboard_embedded_python.txt
Q: Python RE - different matching for finditer and findall here is some code: >>> p = re.compile(r'\S+ (\[CC\] )+\S+') >>> s1 = 'always look [CC] on the bright side' >>> s2 = 'always look [CC] [CC] on the bright side' >>> s3 = 'always look [CC] on the [CC] bright side' >>> m1 = p.search(s1) >>> m1.group() 'look [CC] ...
Python RE - different matching for finditer and findall
here is some code: >>> p = re.compile(r'\S+ (\[CC\] )+\S+') >>> s1 = 'always look [CC] on the bright side' >>> s2 = 'always look [CC] [CC] on the bright side' >>> s3 = 'always look [CC] on the [CC] bright side' >>> m1 = p.search(s1) >>> m1.group() 'look [CC] on' >>> p.findall(s1) ['[CC] '] >>> itr = p.finditer(s1) >>> ...
[ "i.group() returns the whole match, including the non-whitespace characters before and after your group. To get the same result as in your findall example, use i.group(1)\nhttp://docs.python.org/library/re.html#re.MatchObject.group\nIn [4]: for i in p.finditer(s1):\n...: i.group(1)\n...: \n...: \nOut[4]...
[ 1 ]
[]
[]
[ "findall", "python", "regex" ]
stackoverflow_0003811743_findall_python_regex.txt
Q: Fastest way to calculate euclidian distance in 2D space What is the fastes way of determening which point q out of n points in 2D space is the closest (smallest euclidian distance) to point p, see attached imgage. My current method of doing this in Python is storing all the distances in a list and then running n...
Fastest way to calculate euclidian distance in 2D space
What is the fastes way of determening which point q out of n points in 2D space is the closest (smallest euclidian distance) to point p, see attached imgage. My current method of doing this in Python is storing all the distances in a list and then running numpy.argmin(list_of_distances) This is however a bit slow wh...
[ "Instead of calculating the distances, you could calculate the squared distances. That way you don't need to perform n * m square roots.\n", "This falls under closest point query -problems. \nHow many points are expected? Are your points static or do they change? One naive but powerful approach for static points ...
[ 5, 4, 1 ]
[]
[]
[ "distance", "optimization", "python" ]
stackoverflow_0003811621_distance_optimization_python.txt
Q: Why would it be important that a content delivery network uses a "reverse caching proxy"? I was reading a description of a project on Github that is a Python-based content delivery network. Why is it important that it uses a "reverse caching proxy" - and what does that mean in this context? A: I think you have t...
Why would it be important that a content delivery network uses a "reverse caching proxy"?
I was reading a description of a project on Github that is a Python-based content delivery network. Why is it important that it uses a "reverse caching proxy" - and what does that mean in this context?
[ "I think you have the question backwards. It would make more sense to ask \"Why would it be important that a reverse caching proxy uses a CDN ?\".\nTypically you put a reverse caching proxy in front of a web server. All inbound requests go through the proxy which may or may not pass the request to the web server.\n...
[ 2 ]
[]
[]
[ "caching", "content_delivery_network", "google_app_engine", "python", "reverse_proxy" ]
stackoverflow_0003811665_caching_content_delivery_network_google_app_engine_python_reverse_proxy.txt
Q: Deleting rows in a ManyToMany intermediate table I have two tables with a ManyToMany relation between them. Sometimes I need to refresh the database so I delete elements from both tables. However relations between deleted rows are still stored inside the automatically created intermediary table. To clarify the pro...
Deleting rows in a ManyToMany intermediate table
I have two tables with a ManyToMany relation between them. Sometimes I need to refresh the database so I delete elements from both tables. However relations between deleted rows are still stored inside the automatically created intermediary table. To clarify the problem, here is a small code: from elixir import * meta...
[ "I think I have found the answer. \nFirst, the problem is the same with sqlalchemy alone. \nThen, this seems only to happen when using this syntax:\nsession.query(B).delete()\n\nBut one can obtain the desired behavior by using:\nsession.delete(b) #where b is an instance of B\n\nA simple iteration of session.delete...
[ 1 ]
[]
[]
[ "orm", "python", "python_elixir", "sqlalchemy", "sqlite" ]
stackoverflow_0003808632_orm_python_python_elixir_sqlalchemy_sqlite.txt
Q: How to strip " (quotes) from post data I have a textbox. When the user enters the " symbol. I had to strip that symbol before storing into the database. Django code: postDict = request.POST.copy() profile = quser.get_profile() profile.i_like= postDict['value'] profile=profile.save() A: No, you need to esc...
How to strip " (quotes) from post data
I have a textbox. When the user enters the " symbol. I had to strip that symbol before storing into the database. Django code: postDict = request.POST.copy() profile = quser.get_profile() profile.i_like= postDict['value'] profile=profile.save()
[ "No, you need to escape the quotes, not strip them. Depending on your database, functions such as mysql_real_escape_sting() will do this\n(assumption, you're using PHP because you've tagged this question \"PHP\")\n", "(Python answer) You can either remove the quotes by simply replacing them in the string (by usin...
[ 1, 1, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003812462_django_python.txt
Q: Using Pip, how do I force upgrade non-upgraded packages only? When running Pip with a requirements.txt file which has fixed versions, we get the following error (or similar): VersionConflict: (solrpy 0.9.1 (.../lib/python2.6/site-packages/solrpy-0.9.1-py2.6.egg), Requirement.parse('solrpy==0.9.3')) because t...
Using Pip, how do I force upgrade non-upgraded packages only?
When running Pip with a requirements.txt file which has fixed versions, we get the following error (or similar): VersionConflict: (solrpy 0.9.1 (.../lib/python2.6/site-packages/solrpy-0.9.1-py2.6.egg), Requirement.parse('solrpy==0.9.3')) because the version conflicts. Using pip install -U -r requirements.txt fixe...
[ "Seems there is an outstanding bug for this: http://bitbucket.org/ianb/pip/issue/13/\n" ]
[ 1 ]
[ "Upgrade the solrpy package separately:\npip install -U --no-deps solrpy\n\nI think you can probably omit the --no-deps parameter, but you might want to try this first, and the former second, if you have problems:\npip install -U solrpy\n\nI don't believe there is a way to just update higher versioned packaged alre...
[ -1 ]
[ "pip", "python", "setuptools" ]
stackoverflow_0003812133_pip_python_setuptools.txt
Q: Are there any basic standards and practices for making human readable code? More specifically making HTML, Java, and python more readable? Does anyone have suggestions for this programming student? A: Make sure your code is well structured (proper indentation, blank lines to separate sections of code, etc.) and ...
Are there any basic standards and practices for making human readable code?
More specifically making HTML, Java, and python more readable? Does anyone have suggestions for this programming student?
[ "Make sure your code is well structured (proper indentation, blank lines to separate sections of code, etc.) and use standard, consistent, and fully named (rather than incomprehensible abbreviated) variable names.\nOthers would suggest using proper comments. I would tend to disagree. If your code is well structured...
[ 5, 5, 5, 5, 3, 3, 2, 2, 1 ]
[]
[]
[ "html", "human_readable", "java", "python" ]
stackoverflow_0003812778_html_human_readable_java_python.txt
Q: Python socket programming How can I know if a node that is being accessed using TCP socket is alive or if the connection was interrupted and other errors? Thanks! A: You can't. Any intermediate nodes can drop your packets or the reply packets from the remote node.
Python socket programming
How can I know if a node that is being accessed using TCP socket is alive or if the connection was interrupted and other errors? Thanks!
[ "You can't. Any intermediate nodes can drop your packets or the reply packets from the remote node.\n" ]
[ 2 ]
[]
[]
[ "distributed", "python", "sockets", "system" ]
stackoverflow_0003813451_distributed_python_sockets_system.txt
Q: Proper way to create an abstraction layer in python I have a project I'm working on (http://github.com/lusis/vogeler). One of the goals is to provide swappable persistance and messaging backends. I think I have a workable model in place but wanted to get input from the Python crowd about best practices. You can se...
Proper way to create an abstraction layer in python
I have a project I'm working on (http://github.com/lusis/vogeler). One of the goals is to provide swappable persistance and messaging backends. I think I have a workable model in place but wanted to get input from the Python crowd about best practices. You can see the new implementation here: http://github.com/lusis/vo...
[ "I think, by convention, the single underscore is a hint that the attribute is an implementation detail that may be changed in the future. Subclasses should not override or invoke underscored methods, because their presence may not be relied on.\nSo, I'd change the underscored methods to hooks: _update --> update_h...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003813577_python.txt
Q: Interesting Python Idiom for removing the only item in a single entry list Stumbled across this today, thought it might be worthy of discussing. Python idiom for taking the single item from a list It sometimes happens in code that I have a list, let’s call it stuff, and I know for certain that this list c...
Interesting Python Idiom for removing the only item in a single entry list
Stumbled across this today, thought it might be worthy of discussing. Python idiom for taking the single item from a list It sometimes happens in code that I have a list, let’s call it stuff, and I know for certain that this list contains exactly one item. And I want to get this item and put it in a variab...
[ "The blog poster wants a single statement to function as (1) extracting an item from a list, (2) an assert, and (3) as a comment telling the user that the list has only one item. \nI'm a huge fan of minimizing the number of lines of code, but I vastly prefer the following:\nassert len(stuff) == 1, \"stuff should h...
[ 7, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003812858_python.txt
Q: how to set namespace prefixes in xml.etree I wish to set the namespace prefix in xml.etree. I found register_namespace(prefix, url) on the Web but this threw "unknown attribute". I have also tried nsmap=NSMAP but this also fails. I'd be grateful for example syntax that shows how to add specified namespace prefixes...
how to set namespace prefixes in xml.etree
I wish to set the namespace prefix in xml.etree. I found register_namespace(prefix, url) on the Web but this threw "unknown attribute". I have also tried nsmap=NSMAP but this also fails. I'd be grateful for example syntax that shows how to add specified namespace prefixes
[ "register_namespace was only introduced in lxml 2.3 (still beta)\nI believe you can provide an nsmap parameter (dictionary with prefix-uri mappings) when creating an element, but I don't think you can change it for an existing element. (there is an .nsmap property on the element, but changing that doesn't seem to w...
[ 1 ]
[]
[]
[ "python", "xml.etree" ]
stackoverflow_0003814365_python_xml.etree.txt
Q: How to mock chained function calls in python? I'm using the mock library written by Michael Foord to help with my testing on a django application. I'd like to test that I'm setting up my query properly, but I don't think I need to actually hit the database, so I'm trying to mock out the query. I can mock out the f...
How to mock chained function calls in python?
I'm using the mock library written by Michael Foord to help with my testing on a django application. I'd like to test that I'm setting up my query properly, but I don't think I need to actually hit the database, so I'm trying to mock out the query. I can mock out the first part of the query just fine, but I am not gett...
[ "Each mock object holds onto the mock object that it returned when it is called. You can get a hold of it using your mock object's return_value property.\nFor your example, \nself.assertTrue(query_mock.distinct.called)\n\ndistinct wasn't called on your mock, it was called on the return value of the filter method of...
[ 24 ]
[]
[]
[ "django", "mocking", "python" ]
stackoverflow_0003813688_django_mocking_python.txt
Q: I am writing a scraper that downloads all the image files from a multiple pages across the same site and saves them to a specific folder the pages have only one variable which changes, and each page only holds one image. (example: http://www.example.com/photos/ooo1.jpg ...http://www.example.com/photos/1745.jpg) ...
I am writing a scraper that downloads all the image files from a multiple pages across the same site and saves them to a specific folder
the pages have only one variable which changes, and each page only holds one image. (example: http://www.example.com/photos/ooo1.jpg ...http://www.example.com/photos/1745.jpg) I'm currently building the script with python and beautfulSoup but am having a problem creating a loop with the changing variable. I just gett...
[ "for i in xrange(1, 1746):\n file = urllib2.urlopen(\"http://www.example.com/photos/%04d.jpg\" % i)\n ...\n # Write file locally\n ...\n\nYou don't need Beautiful soup if you already know the image urls.\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "html", "python" ]
stackoverflow_0003815016_beautifulsoup_html_python.txt
Q: Implementing C's enum and union in python I'm trying to figure out some C code so that I can port it into python. The code is for reading a proprietary binary data file format. It has been straightforward thus far -- it's mainly been structs and I have been using the struct library to ask for particular ctypes fro...
Implementing C's enum and union in python
I'm trying to figure out some C code so that I can port it into python. The code is for reading a proprietary binary data file format. It has been straightforward thus far -- it's mainly been structs and I have been using the struct library to ask for particular ctypes from the file. However, I just came up on this bit...
[ "Enums: There are no enums in the language. Various idioms have been proposed, but none is really widespread. The most straightforward (and in this case sufficient) solution is\nTEEG_EVENT_TAB1 = 1\nTEEG_EVENT_TAB2 = 2\n\nUnions: ctypes has unions.\nThe fieldname : n syntax is called a bitfield and, yeah, does mean...
[ 8, 2, 0, 0 ]
[]
[]
[ "c", "python", "struct", "unions" ]
stackoverflow_0003814952_c_python_struct_unions.txt
Q: Ways to Move up and Down the dir structure in Python #Moving up/down dir structure print os.listdir('.') print os.listdir('..') print os.listdir('../..') Any othe ways??? I got saving dirs before going deeper, then reassigning later. A: This should do the trick: for root, dirs, files in os.walk(os.getcwd()): ...
Ways to Move up and Down the dir structure in Python
#Moving up/down dir structure print os.listdir('.') print os.listdir('..') print os.listdir('../..') Any othe ways??? I got saving dirs before going deeper, then reassigning later.
[ "This should do the trick:\nfor root, dirs, files in os.walk(os.getcwd()):\n for name in dirs:\n try:\n os.rmdir(os.path.join(root, name))\n except WindowsError:\n print 'Skipping', os.path.join(root, name)\n\nThis will walk the file system beginning in the directory the scrip...
[ 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003806562_python.txt
Q: Running Python Scripts From MS Office I have installed PythonWin installed.. I can read and write to Excel from Python, not a problem. Not the usage I need. All examples I have found are more complex than I need. Since, I'm moving away from Excel, I need a half steps for testing. Whats the simplest way to fire o...
Running Python Scripts From MS Office
I have installed PythonWin installed.. I can read and write to Excel from Python, not a problem. Not the usage I need. All examples I have found are more complex than I need. Since, I'm moving away from Excel, I need a half steps for testing. Whats the simplest way to fire off python scripts from Excel. I dont need g...
[ "You can use Excel's Shell function*, e.g.\nSub RunExternalProg()\n\n Dim return_value As Double\n return_value = Shell(\"C:\\Python26\\pythonw.exe C:\\my_script.py\", vbHide)\n Debug.Print return_value\n\nEnd Sub\n\nYou may need to change the path to the pythonw executable; depending on your setup.\n\n*Sh...
[ 4 ]
[]
[]
[ "excel", "python", "pywin32", "vba" ]
stackoverflow_0003815340_excel_python_pywin32_vba.txt
Q: Python - How do I differentiate between two list elements that point to the same object? I have a Ring structure implemented as follows (based on a cookbook recipe I found): class Ring(list): def turn(self): last = self.pop(0) self.append(last) def setTop(self, objectReference): i...
Python - How do I differentiate between two list elements that point to the same object?
I have a Ring structure implemented as follows (based on a cookbook recipe I found): class Ring(list): def turn(self): last = self.pop(0) self.append(last) def setTop(self, objectReference): if objectReference not in self: raise ValueError, "object is not in ring" ...
[ "From Learning Python, 4th edition -- Chapter 6:\n\nAt least conceptually, each time you generate a new value in your script by running an\n expression, Python creates a new object (i.e., a chunk of memory) to represent that\n value. Internally, as an optimization, Python caches and reuses certain kinds of un-\n ...
[ 4, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003814843_python.txt
Q: Quick counting with linked Django Models I've got a stack of Models something like this (I'm typing it out in relative shorthand): class User: pass class ItemList: pass # A User can have more than one ItemList # An ItemList can have more than one User # Classic M2M class ItemListOwnership: user = fk...
Quick counting with linked Django Models
I've got a stack of Models something like this (I'm typing it out in relative shorthand): class User: pass class ItemList: pass # A User can have more than one ItemList # An ItemList can have more than one User # Classic M2M class ItemListOwnership: user = fk(User) itemlist = fk(ItemList) # An It...
[ "Firstly, defining extra fields in a linking table is what the through functionality of ManyToManyField is for. So, keep your ItemListOwnership table with its FKs, but add a userlist=ManyToMany('User', through='ItemListOwnership') to UserList.\nOnce you've done this, you can easily count the number of items for eac...
[ 3 ]
[]
[]
[ "django", "django_models", "python", "sql" ]
stackoverflow_0003815395_django_django_models_python_sql.txt
Q: How to write a script (for Windows XP) to run a python program? Basically, I'd like to run a script (versus typing python program.py) or even have a shortcut that I could click on and start the program. Any ideas? A: From python.org: On Windows systems, there is no notion of an “executable mode”. The Python...
How to write a script (for Windows XP) to run a python program?
Basically, I'd like to run a script (versus typing python program.py) or even have a shortcut that I could click on and start the program. Any ideas?
[ "From python.org:\n\nOn Windows systems, there is no\n notion of an “executable mode”. The\n Python installer automatically\n associates .py files with python.exe\n so that a double-click on a Python\n file will run it as a script. The\n extension can also be .pyw, in that\n case, the console window that nor...
[ 2, 1, 1 ]
[ "Use py2exe to create a portable windows executable file.\n" ]
[ -1 ]
[ "python", "windows_xp" ]
stackoverflow_0003815746_python_windows_xp.txt
Q: Python how to exit main function Possible Duplicates: Terminating a Python script Terminating a Python Program My question is how to exit out in Python main function? I have tried 'return' but it gave the error SyntaxError: 'return' outside function. Can anyone help? Thanks. if __name__ == '__main__': try: ...
Python how to exit main function
Possible Duplicates: Terminating a Python script Terminating a Python Program My question is how to exit out in Python main function? I have tried 'return' but it gave the error SyntaxError: 'return' outside function. Can anyone help? Thanks. if __name__ == '__main__': try: if condition: (I want to exit h...
[ "You can use sys.exit() to exit from the middle of the main function.\nHowever, I would recommend not doing any logic there. Instead, put everything in a function, and call that from __main__ - then you can use return as normal.\n", "You can't return because you're not in a function. You can exit though.\nimport...
[ 117, 32, 12, 7, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003815860_python.txt
Q: Tornado Request Handler For some reason i am unable to instantiate the set_cookie outside of the MainHandler.. This is a little code to show what im wanting to do.. Can Anyone help?? import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web from tornado.options import define, option...
Tornado Request Handler
For some reason i am unable to instantiate the set_cookie outside of the MainHandler.. This is a little code to show what im wanting to do.. Can Anyone help?? import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web from tornado.options import define, options from GenCookie import * c...
[ "I thought that explains itself.\nset_cookie is a method of tornado.web.RequestHandler\nwhile in your code \"self.set_cookie\", self refers to object of class GenCookie.\nYour code can be modified to pass the necessary reference\nclass MainHandler(tornado.web.RequestHandler):\n     def get(self):\n       g=GenCooki...
[ 7 ]
[]
[]
[ "class", "python", "request", "setcookie", "tornado" ]
stackoverflow_0003816105_class_python_request_setcookie_tornado.txt
Q: Is there a DB/ORM pattern for attributes? i want to create an object with different key-value as attributes, for example: animal id name attribute id name and mapping animal_attribute animal_id attribute_id so i can have a entry "duck", which has multiple attribute "flying", "swimming", ...
Is there a DB/ORM pattern for attributes?
i want to create an object with different key-value as attributes, for example: animal id name attribute id name and mapping animal_attribute animal_id attribute_id so i can have a entry "duck", which has multiple attribute "flying", "swimming", etc. Each attribute type would have its own ta...
[ "You have several alternatives.\nIf you have not very deep hierarchy of objects and just several attributes, then you can create one table and add columns for every attribute you need to support\nOther way is to create table for each object and map each attribute to different column.\nApproach you want to use is no...
[ 4 ]
[]
[]
[ "database", "database_design", "python", "sqlalchemy" ]
stackoverflow_0003816220_database_database_design_python_sqlalchemy.txt
Q: Numpy/Python performing terribly vs. Matlab Novice programmer here. I'm writing a program that analyzes the relative spatial locations of points (cells). The program gets boundaries and cell type off an array with the x coordinate in column 1, y coordinate in column 2, and cell type in column 3. It then checks...
Numpy/Python performing terribly vs. Matlab
Novice programmer here. I'm writing a program that analyzes the relative spatial locations of points (cells). The program gets boundaries and cell type off an array with the x coordinate in column 1, y coordinate in column 2, and cell type in column 3. It then checks each cell for cell type and appropriate distance...
[ "Here are some ways to speed up your python code.\nFirst: Don't make np arrays when you are only storing one value. You do this many times over in your code. For instance,\nif firstcelltype == np.array((cellrecord[basecell,2])):\n\ncan just be\n if firstcelltype == cellrecord[basecell,2]:\n\nI'll show you why with ...
[ 27, 2, 0, 0 ]
[]
[]
[ "matlab", "numpy", "python" ]
stackoverflow_0003815357_matlab_numpy_python.txt
Q: Validate a name in Python For an internationalised project, I have to validate the global syntax for a name (first, last) with Python. But the lack of unicode classes support is really maling things harder. Is there any regex / library to do that ? Examples: Björn, Anne-Charlotte, توماس, 毛, or מיק must be accepted...
Validate a name in Python
For an internationalised project, I have to validate the global syntax for a name (first, last) with Python. But the lack of unicode classes support is really maling things harder. Is there any regex / library to do that ? Examples: Björn, Anne-Charlotte, توماس, 毛, or מיק must be accepted. -Björn, Anne--Charlotte, Tom_...
[ "Python does support unicode in regular expressions if you specify the re.UNICODE flag. You can probably use something like this:\nr'^[^\\W_]+(-[^\\W_]+)?$'\n\nTest code:\n# -*- coding: utf-8 -*-\nimport re\n\nnames = [\n u'Björn',\n u'Anne-Charlotte',\n u'توماس',\n u'毛',...
[ 13 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003816332_python_regex.txt
Q: Is there a pure Python Lucene? The ruby folks have Ferret. Someone know of any similar initiative for Python? We're using PyLucene at current, but I'd like to investigate moving to pure Python searching. A: Whoosh is a new project which is similar to lucene, but is pure python. A: The only one pure-python (not...
Is there a pure Python Lucene?
The ruby folks have Ferret. Someone know of any similar initiative for Python? We're using PyLucene at current, but I'd like to investigate moving to pure Python searching.
[ "Whoosh is a new project which is similar to lucene, but is pure python.\n", "The only one pure-python (not involving even C extension) search solution I know of is Nucular. It's slow (much slower than PyLucene) and unstable yet.\nWe moved from PyLucene-based home baked search and indexing to Solr but YMMV.\n", ...
[ 44, 6, 4, 3, 2, 2, 2, 1 ]
[]
[]
[ "ferret", "full_text_search", "lucene", "python" ]
stackoverflow_0000438315_ferret_full_text_search_lucene_python.txt
Q: how can I upload a kml file with a script to google maps? I have a python script, that generates kml files. Now I want to upload this kml file within the script (not per hand) to the "my maps" section of google maps. Does anybody have a python or other script/code to do so? A: Summary: You can't until issue 2590...
how can I upload a kml file with a script to google maps?
I have a python script, that generates kml files. Now I want to upload this kml file within the script (not per hand) to the "my maps" section of google maps. Does anybody have a python or other script/code to do so?
[ "Summary: You can't until issue 2590 is fixed, which may be a while because Google have closed this issue as WontFix. There are workarounds you can try to achieve the same end result, but as it stands you cannot simply upload a KML file using the Google Maps Data API.\nLong version:\nI don't didn't have any Python ...
[ 1 ]
[]
[]
[ "gdata", "gdata_python_client", "google_maps", "python" ]
stackoverflow_0003816541_gdata_gdata_python_client_google_maps_python.txt
Q: Something similar to ParallelPython for C++? I need to do some extensive searching and string comparisons and for this I figure that a compiled program is much better than an interpreted ones especially after seeing some comparison studies. I came across ParallelPython which was beautiful. It has autodiscovery for...
Something similar to ParallelPython for C++?
I need to do some extensive searching and string comparisons and for this I figure that a compiled program is much better than an interpreted ones especially after seeing some comparison studies. I came across ParallelPython which was beautiful. It has autodiscovery for clusters and can pretty much do all the load bala...
[ "I would suggest OpenMPI. I do not know what ParallelPython does exactly, but OpenMPI is an open API for cluster computing, and I imagine it will provide the requested functionality.\n", "You can always use ParallelPython for your high level work, and call into C++ code for the \"hard-core\" processing, as needed...
[ 1, 1 ]
[]
[]
[ "c++", "cluster_computing", "distributed", "python" ]
stackoverflow_0003816680_c++_cluster_computing_distributed_python.txt
Q: Using lists and dictionaries to store temporary information I will have alot of similar objects with similar parameters. Example of an object parameters would be something like : name, boolean, number and list. The name must be unique value among all the objects while values for boolean, number and list parameter...
Using lists and dictionaries to store temporary information
I will have alot of similar objects with similar parameters. Example of an object parameters would be something like : name, boolean, number and list. The name must be unique value among all the objects while values for boolean, number and list parameters must not. I could store the data as list of dictionaries i gue...
[ "If the name is the actual (unique) identifier of each inner data, you could just use a dictionary for the outer data as well:\ndata = {\n 'a' : { 'bool':true, 'number':123, 'list':[1, 2, 3] },\n 'b' : { 'bool':false, 'number':143, 'list':[1, 3, 5] },\n 'c' : { 'bool':false, 'number':123, 'list':[1, 4, 5, 18] },...
[ 6, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003816669_python.txt
Q: Python: Convert from buffer of Structure object to unsiged integer I'm new to Python, so I was wondering how would I extract buffer to convert the whole buffer into one integer from a Structure object with the code defined below g = 12463 h = 65342 i = 94854731 j = 9000 class Blah(Structure): _fields_ = [ ...
Python: Convert from buffer of Structure object to unsiged integer
I'm new to Python, so I was wondering how would I extract buffer to convert the whole buffer into one integer from a Structure object with the code defined below g = 12463 h = 65342 i = 94854731 j = 9000 class Blah(Structure): _fields_ = [ ("a", ctypes.c_int32, 17), ("b", ctypes.c_in...
[ "Instead of using a ctypes structure, use bit shift operations to assemble the integer.\ny = g << 160 + h << 128 + i << 64 + j\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003817100_python.txt
Q: Regular expression isn't found in line: execution just hangs I am new to python (and this site); I am trying to write a script that will use a regular expression to search through a given file to find a name. I have to print out the different ways the name was capitalized and how many times the name was found. My ...
Regular expression isn't found in line: execution just hangs
I am new to python (and this site); I am trying to write a script that will use a regular expression to search through a given file to find a name. I have to print out the different ways the name was capitalized and how many times the name was found. My current code will just print out my first flag and then hang. I do...
[ "First I would say to take a look at this thread for a bit of information about reading from stdin (if that's really what you want to do).\nSecond, I would consider just opening the file instead of reading from sys.stdin, either using a library like fileinput or a with statement or other file handle.\nNext, I would...
[ 4, 3, 0 ]
[]
[]
[ "file_io", "python", "regex" ]
stackoverflow_0003816825_file_io_python_regex.txt
Q: Design question on Python network programming I'm currently writing a project in Python which has a client and a server part. I have troubles with the network communication, so I need to explain some things... The client mainly does operations the server tells him to and sends the results of the operations back to...
Design question on Python network programming
I'm currently writing a project in Python which has a client and a server part. I have troubles with the network communication, so I need to explain some things... The client mainly does operations the server tells him to and sends the results of the operations back to the server. I need a way to communicate bidirectio...
[ "\"I don't even know if using the LineReceiver is a good idea for this kind of problem, because it cannot send any data, if it does not receive data from the client. There is only a lineReceived event.\"\nYou can send data using protocol.transport.write from anywhere, not just in lineReceived.\n", "\n\"I need a w...
[ 2, -1 ]
[]
[]
[ "event_driven_design", "network_programming", "python", "twisted" ]
stackoverflow_0003772719_event_driven_design_network_programming_python_twisted.txt
Q: Generating SHA-256 hash in Python 2.4 using M2Crypto Is it possible to generate a SHA-256 hash using M2Crypto? Python 2.4's SHA module doesn't support 256, so I started using PyCrypto, only to find out that PyCrypto doesn't support PKCS#5 (needed elsewhere in my project.) I switched to M2Crypto as a result and n...
Generating SHA-256 hash in Python 2.4 using M2Crypto
Is it possible to generate a SHA-256 hash using M2Crypto? Python 2.4's SHA module doesn't support 256, so I started using PyCrypto, only to find out that PyCrypto doesn't support PKCS#5 (needed elsewhere in my project.) I switched to M2Crypto as a result and now I would like to replace my PyCrypto SHA-256 call with a...
[ "You could download the hashlib module of Python 2.5 (supports SHA256) for usage on older Pythons (e.g. Python 2.4).\n" ]
[ 6 ]
[]
[]
[ "cryptography", "hash", "m2crypto", "python", "sha256" ]
stackoverflow_0003817303_cryptography_hash_m2crypto_python_sha256.txt
Q: argparse missing in python 3 does somebody know, why the argparse module didn't make it in python 3? it's new in python 2.7, but the 2.x branch is running out with 2.7. it makes no sense to me not to support it in the actual python 3 branch. A: It will be in Python 3.2. It was just added in Python 2.7, which was...
argparse missing in python 3
does somebody know, why the argparse module didn't make it in python 3? it's new in python 2.7, but the 2.x branch is running out with 2.7. it makes no sense to me not to support it in the actual python 3 branch.
[ "It will be in Python 3.2. It was just added in Python 2.7, which was released just this July; Python 3.2 will be the next 3.x release after that date.\n", "argparse is in Python 3, 3.2 to be specific. See also: http://www.python.org/dev/peps/pep-0389/\n" ]
[ 12, 4 ]
[]
[]
[ "argparse", "command_line", "python", "python_3.x" ]
stackoverflow_0003817481_argparse_command_line_python_python_3.x.txt
Q: How to import function handlers from other file to a Python/GTK Builder program? I have a Python script which uses a glade file to define its UI, and has a lot of repetitive widgets, each one to adjust a different numerical attribute of a certain active object. Since it is repetitive, I decided to define all the h...
How to import function handlers from other file to a Python/GTK Builder program?
I have a Python script which uses a glade file to define its UI, and has a lot of repetitive widgets, each one to adjust a different numerical attribute of a certain active object. Since it is repetitive, I decided to define all the handlers in a separate file for encapsulation and readability. Here are some code excer...
[ "the obj arguments or names are missing. perhaps you need to import something and assign it, or add it to the arguments for the handler functions? what exactly is the obj supposed to be?\n", "I think you've forgotten the self argument all over the place.\ni.e. change this:\nclass Handlers:\n def adjustbottomBr...
[ 0, 0 ]
[]
[]
[ "builder", "glade", "pygtk", "python" ]
stackoverflow_0003817758_builder_glade_pygtk_python.txt
Q: syntax for creating a dictionary into another dictionary in python Possible Duplicate: syntax to insert one list into another list in python How could be the syntax for creating a dictionary into another dictionary in python A: You can declare a dictionary inside a dictionary by nesting the {} containers: d = ...
syntax for creating a dictionary into another dictionary in python
Possible Duplicate: syntax to insert one list into another list in python How could be the syntax for creating a dictionary into another dictionary in python
[ "You can declare a dictionary inside a dictionary by nesting the {} containers:\nd = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}\n\nAnd then you can access the elements using the [] syntax:\nprint d['dict1'] # {'foo': 1, 'bar': 2}\nprint d['dict1']['foo'] # 1\nprint d['dict2']['quux...
[ 106, 9, 3 ]
[]
[]
[ "python" ]
stackoverflow_0003817529_python.txt
Q: Join list of string in python with string %s replacement I have a list of ints that I want to join into a string ids = [1,2,3,4,5] that looks like 'Id = 1 or Id = 2 or Id = 3 or Id = 4 or ID = 5' I have an answer now but I thought it may be good to get the panel's opinion Edit: More information to the nay sayers...
Join list of string in python with string %s replacement
I have a list of ints that I want to join into a string ids = [1,2,3,4,5] that looks like 'Id = 1 or Id = 2 or Id = 3 or Id = 4 or ID = 5' I have an answer now but I thought it may be good to get the panel's opinion Edit: More information to the nay sayers... This not generating SQL directly, this is dynamic expressi...
[ "\" or \".join(\"id = %d\" % id for id in ids)\n\n", "mystring = 'id =' + 'or id ='.join(str(i) for i in ids)\n\nIf you want to generate dynamic sql as those in the comments have pointed out (don't know how I missed it), you should be doing this as\nmystring = ' or '.join(['id = ?']*len(ids)) \n\nwhere ? is mean...
[ 5, 1 ]
[]
[]
[ "python", "string_concatenation" ]
stackoverflow_0003818362_python_string_concatenation.txt
Q: Are there any keyboard shortcuts for formatting in Python? After we write a code in Matlab we can use ctrl+A+ctrl+I and ctrl+A+ctrl+J to format our code (comments, loops alignment etc). Is there something similar or any helpful keyboard shortcuts in Python? Also, just like we can use upward arrow to copy our previ...
Are there any keyboard shortcuts for formatting in Python?
After we write a code in Matlab we can use ctrl+A+ctrl+I and ctrl+A+ctrl+J to format our code (comments, loops alignment etc). Is there something similar or any helpful keyboard shortcuts in Python? Also, just like we can use upward arrow to copy our previous command window history in Matlab, is it possible or some key...
[ "Python is a programming language, not an integrated development environment (IDE), therefore it has no \"keyboard shortcuts\" or the like. Each given development environment may offer different facilities or the like. You appear to consider GNU Readline (typically used in the simple text-mode interpreter environ...
[ 7, 1, 1 ]
[]
[]
[ "formatting", "keyboard_shortcuts", "matlab", "python" ]
stackoverflow_0003818405_formatting_keyboard_shortcuts_matlab_python.txt
Q: Jobs are getting lost in ParallelPython? I am submitting about 234 jobs (but my example contains only 50 for demonstration purpose) to my 20 node cluster using ParallelPython. I was expecting that it would queue and execute them but it seems to "lose" jobs and I am not understand where things are going wrong. When...
Jobs are getting lost in ParallelPython?
I am submitting about 234 jobs (but my example contains only 50 for demonstration purpose) to my 20 node cluster using ParallelPython. I was expecting that it would queue and execute them but it seems to "lose" jobs and I am not understand where things are going wrong. When the script finishes, I am not able to see 50 ...
[ "Ok my mistake! Just in case anyone else faces this issue, make sure your directory paths are absolute whether you are reading from a file or writing into a file... 5 hours of debugging :( but I learnt my lesson :)\n" ]
[ 0 ]
[]
[]
[ "cluster_computing", "debugging", "parallel_processing", "python" ]
stackoverflow_0003818252_cluster_computing_debugging_parallel_processing_python.txt
Q: Assignment raises exception for list.index How could this code fragment... def subInPath(origPath, subPath): origSplit = split(origPath, '/') subSplit = split(subPath, '/') subRoot = subSplit[0] origSplit.reverse() print origSplit.index(subRoot) rootIndex = origSplit.index(subRoot) or...
Assignment raises exception for list.index
How could this code fragment... def subInPath(origPath, subPath): origSplit = split(origPath, '/') subSplit = split(subPath, '/') subRoot = subSplit[0] origSplit.reverse() print origSplit.index(subRoot) rootIndex = origSplit.index(subRoot) origSplit[:rootIndex+1] = [] origSplit.reverse...
[ "Always use os.path module when working with directories or paths. It's got all the methods needed to work with directories, plus it has the advantage of being compatible in multiples operating system.\nIt's just better software engineering.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003818923_python.txt
Q: How to replace all the characters with * using Regular Expression I am having a text like s = bluesky I want to get it as s = ******* (equal no of * as no of characters) I am searching for a regular expression for Python. Edit 1 : b = '*'*len(s) How can we do it in Django Template? A: You don't need a regex f...
How to replace all the characters with * using Regular Expression
I am having a text like s = bluesky I want to get it as s = ******* (equal no of * as no of characters) I am searching for a regular expression for Python. Edit 1 : b = '*'*len(s) How can we do it in Django Template?
[ "You don't need a regex for this:\ns = 'bluesky'\nb = '*'*len(s)\nprint b\n\noutput : \n>>> s = 'bluesky'\n>>> b = '*'*len(s)\n>>> print b\n*******\n\n", "No need for regexp, just text.replace('bluesky','*'*len('bluesky'))\ne.g:\n>>> text = \"s = bluesky\"\n>>> text.replace('bluesky','*'*len('bluesky'))\n's = ***...
[ 6, 2, 2, 0 ]
[]
[]
[ "django", "django_templates", "html", "python", "regex" ]
stackoverflow_0003819097_django_django_templates_html_python_regex.txt
Q: django: can we do loader.get_template('my_template.txt')? I want to use django template to process plain text file, and tried this: from django.template import loader, Context t = loader.get_template('my_template.txt') however, it works for this: from django.template import loader, Context t = loader.get_template...
django: can we do loader.get_template('my_template.txt')?
I want to use django template to process plain text file, and tried this: from django.template import loader, Context t = loader.get_template('my_template.txt') however, it works for this: from django.template import loader, Context t = loader.get_template('my_template.html') Can we load txt files using django templa...
[ "As @Seth commented I don't see any reason why this shouldn't work. Django doesn't care about the extension of the file. You can very well load my_template.foo. \nCheck the following:\n\nThe file is indeed present where it should be. If it is in a subdirectory then you'll have to use loader.get_template('<subdirect...
[ 3 ]
[ "I would leave this for some one else to answer as I am not very comfortable with Django.\nHow ever, if you are interested in templates and plain text processing, why don't you look at slew of other products available within python.\n\nhttps://stackoverflow.com/questions/98245/what-is-your-single-favorite-python-te...
[ -7 ]
[ "django", "django_templates", "python" ]
stackoverflow_0003817926_django_django_templates_python.txt
Q: Is there any filter in Django to display asterisks (*) instead of text I am eager to know whether any filter is available for displaying all the text as * like this mytext = 'raja' {{ mytext|password }} should show **** How can we do this? A: Easy. Do this: {% for char in mytext %}*{% endfor %} That said, can ...
Is there any filter in Django to display asterisks (*) instead of text
I am eager to know whether any filter is available for displaying all the text as * like this mytext = 'raja' {{ mytext|password }} should show **** How can we do this?
[ "Easy. Do this:\n{% for char in mytext %}*{% endfor %}\n\nThat said, can I ask you where you are displaying the password? Usually passwords are not displayed on screen. If you want to display it in a form you can use a PasswordInput widget. \nAs @Ars said it is a bad idea to reveal the length of the password. You m...
[ 3, 2 ]
[]
[]
[ "django", "django_templates", "html", "python" ]
stackoverflow_0003819260_django_django_templates_html_python.txt
Q: Python: How to do break up array processing (using multiple queued functions) in timed chunks (600ms) I was wondering what would be the best approach to split up array processing using multiple queued functions into small time chunks? So say I have an multi dimensional array, and I want to run a function(s) over i...
Python: How to do break up array processing (using multiple queued functions) in timed chunks (600ms)
I was wondering what would be the best approach to split up array processing using multiple queued functions into small time chunks? So say I have an multi dimensional array, and I want to run a function(s) over it, but only in small timed chunks, say 500ms each time I trigger the processing to occur. What would be the...
[ "You could set up a queue of functions to run as a generator that would yield each run, then have a small loop that looked like this:\ntime_elapsed = 0\nfor func in function_queue_generator:\n if time_elapsed > time_limit:\n yield\n time_elapsed = 0\n func()\n\nSuch a generator could be implemen...
[ 1 ]
[]
[]
[ "multidimensional_array", "python" ]
stackoverflow_0003819387_multidimensional_array_python.txt
Q: Flex networking: How to read multiple AMF Objects I'm trying to write a very plain game client to get some practice with Actionscript 3 and the Flex Framework. I have some problems with following code: private function readResponse():void { var r:ByteArray = new ByteArray(); readBytes(r); while (r.bytesA...
Flex networking: How to read multiple AMF Objects
I'm trying to write a very plain game client to get some practice with Actionscript 3 and the Flex Framework. I have some problems with following code: private function readResponse():void { var r:ByteArray = new ByteArray(); readBytes(r); while (r.bytesAvailable != 0) { try { var d:Object = r...
[ "If you are using AMF, I do not understand why you would read bytes from a binary array?\nTry using RemoteObject, and a response-handler ( and eventually also an error handler )\nThere is an example here: http://pyamf.org/tutorials/actionscript/simple.html#actionscript\n(which I have not tried as I am not python sa...
[ 0 ]
[]
[]
[ "actionscript_3", "apache_flex", "flex4", "python" ]
stackoverflow_0003814140_actionscript_3_apache_flex_flex4_python.txt
Q: Lua or Python binding with C++ I have used Lua.NET on .NET platform and I could call the .NET class/object from Lua and I could call the Lua from .NET Lua API interface. I did the same with the IronPython. I knew the how the .NET binding works. Now I have a C++ project and I want to use the dynamic capabilities. ...
Lua or Python binding with C++
I have used Lua.NET on .NET platform and I could call the .NET class/object from Lua and I could call the Lua from .NET Lua API interface. I did the same with the IronPython. I knew the how the .NET binding works. Now I have a C++ project and I want to use the dynamic capabilities. I want to call C++ object which may ...
[ "\nWhen considering Lua to Python in C++ for two way calling, is Python have upper hand with Boost Python library?\n\nThere are a few libraries that simplify the communication between C++ and Lua. One of them, luabind, is inspired by boost.python and is quite powerful and fairly easy to use. \nOther C++ <-> Lua lib...
[ 4, 0 ]
[]
[]
[ "boost", "c++", "embedding", "lua", "python" ]
stackoverflow_0003818703_boost_c++_embedding_lua_python.txt
Q: Google appengine blobstore debugging I'm having an issue with blobstore uploads, but because of the way gae handles all of that, actually figuring out what the error was is giving me some trouble. I'm using django, which unfortunately tries very hard to prevent exceptions from reaching the user without formatting...
Google appengine blobstore debugging
I'm having an issue with blobstore uploads, but because of the way gae handles all of that, actually figuring out what the error was is giving me some trouble. I'm using django, which unfortunately tries very hard to prevent exceptions from reaching the user without formatting. It looks like the uploads are successfu...
[ "The exception your code is raising should be output immediately above the log lines you pasted - scroll up! If it's not, something in your framework is catching exceptions and not reporting them - possibly it's returning them to the user, which is not much use in this scenario.\n", "Well, here's how i'm now maki...
[ 2, 0 ]
[]
[]
[ "blobstore", "django", "google_app_engine", "python" ]
stackoverflow_0003818754_blobstore_django_google_app_engine_python.txt
Q: Distinct in many-to-many relation class Order(models.Model): ... class OrderItem(models.Model) order = models.ForeignKey(Order) product = models.ForeignKey(Product) quantity = models.PositiveIntegerField() What I need to do is to get the Order(s) which has only one order item. How can I write it ...
Distinct in many-to-many relation
class Order(models.Model): ... class OrderItem(models.Model) order = models.ForeignKey(Order) product = models.ForeignKey(Product) quantity = models.PositiveIntegerField() What I need to do is to get the Order(s) which has only one order item. How can I write it using the QuerySet objects (without wri...
[ "The easiest way to do this would be to use the Count aggregation:\nfrom django.db.models import Count\nOrder.objects.annotate(count = Count('orderitem__id')).filter(count = 1)\n\n" ]
[ 3 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003819677_django_django_models_python.txt
Q: Improving text extraction routine from XML I've an XML file which contains no. of <TEXT> </TEXT> tags enclosing text. <TEXT> <!-- PJG STAG 4703 --> <!-- PJG ITAG l=94 g=1 f=1 --> <!-- PJG /ITAG --> <!-- PJG ITAG l=69 g=1 f=1 --> <!-- PJG /ITAG --> <!-- PJG ITAG l=50 g=1 f=1 --> <USDEPT>DEPARTMENT OF AGRICU...
Improving text extraction routine from XML
I've an XML file which contains no. of <TEXT> </TEXT> tags enclosing text. <TEXT> <!-- PJG STAG 4703 --> <!-- PJG ITAG l=94 g=1 f=1 --> <!-- PJG /ITAG --> <!-- PJG ITAG l=69 g=1 f=1 --> <!-- PJG /ITAG --> <!-- PJG ITAG l=50 g=1 f=1 --> <USDEPT>DEPARTMENT OF AGRICULTURE</USDEPT> <!-- PJG /ITAG --> <!-- PJG IT...
[ "lxml is much easier to use than the xml libraries included in the standard python library. It's a binding for the C libxml2 library, so I'm assuming it's also faster.\nI'd do something like this (using your variable names):\nfrom lxml import etree\nwith open('some-file.xml') as f:\n xmlDoc = etree.parse(f)\n ...
[ 1, 0 ]
[]
[]
[ "python", "xml", "xml_parsing" ]
stackoverflow_0003818711_python_xml_xml_parsing.txt
Q: Testing for extra_context in django I'm trying to test if the extra_context provided by the user was correctly processed in the view. Here is my test approach: # tests.py (of course it's a part of TestCase class) def test_should_use_definied_extra_context(self): response = self.client.get(reverse('contact_ques...
Testing for extra_context in django
I'm trying to test if the extra_context provided by the user was correctly processed in the view. Here is my test approach: # tests.py (of course it's a part of TestCase class) def test_should_use_definied_extra_context(self): response = self.client.get(reverse('contact_question_create'), { 'extra_context':...
[ "You need to use following solution:\ndef contact_question_create(request, success_url=None, form_class=None,\n template_name=\"contact/contact_form.html\",\n extra_context=None, **kwargs):\n\n # your view code here\n\n context = {'defult':'foo'}\n\n if extra_c...
[ 3 ]
[]
[]
[ "django", "python", "tdd", "unit_testing" ]
stackoverflow_0003817199_django_python_tdd_unit_testing.txt
Q: List of combinations I have a list with length N and each element of this list are 0 or 1. I need to get all possible combinations of this list. Here is my code: def some(lst): result = [] for element in lst: c1 = copy.copy(element) c2 = copy.copy(element) c1.append(0) c2.a...
List of combinations
I have a list with length N and each element of this list are 0 or 1. I need to get all possible combinations of this list. Here is my code: def some(lst): result = [] for element in lst: c1 = copy.copy(element) c2 = copy.copy(element) c1.append(0) c2.append(1) result.ap...
[ "Don't they look like bit patterns (0000 ....1111 ) i.e binary bits.\nAnd all possible combination of n binary bits will range from 0 to 2**n -1 \nnoOfBits = 5\nfor n in range(2**noOfBits):\n binVal = bin(n)[2:].zfill(noOfBits)\n b = [ x for x in binVal]\n print b\n\nDo we need combinatorics for this purpo...
[ 5, 3 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0003819658_algorithm_python.txt
Q: Telnet performance in windows xp and Linux I has a Library impelmented based on Python's telnetlib. And recently, i noticed that the performance in windows xp and Linux is so different. below script, i design three operations, "get units", "just press enter", "get units with options" "get units" has long string re...
Telnet performance in windows xp and Linux
I has a Library impelmented based on Python's telnetlib. And recently, i noticed that the performance in windows xp and Linux is so different. below script, i design three operations, "get units", "just press enter", "get units with options" "get units" has long string return, "get units with options" return shorter st...
[ "Maybe it's delaying sending a short packet because of Nagle's algorithm.\nYou could test that by disabling the Nagle algorithm on the XP machine (Google for how to do that).\n", "Thank you all. I have solve this problems. There are two algorithm: The Nagle algorithm, The delayed ACK algorithm. My problem is caus...
[ 0, 0 ]
[]
[]
[ "linux", "python", "sockets", "telnet", "windows" ]
stackoverflow_0003818345_linux_python_sockets_telnet_windows.txt
Q: Accessing Yahoo Contacts through OAuth on App Engine (Python) I have an existing webapp, running in Python on App Engine, in which users can login through open-id using a Yahoo account. Now, once they're signed in, I'd like them to be able to access their Yahoo contacts, through OAuth. I'm working though the Yahoo...
Accessing Yahoo Contacts through OAuth on App Engine (Python)
I have an existing webapp, running in Python on App Engine, in which users can login through open-id using a Yahoo account. Now, once they're signed in, I'd like them to be able to access their Yahoo contacts, through OAuth. I'm working though the Yahoo Python SDK and am just stuck. I have the consumer key, consumer s...
[ "You should look for OpenID+Oauth Hybrid protocol.\nOpenID+OAuth Hybrid protocol lets web developers combine an OpenID request with an OAuth authentication request.\nThis extension is useful for web developers who use both OpenID and OAuth, particularly in that it simplifies the process for users by requesting thei...
[ 0 ]
[]
[]
[ "google_app_engine", "oauth", "python", "yahoo_oauth" ]
stackoverflow_0003818046_google_app_engine_oauth_python_yahoo_oauth.txt
Q: How to get server reply after sending a mail using smtplib SMTP.sendmail I have a program to send mail using python smtplib. I have the mail sending part working fine, but I also need to capture the server return message after a mail has been sent. For example postfix returns the following message after a mail has...
How to get server reply after sending a mail using smtplib SMTP.sendmail
I have a program to send mail using python smtplib. I have the mail sending part working fine, but I also need to capture the server return message after a mail has been sent. For example postfix returns the following message after a mail has been queueed: reply: '250 2.0.0 Ok: queued as EB83821273B\r\n' reply: retcode...
[ "If you are using the sendmail method on an SMTP instance, then it will return\n\na dictionary, with one entry for each\n recipient that was refused. Each entry\n contains a tuple of the SMTP error\n code and the accompanying error\n message sent by the server.\n\nif you use the docmd method on the same class, ...
[ 5 ]
[]
[]
[ "python", "smtplib" ]
stackoverflow_0003820603_python_smtplib.txt
Q: How to perform this sql in django model? SELECT *, SUM( cardtype.price - cardtype.cost ) AS profit FROM user LEFT OUTER JOIN card ON ( user.id = card.buyer_id ) LEFT OUTER JOIN cardtype ON ( card.cardtype_id = cardtype.id ) GROUP BY user.id ORDER BY profit DESC I tried this: User.objects.extra(s...
How to perform this sql in django model?
SELECT *, SUM( cardtype.price - cardtype.cost ) AS profit FROM user LEFT OUTER JOIN card ON ( user.id = card.buyer_id ) LEFT OUTER JOIN cardtype ON ( card.cardtype_id = cardtype.id ) GROUP BY user.id ORDER BY profit DESC I tried this: User.objects.extra(select=dict(profit='SUM(cardtype.price-cardtype...
[ "First, one of the outer joins appears to be a bad idea for this kind of thing. Since you provided no information on your model, I can only guess. \nAre you saying that you may not have a CARD for each user? That makes some sense.\nAre you also saying that some cards don't have card types? That doesn't often mak...
[ 1 ]
[ "Well, I found this\nSum computed column in Django QuerySet\nHave to use raw SQL now...\nThank you two!\n" ]
[ -1 ]
[ "django", "django_models", "python" ]
stackoverflow_0003819984_django_django_models_python.txt
Q: linux "more" like code in python for very big tuple/file/db records/numpy.darray? I am in looking for a buffer code for process huge records in tuple / csv file / sqlite db records / numpy.darray, the buffer may just like linux command "more". The request came from processing huge data records(100000000 rows maybe...
linux "more" like code in python for very big tuple/file/db records/numpy.darray?
I am in looking for a buffer code for process huge records in tuple / csv file / sqlite db records / numpy.darray, the buffer may just like linux command "more". The request came from processing huge data records(100000000 rows maybe), the records may look like this: 0.12313 0.231312 0.23123 0.152432 0.22569 0.311312 0...
[ "The linecache module may be helpful — you can call getline(filename, lineno) to efficiently retrieve lines from the given file.\nYou'll still have to figure out how high and wide the screen is. A quick googlance suggests that there are about 14 different ways to do this, some of which are probably outdated. The ...
[ 0, 0 ]
[]
[]
[ "buffer", "object", "pager", "python", "tuples" ]
stackoverflow_0003820503_buffer_object_pager_python_tuples.txt
Q: does python gives interactivity as javascript? I want to add interactivity like clicks, hover, onpage load() to a webpage, if i use python for generating xhtml, will python give essential flavors like javascript?? I'm bit confused and starter in python for web development, so is there need to include old javascrip...
does python gives interactivity as javascript?
I want to add interactivity like clicks, hover, onpage load() to a webpage, if i use python for generating xhtml, will python give essential flavors like javascript?? I'm bit confused and starter in python for web development, so is there need to include old javascript into python or the python only can handle interact...
[ "When you use Python for web development, you use it server-side (like PHP). It's not for client-side programming in the same way that JavaScript is. The vast majority of browsers only support JavaScript for client-side programming.\nIf you want client-side code on a site that's using Python on the server, it sti...
[ 5 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0003821305_javascript_python.txt
Q: Django ManyToMany relationship with abstract base - not possible, but is there a better way? Given the following models: class BaseMachine(models.Model) fqdn = models.CharField(max_length=150) cpus = models.IntegerField() memory = models.IntegerField() class Meta: abstract = True class Ph...
Django ManyToMany relationship with abstract base - not possible, but is there a better way?
Given the following models: class BaseMachine(models.Model) fqdn = models.CharField(max_length=150) cpus = models.IntegerField() memory = models.IntegerField() class Meta: abstract = True class PhysicalMachine(BaseMachine) location = models.CharField(max_length=150) class VirtualMachine(...
[ "EDIT: I have updated the soultion, so one admin can have many machines and one machine can have many admins:\nclass Sysadmin(models.Model):\n name = models.CharField(max_length=100)\n\n\nclass BaseMachine(models.Model):\n fqdn = models.CharField(max_length=150)\n cpus = models.IntegerField()\n memory =...
[ 3, 2 ]
[]
[]
[ "django", "orm", "python" ]
stackoverflow_0003821116_django_orm_python.txt
Q: Python: plot data from a txt file How do I plot a histogram of this kind of data, 10 apples 3 oranges 6 tomatoes 10 pears from a text file? thanks A: Here's one way you can assign different colors to the bars. It works with even a variable number of bars. import numpy as np import pylab import matplotlib.cm as ...
Python: plot data from a txt file
How do I plot a histogram of this kind of data, 10 apples 3 oranges 6 tomatoes 10 pears from a text file? thanks
[ "Here's one way you can assign different colors to the bars. It works with even a variable number of bars.\nimport numpy as np\nimport pylab\nimport matplotlib.cm as cm\n\narr = np.genfromtxt('data', dtype=None)\nn = len(arr)\ncenters = np.arange(n)\ncolors = cm.RdYlBu(np.linspace(0, 1, n))\npylab.bar(centers, arr[...
[ 6, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003821362_python.txt
Q: Are pyc files independent of the interpreter architecture? From the tests I've done, with the same version of python (same magic number), a 64 bit interpreter can load pyc files made with a 32 bit version of python. And reciprocally I assume. But is it totally safe? Can this lead to unexpected behavior? A: pyc f...
Are pyc files independent of the interpreter architecture?
From the tests I've done, with the same version of python (same magic number), a 64 bit interpreter can load pyc files made with a 32 bit version of python. And reciprocally I assume. But is it totally safe? Can this lead to unexpected behavior?
[ "pyc files are stored in the python marshal format.\nhttp://daeken.com/python-marshal-format\nit seems that the only issue is with encoded integers which are automatically downgraded to 32 bit integers when you read the pyc on a 32 bit machine.\nHowever the pyc format doesn't include 64bit addresses/offset inside i...
[ 2 ]
[]
[]
[ "32_bit", "64_bit", "pyc", "python" ]
stackoverflow_0003821728_32_bit_64_bit_pyc_python.txt
Q: Python: create fixed point decimal from two 32-bit ints (one for int portion, one for decimal) I have a 64-bit timestamp unpacked from a file with binary data, where the top 32 bits are the number of seconds and the bottom 32 bits are the fraction of the second. I'm stuck with how to actually convert the bottom 3...
Python: create fixed point decimal from two 32-bit ints (one for int portion, one for decimal)
I have a 64-bit timestamp unpacked from a file with binary data, where the top 32 bits are the number of seconds and the bottom 32 bits are the fraction of the second. I'm stuck with how to actually convert the bottom 32 bits into a fraction without looping through it bit-by-bit. Any suggestions? For reference, the nu...
[ "You can just divide the hex number by the maximum possible to get the correct ratio:\n>>> float(0x9481ef80) / 0x100000000\n0.58010765910148621\n\n", "To represent the sum of integral and fractional part with enough precision (32 + 29 = 61 bits), you need a Decimal (28 decimal digits by default, which is enough f...
[ 3, 2, 1 ]
[]
[]
[ "fixed_point", "python" ]
stackoverflow_0003813990_fixed_point_python.txt
Q: access a file in python that is created from SunGridEngine i have a python script, that submits an job to the SGE (Sun Grid Engine). When the job is done i want to access the output file, generated from the SGE job. i see with "ls" in the directory that the file is already existing and the job is done, but python ...
access a file in python that is created from SunGridEngine
i have a python script, that submits an job to the SGE (Sun Grid Engine). When the job is done i want to access the output file, generated from the SGE job. i see with "ls" in the directory that the file is already existing and the job is done, but python needs about 20-30 seconds to get access to that file... is there...
[ "created a sleep timer which checks every second for access..\nafter some time (~15s), access is granted and file is usable!\n" ]
[ 0 ]
[]
[]
[ "python", "sungridengine" ]
stackoverflow_0002738290_python_sungridengine.txt
Q: Are pyc files independent of the minor version of python? Is it possible and safe to load pyc files made with a different minor version of python? For instance 2.5.1 with 2.5.5? My guess is that the magic number does not change with minor versions. If I refer to this file import.c the magic number corresponds to t...
Are pyc files independent of the minor version of python?
Is it possible and safe to load pyc files made with a different minor version of python? For instance 2.5.1 with 2.5.5? My guess is that the magic number does not change with minor versions. If I refer to this file import.c the magic number corresponds to the variable pyc_magic ( equals MAGIC or MAGIC+1 ) The file comm...
[ "You can't assume that it won't change. Whenever I've needed to distribute .pyc files instead of readable .py files, I've ended up shipping a Python binary too.\n" ]
[ 1 ]
[]
[]
[ "pyc", "python", "version" ]
stackoverflow_0003821926_pyc_python_version.txt
Q: using file/db as the buffer for very big numpy array to yield data prevent overflow? In using the numpy.darray, I met a memory overflow problem due to the size of data,for example: Suppose I have a 100000000 * 100000000 * 100000000 float64 array data source, when I want to read data and process it in memory with n...
using file/db as the buffer for very big numpy array to yield data prevent overflow?
In using the numpy.darray, I met a memory overflow problem due to the size of data,for example: Suppose I have a 100000000 * 100000000 * 100000000 float64 array data source, when I want to read data and process it in memory with np. It will raise a Memoray Error because it works out all memory for storing such a big ar...
[ "Take a look at pytables or numpy.memmap, maybe they fit your needs. \nbest, Peter\n", "If You have matrices with lots of zeros use scipy.sparse.csc_matrix. \nIt's possible to write everything, for example You can override numarray array class.\n" ]
[ 1, 0 ]
[]
[]
[ "memory_management", "numpy", "python" ]
stackoverflow_0003818881_memory_management_numpy_python.txt
Q: How to format integers greater than 999 in python to look more readable? I have a bunch of numbers that I want to print to the user. Each number is greater than one million so I want to print it as 1.000.000 or 1,000,000 (any of these forms is valid to me). I want to know if is it possible to format integer number...
How to format integers greater than 999 in python to look more readable?
I have a bunch of numbers that I want to print to the user. Each number is greater than one million so I want to print it as 1.000.000 or 1,000,000 (any of these forms is valid to me). I want to know if is it possible to format integer numbers this way in python using the built-in formating utilities.
[ "Use locale.format. You will need to setlocale first, since the formatting style is dependent on location (European countries typically use . instead of , for separating the digits, for instance).\n>>> import locale\n>>> locale.setlocale(locale.LC_ALL, '')\n'English_United Kingdom.1252'\n>>> locale.format(\"%d\", 1...
[ 7, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003822006_python.txt
Q: when we need chmod +x file.py i wrote a py script to fetch page from web,it just read write permission enough,so my question is when we need execute permission? A: Read/write is enough if you want to run it by typing python file.py. If you want to run it directly as if it were a compiled program, e.g. ./file.py...
when we need chmod +x file.py
i wrote a py script to fetch page from web,it just read write permission enough,so my question is when we need execute permission?
[ "Read/write is enough if you want to run it by typing python file.py. If you want to run it directly as if it were a compiled program, e.g. ./file.py, then you need execute permission (and the appropriate hash-bang line at the top).\n", "It's required to do so if you need to run the script in this way: ./file.py...
[ 6, 5, 0 ]
[]
[]
[ "chmod", "permissions", "python" ]
stackoverflow_0003822336_chmod_permissions_python.txt
Q: Python: interrupt execution with key and run again how can I interrupt python execution with a key and continue to run when the key is pressed again ? thanks A: If you're using pygame, you can check for the key event and use a boolean switch. def check_pause(self): for event in pygame.event.get(): if...
Python: interrupt execution with key and run again
how can I interrupt python execution with a key and continue to run when the key is pressed again ? thanks
[ "If you're using pygame, you can check for the key event and use a boolean switch.\ndef check_pause(self):\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_p:\n self.pause = not self.pause\n\nSomething like that, attached to\nwhile ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003822485_python.txt
Q: Why must I use Qt Designer 2.7 with Python 2.7? Why can't I use other Qt series with different Python releases? A: You can. If you have a specific version of Qt you would like to use, you can either download a matching PyQt version from Riverbank's download site or you can compile your own version of PyQt. I've ...
Why must I use Qt Designer 2.7 with Python 2.7?
Why can't I use other Qt series with different Python releases?
[ "You can. If you have a specific version of Qt you would like to use, you can either download a matching PyQt version from Riverbank's download site or you can compile your own version of PyQt. I've had to build them from scratch a few times when the provided binaries didn't match the Qt/Python versions I wanted to...
[ 0 ]
[]
[]
[ "python", "qt", "qt_creator" ]
stackoverflow_0003820343_python_qt_qt_creator.txt
Q: Pyqt tabs like in Google Chrome I would like to have my pyqt aplication have tabs in the menu bar like Google Chrome :) Any suggestions or a simple example on how to do it? I did find these relevant link: - http://ivan.fomentgroup.org/blog/2009/03/29/instant-chrome/ A: You have to use the Qt.FramelessWindowHint...
Pyqt tabs like in Google Chrome
I would like to have my pyqt aplication have tabs in the menu bar like Google Chrome :) Any suggestions or a simple example on how to do it? I did find these relevant link: - http://ivan.fomentgroup.org/blog/2009/03/29/instant-chrome/
[ "You have to use the Qt.FramelessWindowHint for that, and then create your own Max, Min, Close buttons as Widgets and add them there. I have a good working toolkit for these types of softwares: http://traipse.assembla.com/spaces/ghostqt\nIn your case you should reclass the resizeEvent so you can change the flags. I...
[ 3, 2, 2 ]
[]
[]
[ "pyqt", "python", "qt", "tabs", "user_interface" ]
stackoverflow_0003630851_pyqt_python_qt_tabs_user_interface.txt
Q: Assigning to a dict Forgive me if this has been asked before. I did not know how to search for it. I'm quite familiar with the following idiom: def foo(): return [1,2,3] [a,b,c] = foo() (d,e,f) = foo() wherein the values contained within the left hand side will be assigned based upon the values returned fro...
Assigning to a dict
Forgive me if this has been asked before. I did not know how to search for it. I'm quite familiar with the following idiom: def foo(): return [1,2,3] [a,b,c] = foo() (d,e,f) = foo() wherein the values contained within the left hand side will be assigned based upon the values returned from the function on the rig...
[ "Dictionary items do not have an order, so while this works:\n>>> def bar():\n... return dict(a=1,b=2,c=3)\n>>> bar()\n{'a': 1, 'c': 3, 'b': 2}\n>>> (lettera,one),(letterb,two),(letterc,three) = bar().items()\n>>> lettera,one,letterb,two,letterc,three\n('a', 1, 'c', 3, 'b', 2)\n\nYou can see that you can't nece...
[ 4, 1 ]
[ "No, if you can not change bar function, you could create a dict from the output pretty easily.\nThis is the most compact solution. But I would prefer to modify the bar function to return a dict.\ndict(zip(['one', 'two', 'three'], bar()))\n\n" ]
[ -1 ]
[ "dictionary", "python" ]
stackoverflow_0003822519_dictionary_python.txt
Q: "chunksize" parameter in multiprocessing.Pool.map If I have a pool object with 2 processors for example: p=multiprocessing.Pool(2) and I want to iterate over a list of files on directory and use the map function could someone explain what is the chunksize of this function: p.map(func, iterable[, chunksize]) If I...
"chunksize" parameter in multiprocessing.Pool.map
If I have a pool object with 2 processors for example: p=multiprocessing.Pool(2) and I want to iterate over a list of files on directory and use the map function could someone explain what is the chunksize of this function: p.map(func, iterable[, chunksize]) If I set the chunksize for example to 10 does that means ev...
[ "Looking at the documentation for Pool.map it seems you're almost correct: the chunksize parameter will cause the iterable to be split into pieces of approximately that size, and each piece is submitted as a separate task.\nSo in your example, yes, map will take the first 10 (approximately), submit it as a task for...
[ 52 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0003822512_multiprocessing_python.txt
Q: Python, convert a number to a string 'as is' Using Python 2.6 I want to be able to convert numbers such as 00000, 000.00004 and 001 to strings. Such that each string is '00000', '000.00004' and '001' respectively. It is also necessary that the way to do this is the same with all numbers, and also copes when lette...
Python, convert a number to a string 'as is'
Using Python 2.6 I want to be able to convert numbers such as 00000, 000.00004 and 001 to strings. Such that each string is '00000', '000.00004' and '001' respectively. It is also necessary that the way to do this is the same with all numbers, and also copes when letters are fed into it. E.g. foo should become 'foo', ...
[ "There is no number 0000 or 001. There is only 0 and 1. If you want to produce a string representation of a number, you can use string formatting to pad zeros.\nn = 1\nprint '%03d' % n //001\n\n", "The first step would be: however you are getting a number that you think should be 00000 instead of 0 ... don't actu...
[ 8, 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0003822858_python_sqlite.txt
Q: Python App Engine: Task Queues I need to import some data to show it for user but page execution time exceeds 30 second limit. So I decided to split my big code into several tasks and try Task Queues. I add about 10-20 tasks to queue and app engine executes tasks in parallel while user is waiting for data. How can...
Python App Engine: Task Queues
I need to import some data to show it for user but page execution time exceeds 30 second limit. So I decided to split my big code into several tasks and try Task Queues. I add about 10-20 tasks to queue and app engine executes tasks in parallel while user is waiting for data. How can I determine that my tasks are compl...
[ "I've solved this in the past by keeping the status for the tasks in memcached, and polling (via Ajax) to determine when the tasks are finished. \nIf you go this way, it's best if you can always \"manually\" determine the status of the tasks without looking in memcached, since there's always the (slim) chance that...
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003821636_google_app_engine_python.txt
Q: What do we call this (new?) higher-order function? I am trying to name what I think is a new idea for a higher-order function. To the important part, here is the code in Python and Haskell to demonstrate the concept, which will be explained afterward. Python: >>> def pleat(f, l): return map(lambda t: f(*t),...
What do we call this (new?) higher-order function?
I am trying to name what I think is a new idea for a higher-order function. To the important part, here is the code in Python and Haskell to demonstrate the concept, which will be explained afterward. Python: >>> def pleat(f, l): return map(lambda t: f(*t), zip(l, l[1:])) >>> pleat(operator.add, [0, 1, 2, 3]) [1...
[ "Hmm... a counterpoint.\n(`ap` tail) . zipWith\n\ndoesn't deserve a name.\nBTW, quicksilver says:\n zip`ap`tail\n\nThe Aztec god of consecutive numbers\n", "Since it's similar to \"fold\" but doesn't collapse the list into a single value, how about \"crease\"? If you keep \"creasing\", you end up \"folding\" (sor...
[ 17, 6, 6, 5, 4, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 0 ]
[]
[]
[ "functional_programming", "haskell", "higher_order_functions", "python", "theory" ]
stackoverflow_0003774247_functional_programming_haskell_higher_order_functions_python_theory.txt
Q: Python ranking algorithm with 30 levels I trying find a simple python-based algorithmic ranking system. Here's the scenario: There will be 30 levels, level 1 starts at 0 points. 2000 points are required to achieve level 30. More points will be required as the levels progress. For example, to go from level 1 to 2 m...
Python ranking algorithm with 30 levels
I trying find a simple python-based algorithmic ranking system. Here's the scenario: There will be 30 levels, level 1 starts at 0 points. 2000 points are required to achieve level 30. More points will be required as the levels progress. For example, to go from level 1 to 2 might take 3 points. Level 2 to 3 might take 5...
[ "The usual solution is to use a logarithmic scale. If you use log base 2, then each level needs twice as many points. If you use a log base 10, each level needs 10 times the points. This way, you can \"bend\" the curve. See the Wikipedia page for the math.\n", "Use a logarithmic scale. If you want a code example:...
[ 3, 3 ]
[]
[]
[ "algorithm", "python", "ranking" ]
stackoverflow_0003823243_algorithm_python_ranking.txt
Q: Filtering a String for a Set of Characters this is from the 'python cookbook' but isn't explained that well. allchars = string.maketrans('','') def makefilter(keep): delchars = allchars.translate(allchars, keep) def thefilter(s): return s.translate(allchars,delchars) return thefilter if __name...
Filtering a String for a Set of Characters
this is from the 'python cookbook' but isn't explained that well. allchars = string.maketrans('','') def makefilter(keep): delchars = allchars.translate(allchars, keep) def thefilter(s): return s.translate(allchars,delchars) return thefilter if __name__ == '__main__': just_vowels = makefilter('...
[ "makefilter returns a function.\nIn the example code:\njust_vowels = makefilter('aeiou')\n\nthe variable just_vowels now refers to a function based on thefilter.\nThe code:\nprint just_vowels('tigere, igers, bigers')\n\nis calling that function, and setting its s parameter to the string 'tigere, igers, bigers'.\n",...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003822919_python.txt
Q: Django, Python calling Python code without waiting for response? I am using Django and am making some long running processes that I am just interacting with through my web user interface. Such as, they would be running all the time, checking a database value every few minutes and stopping only if this has changed...
Django, Python calling Python code without waiting for response?
I am using Django and am making some long running processes that I am just interacting with through my web user interface. Such as, they would be running all the time, checking a database value every few minutes and stopping only if this has changed (would be boolean true false). So, I want to be able to use Django to...
[ "Can't vouch for it because I haven't used it yet, but \"Celery\" does pretty much what you're asking for and was originally built specifically for Django.\nhttp://celeryproject.org/\nTheir example showing a simple task adding two numbers:\nfrom celery.decorators import task\n\n@task\ndef add(x, y):\n return x +...
[ 6, 0 ]
[]
[]
[ "django", "long_running_processes", "python" ]
stackoverflow_0003806574_django_long_running_processes_python.txt
Q: Python & C#: Is IronPython absolutely necessary? I'm primarily a C# programmer, but have been left with a project that leaves me with 2 options: Call out to a python script (saved as a .py file) and process the return value, OR... Rewrite the whole python script (involving 6 .py files in total) in C#. Naturally,...
Python & C#: Is IronPython absolutely necessary?
I'm primarily a C# programmer, but have been left with a project that leaves me with 2 options: Call out to a python script (saved as a .py file) and process the return value, OR... Rewrite the whole python script (involving 6 .py files in total) in C#. Naturally, Option 2 is a MAJOR waste of time if I can simply imp...
[ "Use Process.Start to run the Python script. In the ProcessStartInfo object, you specify:\n\nFileName = the path and file name of the Python script.\nArguments = any arguments that you want to pass to the script.\nRedirectStandardOutput = true (and RedirectStandardError if needed)\nUseShellExecute = false\n\nThen y...
[ 6, 2, 2 ]
[]
[]
[ "c#", "python" ]
stackoverflow_0003823880_c#_python.txt
Q: More pythonic way to write this? I have this code here: import re def get_attr(str, attr): m = re.search(attr + r'=(\w+)', str) return None if not m else m.group(1) str = 'type=greeting hello=world' print get_attr(str, 'type') # greeting print get_attr(str, 'hello') # world print get_attr(str, 'at...
More pythonic way to write this?
I have this code here: import re def get_attr(str, attr): m = re.search(attr + r'=(\w+)', str) return None if not m else m.group(1) str = 'type=greeting hello=world' print get_attr(str, 'type') # greeting print get_attr(str, 'hello') # world print get_attr(str, 'attr') # None Which works, but I am n...
[ "Python has a ternary operator. You're using it. It's just in the X if Y else Z form.\nThat said, I'm prone to writing these things out. Fitting things on one line isn't so great if you sacrifice clarity.\ndef get_attr(str, attr):\n m = re.search(attr + r'=(\\w+)', str)\n if m:\n return m.group(1)\n...
[ 10, 4, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003823980_python.txt
Q: Running Python command-line utility from Java I developed a command-line utility which needs to be called from a Java GUI application. The team in charge on the Java GUI would like to bind my command-line application to a button in the GUI; the Python application is such that at the time we have no time or interes...
Running Python command-line utility from Java
I developed a command-line utility which needs to be called from a Java GUI application. The team in charge on the Java GUI would like to bind my command-line application to a button in the GUI; the Python application is such that at the time we have no time or interest in rewriting it in Java. I have no experience wha...
[ "You should be able to execute a spawned process from Java using Runtime.exec(). Here's some examples.\nMake sure you capture the stdout and stderr (concurrently - see this answer for more details) so you can report on errors. You can capture the exit code of the application, so make sure that the application itsel...
[ 1, 0, 0 ]
[]
[]
[ "java", "python", "scripting" ]
stackoverflow_0003824249_java_python_scripting.txt