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: Weird list behavior in class I've written a class that has a list as a variable. I have a function that adds to that list and a function that outputs that list. class MyClass: myList = [] def addToList(self, myNumber): self.myList.append(myNumber) def outputList(self): for someNumber...
Weird list behavior in class
I've written a class that has a list as a variable. I have a function that adds to that list and a function that outputs that list. class MyClass: myList = [] def addToList(self, myNumber): self.myList.append(myNumber) def outputList(self): for someNumber in self.myList: print...
[ "Your syntax is wrong. You are using a class-static variable. Consider this:\nclass MyClass:\n myList = [] # Static variable\n\n def __init__(self):\n self.myRealList = [] # Member variable\n\nmyList is actually a part of the MyClass definition, and thus is visible not only by the class name, but ...
[ 6, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0008221507_list_python.txt
Q: how do i dump a single sqlite3 table in python? I would like to dump only one table but by the looks of it, there is no parameter for this. I found this example of the dump but it is for all the tables in the DB: # Convert file existing_db.db to SQL dump file dump.sql import sqlite3, os con = sqlite3.connect('exi...
how do i dump a single sqlite3 table in python?
I would like to dump only one table but by the looks of it, there is no parameter for this. I found this example of the dump but it is for all the tables in the DB: # Convert file existing_db.db to SQL dump file dump.sql import sqlite3, os con = sqlite3.connect('existing_db.db') with open('dump.sql', 'w') as f: fo...
[ "You can copy only the single table in an in memory db: \nimport sqlite3\n\ndef getTableDump(db_file, table_to_dump):\n conn = sqlite3.connect(':memory:') \n cu = conn.cursor()\n cu.execute(\"attach database '\" + db_file + \"' as attached_db\")\n cu.execute(\"select sql from attached_db.sqlite_mas...
[ 10, 3, 2 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0006677540_python_sqlite.txt
Q: Using WSGI on Redhat Linux I wanted to install WSGI on a RedHat linux box in order to make a Python server interface, but the only way I could find to do that was to use modwsgi, which is an Apache module. The whole reason I'm using WSGI is that I don't want to use Apache, so this kinda defeats the purpose. Does ...
Using WSGI on Redhat Linux
I wanted to install WSGI on a RedHat linux box in order to make a Python server interface, but the only way I could find to do that was to use modwsgi, which is an Apache module. The whole reason I'm using WSGI is that I don't want to use Apache, so this kinda defeats the purpose. Does anyone know of actual WSGI packa...
[ "You can also run something like uwsgi. It runs as a server on either a file or TCP socket, and you can hook into it with any web server you wish. I personally use Cherokee, but Apache or nginx, or anything else can use it too.\n", "I found out that WSGI is included in Python 2.5 and above, so you don't need to d...
[ 0, 0, 0 ]
[]
[]
[ "package", "python", "redhat" ]
stackoverflow_0008221114_package_python_redhat.txt
Q: Python topological sort using lists indicating edges Given lists: [1, 5, 6], [2, 3, 5, 6], [2, 5] etc. (not necessarily in any sorted order) such that if x precedes y in one list, then x precedes y in every list that have x and y, I want to find the list of all elements topologically sorted (so that x precedes y ...
Python topological sort using lists indicating edges
Given lists: [1, 5, 6], [2, 3, 5, 6], [2, 5] etc. (not necessarily in any sorted order) such that if x precedes y in one list, then x precedes y in every list that have x and y, I want to find the list of all elements topologically sorted (so that x precedes y in this list if x precedes y in any other list.) There mi...
[ "Here is a slightly simpler version of @unutbu's networkx solution:\nimport networkx as nx\ndata=[[1, 5, 6], [2, 3, 5, 6], [2, 5], [7]]\nG = nx.DiGraph()\nfor path in data:\n G.add_nodes_from(path)\n G.add_path(path)\nts=nx.topological_sort(G)\nprint(ts)\n# [7, 2, 3, 1, 5, 6]\n\n", "Using networkx, and in p...
[ 8, 6, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0008194078_algorithm_python.txt
Q: Is there a reason the SQLAlchemy ORM tutorial puts angle brackets around its __repr__ values? The SQLAlchemy ORM tutorial uses this class: >>> from sqlalchemy import Column, Integer, String >>> class User(Base): ... __tablename__ = 'users' ... ... id = Column(Integer, primary_key=True) ... name = Colum...
Is there a reason the SQLAlchemy ORM tutorial puts angle brackets around its __repr__ values?
The SQLAlchemy ORM tutorial uses this class: >>> from sqlalchemy import Column, Integer, String >>> class User(Base): ... __tablename__ = 'users' ... ... id = Column(Integer, primary_key=True) ... name = Column(String) ... fullname = Column(String) ... password = Column(String) ... ... def __ini...
[ "the angle bracket convention is used by the Python interpreter itself, so this is more of a question for ...GVR ?\n>>> class Foo(object):\n... pass\n... \n>>> f = Foo()\n>>> print repr(f)\n<__main__.Foo object at 0x1004ab290>\n\n", "Bear in mind that eval is not used too much; crafting strings for it (or che...
[ 4, 2, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0008221324_python_sqlalchemy.txt
Q: Is the insertion optimal? I want to insert some data into a table and I want the multiple insertion to be as fast as possible. I use sqlalchemy library for Python. I want to know if my insertion is optimal, or there is a better way to do that.Here is my code: from sqlalchemy import * from sqlalchemy import sc...
Is the insertion optimal?
I want to insert some data into a table and I want the multiple insertion to be as fast as possible. I use sqlalchemy library for Python. I want to know if my insertion is optimal, or there is a better way to do that.Here is my code: from sqlalchemy import * from sqlalchemy import schema metadata = schema.Met...
[ "If you see the log then you can check that \n2011-11-22 10:15:37,188 INFO sqlalchemy.engine.base.Engine SELECT DATABASE()\n2011-11-22 10:15:37,188 INFO sqlalchemy.engine.base.Engine ()\n2011-11-22 10:15:37,191 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'character_set%%'\n2011-11-22 10:15:37,191 INFO sq...
[ 3 ]
[]
[]
[ "insert", "python", "sqlalchemy" ]
stackoverflow_0008187016_insert_python_sqlalchemy.txt
Q: Python - Waiting for input from lots of sockets I'm working on a simple experiment in Python. I have a "master" process, in charge of all the others, and every single process has a connection via unix socket to the master process. I would like to be able for the master process to be able to monitor all of the so...
Python - Waiting for input from lots of sockets
I'm working on a simple experiment in Python. I have a "master" process, in charge of all the others, and every single process has a connection via unix socket to the master process. I would like to be able for the master process to be able to monitor all of the sockets for a response - but there could theoretically ...
[ "One hundred simultaneous threads might be pushing the reasonable limits of threading. If you find this is the cleanest way to organize your code, I'd say give it a try, but threading really doesn't scale very far.\nWhat works better is to use a technique like select to wait for one of the sockets to be readable / ...
[ 5, 1 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0008221981_python_sockets.txt
Q: Limiting Admin Choices Using limit_choices_to I would like to limit the choices for a ForeignKey in the admin UI using limit_choices_to; however, I would like to achieve this without changing the model, since the model is brought in from a library, that I don't have control over. What is the way of dynamically ach...
Limiting Admin Choices Using limit_choices_to
I would like to limit the choices for a ForeignKey in the admin UI using limit_choices_to; however, I would like to achieve this without changing the model, since the model is brought in from a library, that I don't have control over. What is the way of dynamically achieving this? Or could I use a field on the admin mo...
[ "Django provides an admin hook to modify a foreign keys queryset: formfield_for_foreignkey \nclass MyModelAdmin(admin.ModelAdmin):\n def formfield_for_foreignkey(self, db_field, request, **kwargs):\n if db_field.name == \"car\":\n kwargs[\"queryset\"] = Car.objects.filter(owner=request.user)\n ...
[ 14 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008221885_django_python.txt
Q: How to look up two directories in Python? I know that to go up to a parent directory, you should use parentname = os.path.abspath(os.path.join(yourpath, os.path.pardir)) But what if I want to get the name of a directory a few folders up? Say I am given /stuff/home/blah/pictures/myaccount/album, and I want to get ...
How to look up two directories in Python?
I know that to go up to a parent directory, you should use parentname = os.path.abspath(os.path.join(yourpath, os.path.pardir)) But what if I want to get the name of a directory a few folders up? Say I am given /stuff/home/blah/pictures/myaccount/album, and I want to get the names of the last two folders of "myaccount...
[ ">>> p='/stuff/home/blah/pictures/myaccount/album'\n>>> os.path.abspath(p).split(os.sep)[-1]\n'album'\n>>> os.path.abspath(p).split(os.sep)[-2]\n'myaccount'\n>>> os.path.abspath(p).split(os.sep)[-3]\n'pictures'\n>>> os.path.abspath(p).split(os.sep)[-4]\n'blah'\n\netc...\n", "There doesn't look to be anything part...
[ 3, 2, 2 ]
[]
[]
[ "directory", "parent", "python" ]
stackoverflow_0008221844_directory_parent_python.txt
Q: How to send part of the output of a Python script to a text file? I want to only save part of the output of script.py, and to a file in another folder. script.py prints out a list of file names and their sizes, like file_asfs.txt- 2KB file_jsdfhkjh.doc- 17KB .... If I want to save only the list of file names that...
How to send part of the output of a Python script to a text file?
I want to only save part of the output of script.py, and to a file in another folder. script.py prints out a list of file names and their sizes, like file_asfs.txt- 2KB file_jsdfhkjh.doc- 17KB .... If I want to save only the list of file names that are exactly 2KB in a text file /temp/filelist , how do I go about doin...
[ "script.py | grep \"\\\\b2KB$\" > output.txt\n\n", "you could create a program to filter it:\nfilter.py:\nimport sys\nfor line in sys.stdin:\n line=line.strip()\n if line.endswith(\"- 2KB\"):\n print line\n\nthen go\npython script.py | python filter.py > /temp/filelist.txt\n\n" ]
[ 2, 1 ]
[]
[]
[ "python", "save", "text_files" ]
stackoverflow_0008222357_python_save_text_files.txt
Q: Newtons Method in Python I'm writing a program in python that will solve for zeros using newtons method. I finished writing the rough version of it, then realized a couple different things and was wondering if I need to impement/change this. (knowledge of the subject may help) def main(): dir(sympy) prin...
Newtons Method in Python
I'm writing a program in python that will solve for zeros using newtons method. I finished writing the rough version of it, then realized a couple different things and was wondering if I need to impement/change this. (knowledge of the subject may help) def main(): dir(sympy) print ("NEWTONS METHOD") print ...
[ "Q1: I agree.\nQ2: x = n near the top of loop. You want to move on.\n", "First of all, the value of x isn't changing in your while loop.\nSecond, the termination criterion should be that the \"current\" estimation vs the \"previous\" one should be \"sufficiently close\", that is.. you should use something like:\...
[ 2, 2 ]
[]
[]
[ "newtons_method", "numerical_methods", "python" ]
stackoverflow_0008222247_newtons_method_numerical_methods_python.txt
Q: Extracting text from a nested tags in XML using BeautifulSoup in python I am trying to extract the text out of nested tags for example the xml is in the form: <thread id = 1_1> <post id = 1> <title> <ne>MediaPortal</ne> Install Guide </title> <content> <ne>MediaPortal</ne> Install Guide 0...
Extracting text from a nested tags in XML using BeautifulSoup in python
I am trying to extract the text out of nested tags for example the xml is in the form: <thread id = 1_1> <post id = 1> <title> <ne>MediaPortal</ne> Install Guide </title> <content> <ne>MediaPortal</ne> Install Guide 0. Introduction and pre-requisites <ne>MediaPortal</ne> is an open-sour...
[ "From BeautifulSoup documentation:\nFor your convenience, if a tag has only one child node,\nand that child node is a string,the child node is made\navailable as tag.string, as well as tag.contents[0].\n\nHowever, in your case:\n>>> t = soup.find('title')\n<title><ne>MediaPortal</ne> Install Guide</title>\n\nHence,...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "xml_parsing" ]
stackoverflow_0008222908_beautifulsoup_python_xml_parsing.txt
Q: How to make a Structured Array from multiple simple array import numpy as np a=np.array([1,2,3,4,5,6,7,8,9]) b=np.array(["a","b","c","d","e","f","g","h","i"]) c=np.array([9,8,7,6,5,4,3,2,1]) datatype=np.dtype({ 'names':['num','char','len'], 'formats':['i','S32','i'] }) d=np.array(zip(a,b,c),dtype=datatype) th...
How to make a Structured Array from multiple simple array
import numpy as np a=np.array([1,2,3,4,5,6,7,8,9]) b=np.array(["a","b","c","d","e","f","g","h","i"]) c=np.array([9,8,7,6,5,4,3,2,1]) datatype=np.dtype({ 'names':['num','char','len'], 'formats':['i','S32','i'] }) d=np.array(zip(a,b,c),dtype=datatype) the code above uses zip() to create a list first and then convert...
[ "zip does create a list of tuples, which could be memory-intensive if the arrays are big. You could use itertools.izip to be more memory-efficient:\nimport itertools\nd=np.fromiter(itertools.izip(a,b,c),dtype=datatype)\n\n\nFor small arrays of length ~10:\nIn [68]: %timeit np.fromiter(itertools.izip(a,b,c),dtype=da...
[ 2, 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0008220689_numpy_python.txt
Q: Is this correct usage of super in python? class SessionWizardView(WizardView): @classonlymethod def as_view(cls, *args, **kwargs): #...snipped.. pass class ParentWizard(SessionWizardView): @classonlymethod def as_view(cls, *args, **kwargs): return super(SessionWizardView, c...
Is this correct usage of super in python?
class SessionWizardView(WizardView): @classonlymethod def as_view(cls, *args, **kwargs): #...snipped.. pass class ParentWizard(SessionWizardView): @classonlymethod def as_view(cls, *args, **kwargs): return super(SessionWizardView, cls).as_view( ... ) class ChildWizard(ParentWiz...
[ "The usual usage of super for classmethods is to put cls first and the name of the current class as the second argument:\nclass SessionWizardView(WizardView):\n @classonlymethod\n def as_view(cls, *args, **kwargs):\n #...snipped..\n pass\n\nclass ParentWizard(SessionWizardView):\n @classonlym...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008223136_django_python.txt
Q: Preventing django from appending "_id" to a foreign key field In django, if I set a field in a model to a foreign key, "_id" is appended to the name of that field. How can this be prevented? A: You can set the field's db_column attribute to whatever you'd like. A: When using the foreign field in a model, Djang...
Preventing django from appending "_id" to a foreign key field
In django, if I set a field in a model to a foreign key, "_id" is appended to the name of that field. How can this be prevented?
[ "You can set the field's db_column attribute to whatever you'd like.\n", "When using the foreign field in a model, Django creates two fields: One for the actual link, and one that references the other model.\nclass A(Model):\n i = IntegerField()\n\nclass B(Model):\n a = ForeignKey(A)\n\nIn B there is now tw...
[ 36, 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008223519_django_python.txt
Q: How to get server_name from url? I have ( for example ) a link: http://10.100.0.178:8134/hds-live/livepkgr/_definst_/liveevent.f4m How to get server_name (http://10.100.0.178:8134/ ) from this link ? Any standard function ? A: import urlparse a = 'http://10.100.0.178:8134/hds-live/livepkgr/_definst_/liveevent....
How to get server_name from url?
I have ( for example ) a link: http://10.100.0.178:8134/hds-live/livepkgr/_definst_/liveevent.f4m How to get server_name (http://10.100.0.178:8134/ ) from this link ? Any standard function ?
[ "import urlparse\n\na = 'http://10.100.0.178:8134/hds-live/livepkgr/_definst_/liveevent.f4m'\noutput = '{0.scheme}://{0.netloc}'.format(urlparse.urlsplit(a))\n\n# output == 'http://10.100.0.178:8134'\n\n", "Yes there is.\nhttp://docs.python.org/library/urlparse.html [deprecated]\nUpdated due to luckydonald's comm...
[ 4, 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008223551_python.txt
Q: Python won't run a basic fibonacci function I'm new to python and can't figure out what the problem with simple fibonacci function is. It also calculates amount of iterations the function makes. Here is the code: times = 0; def fib(n): times = times + 1 if n == 0: return 0 elif n == 1: ...
Python won't run a basic fibonacci function
I'm new to python and can't figure out what the problem with simple fibonacci function is. It also calculates amount of iterations the function makes. Here is the code: times = 0; def fib(n): times = times + 1 if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib...
[ "It looks like you have mixed tabs and spaces, this is evil in python ;) You have to choose, tabs or spaces.\nThe code you post seems to work, except the times = times + 1 that complains about UnboundLocalError: local variable 'times' referenced before assignment, normal as times is a global variable and should be ...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008223725_python.txt
Q: cPickle.UnpicklingError: pickle data was truncated i use a Remote Procedure call to communicate between two prozesses. I send objects from the on hand to the other. the object is a object by a django model. The object has different variables, integers and strings. If i change only integer variables everything work...
cPickle.UnpicklingError: pickle data was truncated
i use a Remote Procedure call to communicate between two prozesses. I send objects from the on hand to the other. the object is a object by a django model. The object has different variables, integers and strings. If i change only integer variables everything works fine. if i change a string variable in the first time ...
[ "I solved my own problem. But first the error message I describe in my question is not meaningful.\nI am the problem tackled new and have used the Pyro4 Framework. So i got a new error message which was equivalent to the old but clearly. U cant pickle class objects. \nBecause I need in my case only the attribute va...
[ 1 ]
[]
[]
[ "django_models", "pickle", "python", "rpc", "sockets" ]
stackoverflow_0008209956_django_models_pickle_python_rpc_sockets.txt
Q: printing a variable in python I have this python code which set A or B in a class. I want to print what this class receives: if options.A: print "setting A" class TmpClass(A): pass else: print "nothing set in the command line => setting to B" class TmpClass(B): pass print "selected=",TmpClass I want ...
printing a variable in python
I have this python code which set A or B in a class. I want to print what this class receives: if options.A: print "setting A" class TmpClass(A): pass else: print "nothing set in the command line => setting to B" class TmpClass(B): pass print "selected=",TmpClass I want to see either A or B in the output ...
[ "What your code is doing, translated in English is:\nif option.A has a value that evaluates to True:\n define an empty class called \"TmpClass\" that inherits from the object called \"A\"\notherwise:\n define an empty class called \"TmpClass\" that inherits from the object called \"B\"\n\nNow, if what the cod...
[ 3, 1, 1, 0 ]
[]
[]
[ "class", "printing", "python" ]
stackoverflow_0008224341_class_printing_python.txt
Q: Debug PyDev+Eclipse - Code not reloads after code change in breakpoint/suspend mode I often doing such steps and want to optimize debug speed: I am setting some breakpoints. I am running Google Appengine Application (Python 2.5.2+). When breakpoint occur I often change code to fix bugs. After code change want to...
Debug PyDev+Eclipse - Code not reloads after code change in breakpoint/suspend mode
I often doing such steps and want to optimize debug speed: I am setting some breakpoints. I am running Google Appengine Application (Python 2.5.2+). When breakpoint occur I often change code to fix bugs. After code change want to test again but there is problem if I changed code in breakpoint/suspend mode the applica...
[ "The way the debug works is not by executing the source line-by-line. The debug \"compiles\" your source to bytecode (the .pyc files) and execute those, not your source.\nThe debug only keeps track of what piece of the .pyc files correspond to what line of your .py ones and display that information for your conveni...
[ 5 ]
[]
[]
[ "debugging", "google_app_engine", "pydev", "python" ]
stackoverflow_0008224592_debugging_google_app_engine_pydev_python.txt
Q: qrcode generator using python for windows I am looking for qrcode generator for python window version. Can anyone help me to find out. I didn't get anywhere. Please help me. Thanks, manu A: either you have to Compile it yourself; or if you only need to generate the codes (i.e. encoding but no decoding), use...
qrcode generator using python for windows
I am looking for qrcode generator for python window version. Can anyone help me to find out. I didn't get anywhere. Please help me. Thanks, manu
[ "either you have to \n\nCompile it yourself; or \nif you only need to generate the codes (i.e. encoding but no decoding), use pyqrencode that you can get from PyPi (e.g. pip install pyqrencode)\n\nIf you don't have pip, I suggest you start by installing setuptools and then use easy_install to install pip (of course...
[ 4, 4, 1, 0, 0 ]
[]
[]
[ "python", "qr_code" ]
stackoverflow_0003888125_python_qr_code.txt
Q: 'SentinelObject' object has no attribute 'reset_mock' I am not sure why the following code is not working. I am using the Mock framework. Anyone could explain it to me? The error I get is this: $ python test_mock.py Calls the mock object method. not a real one. ... ERROR =========================================...
'SentinelObject' object has no attribute 'reset_mock'
I am not sure why the following code is not working. I am using the Mock framework. Anyone could explain it to me? The error I get is this: $ python test_mock.py Calls the mock object method. not a real one. ... ERROR ====================================================================== ERROR: Calls the mock object ...
[ "The problems (sadly) is trivial. I am patching isinstance() to always return True. So, somewhere in the bowels of the module, something is asking whether my mock object is a Sentinel and (since I am overriding the return value), True is returned. Thus the wrong internal behaviour is exhibited. \nThe solution is...
[ 4 ]
[]
[]
[ "mocking", "python", "unit_testing" ]
stackoverflow_0008224622_mocking_python_unit_testing.txt
Q: easy_install-3.2.exe vs easy_install.exe? For Python 3.2, What is recommended: easy_install-3.2 or easy_install? Why two execs? What's the difference? One more question: distribute or setuptools? setuptools is obviously not working on Intel Win64/python3.2 (or not available as of writing this post). A: Answer...
easy_install-3.2.exe vs easy_install.exe?
For Python 3.2, What is recommended: easy_install-3.2 or easy_install? Why two execs? What's the difference? One more question: distribute or setuptools? setuptools is obviously not working on Intel Win64/python3.2 (or not available as of writing this post).
[ "Answering just to the first question.\nRegarding easy_install, since you might have multiple python versions installed, you might have also different easy_install versions installed (one for each python version). In that case, easy_install will be the default version and easy_install-X.Y will be the version to ins...
[ 3, 2 ]
[]
[]
[ "easy_install", "python", "python_3.x", "setuptools" ]
stackoverflow_0008223029_easy_install_python_python_3.x_setuptools.txt
Q: Passing command line argument to another file imported in Python I have a python file (html2text.py) which gives the desired result when i pass command line argument to it i.e., in the following way: python html2text.py file.txt where file.txt contains the source code of a web-site and the result is displayed on ...
Passing command line argument to another file imported in Python
I have a python file (html2text.py) which gives the desired result when i pass command line argument to it i.e., in the following way: python html2text.py file.txt where file.txt contains the source code of a web-site and the result is displayed on the console... I want to use it in another file (let say a.py) and s...
[ "Good way is to create some API in your html2text.py. For example:\n# html2text.py\n\ndef parse(filename):\n f = open(filename)\n # do the stuff\n return output_string\n\ndef main():\n import sys\n print parse(sys.argv[1])\n\nif __name__ == '__main__':\n main()\n\nThen you will be able to use it i...
[ 1, 1 ]
[]
[]
[ "command_line_arguments", "python" ]
stackoverflow_0008225197_command_line_arguments_python.txt
Q: How can I download and read a URL with universal newlines? I was using urllib.urlopen with Python 2.7, but I need to process the downloaded HTML document and its contained newlines (within a <pre> element). The urllib docs indicates urlopen will not use universal newlines. How can I do this? A: Unless the HTML f...
How can I download and read a URL with universal newlines?
I was using urllib.urlopen with Python 2.7, but I need to process the downloaded HTML document and its contained newlines (within a <pre> element). The urllib docs indicates urlopen will not use universal newlines. How can I do this?
[ "Unless the HTML file is already on your disk, urlopen() will handle correctly all formats of newlines (\\n, \\r\\n and \\r) in the HTML file you want to parse (that is it will convert them to \\n), according to the urllib docs:\n\n\"If the URL does not have a scheme identifier, or if it has file: as its scheme ide...
[ 3, 2 ]
[]
[]
[ "python", "python_2.7", "urllib", "web", "web_scraping" ]
stackoverflow_0008221296_python_python_2.7_urllib_web_web_scraping.txt
Q: Changing font in Window created in python code Changing font in Window created in python code. I have some working python code that shows the MMDDYYYY HH:MM:ss in a window I would like to add additional text above the date and time along with increasing the size of the font (of the data and time MMDDYYYY HH:MM:SS)...
Changing font in Window created in python code
Changing font in Window created in python code. I have some working python code that shows the MMDDYYYY HH:MM:ss in a window I would like to add additional text above the date and time along with increasing the size of the font (of the data and time MMDDYYYY HH:MM:SS). I tried to add different text and font size but i...
[ "Using markup most likely will do what you need. First, enable it on the label. Then instead of using set_text, use set_markup:\nself.label.set_use_markup(True)\nt = time.strftime('%m/%d/%Y-%H%M%S')\nself.label.set_markup('<span size=\"18000\">The time:</span> ' + t)\n\nAs a reference: the markup language used by G...
[ 1 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0008224174_pygtk_python.txt
Q: confusing behavior with python import Hi, there. I have two files: a.py: print('in a') import b print('var') VAR = 1 def p(): print('{}, {}'.format(VAR, id(VAR))) if __name__ == '__main__': VAR = -1 p() b.p() # Where does this VAR come from? b.py: print('in b') import a def p(): a.p() I d...
confusing behavior with python import
Hi, there. I have two files: a.py: print('in a') import b print('var') VAR = 1 def p(): print('{}, {}'.format(VAR, id(VAR))) if __name__ == '__main__': VAR = -1 p() b.p() # Where does this VAR come from? b.py: print('in b') import a def p(): a.p() I don't understand why there're two different ...
[ "You might want to read up on global variables? To quote:\n\nIf a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as ‘global’.\n\n...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0008225562_python.txt
Q: Python multiply int to instance both ways Ok, so I'm creating a Vector class (the mathematical vector, like [1,3]), and I want to multiply an instance of Vector with an int. First, I implemented the __mul__ method, and it works fine. However, this don't quite solves the problem. a = Vector(4,3) # Creates a vector...
Python multiply int to instance both ways
Ok, so I'm creating a Vector class (the mathematical vector, like [1,3]), and I want to multiply an instance of Vector with an int. First, I implemented the __mul__ method, and it works fine. However, this don't quite solves the problem. a = Vector(4,3) # Creates a vector, [4,3] a*4 # This works fine, and prints [...
[ "your Vector class can provide the __rmul__() reflected multiply method, which is the method used to implement multiplication when the left-hand operand does not support the operation.\n" ]
[ 10 ]
[]
[]
[ "operator_overloading", "python" ]
stackoverflow_0008225629_operator_overloading_python.txt
Q: Python argument passing in object oriented programming I apologize if this was asked somewhere else, but I do not know how else to formulate this question. I am a physicist and Python is my first object-oriented language. I love this language for its clean code, and somehow everything works as intended (by me ;). ...
Python argument passing in object oriented programming
I apologize if this was asked somewhere else, but I do not know how else to formulate this question. I am a physicist and Python is my first object-oriented language. I love this language for its clean code, and somehow everything works as intended (by me ;). However I have one problem, maybe it is more of a design cho...
[ "\nshould i mainly pass arguments or manipulate the object data directly\n\nThink of objects as systems with a state. If data belongs to the state of the object, then it should be packaged in the object as a member. Otherwise, it should be passed to its methods as an argument.\nIn your example, what you should do d...
[ 4, 2 ]
[]
[]
[ "arguments", "oop", "python" ]
stackoverflow_0008225557_arguments_oop_python.txt
Q: Python: How to force a "print" to use __unicode__ instead of __str__, or otherwise naturally "print" the message without explicitly calling unicode() Basically I just want to be able to create instances using a class called Bottle: eg class Bottle(object):... and then in another module be able to simply "print" a...
Python: How to force a "print" to use __unicode__ instead of __str__, or otherwise naturally "print" the message without explicitly calling unicode()
Basically I just want to be able to create instances using a class called Bottle: eg class Bottle(object):... and then in another module be able to simply "print" any instance without having to hack code to explicitly call a character encoding routine. In summary, when I try: obj=Bottle(u"味精") print obj Or to an "in ...
[ "if you use sys.stdout = codecs.getwriter(encoding)(sys.stdout) then you should pass Unicode strings to print:\n>>> print u\"%s\" % Bottle(u\"魯賓遜漂流記\")\ndebug: __unicode__ 魯賓遜漂流記\n{{{魯賓遜漂流記}}}\n\nAs @bobince points out in the comments: avoid changing sys.stdout in such manner otherwise it might break any library co...
[ 6 ]
[]
[]
[ "character_encoding", "cjk", "python", "string", "unicode" ]
stackoverflow_0008222270_character_encoding_cjk_python_string_unicode.txt
Q: ConfigParser and 2 config files I want to split my config file to 2 config files: common.conf and particular.conf. It's possible parse 2 config files as one config ? A: Just pass all the filenames to configparser. It's in the docs: Attempt to read and parse a list of filenames, returning a list of filenames w...
ConfigParser and 2 config files
I want to split my config file to 2 config files: common.conf and particular.conf. It's possible parse 2 config files as one config ?
[ "Just pass all the filenames to configparser. It's in the docs:\n\nAttempt to read and parse a list of filenames, returning a list of\n filenames which were successfully parsed. If filenames is a string or\n Unicode string, it is treated as a single filename. If a file named in\n filenames cannot be opened, that...
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0008225594_python.txt
Q: Difficulty using Python's socket.gethostbyaddr() I am trying to reverse dns a list of IPs using socket.gethostbyaddr() in python, which returns 'Unknown Host' for some values, but using dig for the same ip returns the Hostname. Also, dig seems to be significantly faster than using python module, is there any speci...
Difficulty using Python's socket.gethostbyaddr()
I am trying to reverse dns a list of IPs using socket.gethostbyaddr() in python, which returns 'Unknown Host' for some values, but using dig for the same ip returns the Hostname. Also, dig seems to be significantly faster than using python module, is there any specific reasons for that? import socket # This returns 'U...
[ "From the comments...\n\nwhereas dig -x 114.143.51.197+short gives me the hostname.\n\nI'm sorry, but you are mistaken. 114.143.51.197 does not have a PTR record... therefore socket.gethostbyaddr() should throw an error... To process this use-case correctly, add a try / except clause that traps socket.herror\n>>> ...
[ 16 ]
[]
[]
[ "dig", "gethostbyaddr", "networking", "python", "python_sockets" ]
stackoverflow_0007832264_dig_gethostbyaddr_networking_python_python_sockets.txt
Q: python - Size limit of set data type I have a list with 7,200,000 elements in it. When I try to convert it with set() it cuts out to 4,500,000 elements. What can I do to bypass this problem? I'm using Python 3.2.2 x86 on Windows. A: I think your list has duplicate elements which are removed in set. Sets include ...
python - Size limit of set data type
I have a list with 7,200,000 elements in it. When I try to convert it with set() it cuts out to 4,500,000 elements. What can I do to bypass this problem? I'm using Python 3.2.2 x86 on Windows.
[ "I think your list has duplicate elements which are removed in set. Sets include unique elements only.\n" ]
[ 11 ]
[]
[]
[ "python" ]
stackoverflow_0008226006_python.txt
Q: win32print and multiple printers I should print a local pdf file, if printer_name is defined (a normal string) the program should send the document to a specific printer otherwise it should use the default printer. This code works but use the default printer anyway! global printer_name if printer_name: print "...
win32print and multiple printers
I should print a local pdf file, if printer_name is defined (a normal string) the program should send the document to a specific printer otherwise it should use the default printer. This code works but use the default printer anyway! global printer_name if printer_name: print "printer",nome_stampante else: nome...
[ "Your code use global variables and nobody knows where printer_name is set and what is in nome_stampante. I propose you to use function that will print file using chosen printer. This can look like:\nimport win32api\nimport win32print\n\ndef win_print(filename, printer_name = None):\n if not printer_name:\n ...
[ 2 ]
[]
[]
[ "pdf", "printing", "python", "win32com", "windows" ]
stackoverflow_0008224133_pdf_printing_python_win32com_windows.txt
Q: Client side s3 upload and returning the public url of the image I am writing a client side image uploader library for python. I need to upload an image to Amazon S3 and return the public URL of the image. I can do this using BOTO however I have to share my Secret Key which is not the correct way of doing it. As an...
Client side s3 upload and returning the public url of the image
I am writing a client side image uploader library for python. I need to upload an image to Amazon S3 and return the public URL of the image. I can do this using BOTO however I have to share my Secret Key which is not the correct way of doing it. As an alternative, I can use Browser upload using Amazon's POST request bu...
[ "I have the same issue. The only thing I have found is to make the image public on save and later use:\nitem.image.url.split('?')[0]\n\nto get the URL.\n", "How about using the urlparse module to get the URL without the query parameters?\n" ]
[ 1, 1 ]
[]
[]
[ "amazon_s3", "boto", "python" ]
stackoverflow_0007007584_amazon_s3_boto_python.txt
Q: sort a dict type variable by value in python I have a dict type variable like {'key1':6,'key2':1,'key3':5,'key4':44} my dictionary contains millions of key:val pair I want to store it in txt file such that key corresponding to highest val comes first and so on in descending order eg my txt file will look like key4...
sort a dict type variable by value in python
I have a dict type variable like {'key1':6,'key2':1,'key3':5,'key4':44} my dictionary contains millions of key:val pair I want to store it in txt file such that key corresponding to highest val comes first and so on in descending order eg my txt file will look like key4: 44 key1: 6 key3: 5 key2: 1
[ "d = {'key1': 6, 'key2': 1, 'key3': 5, 'key4': 44}\nfor k in sorted(d, key=d.get, reverse=True):\n print \"%s: %s\" % (k, d[k])\n\nprints\nkey4: 44\nkey1: 6\nkey3: 5\nkey2: 1\n\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0008226794_python.txt
Q: GAE Send mail - > How to replace mail@myapp.appspotmail.com to mail@mydomain.com According documentation Google App Engine could send mail but from restricted list of addresses -> http://code.google.com/intl/pl/appengine/docs/python/mail/emailmessagefields.html How to send email from Google App Engine with "from:"...
GAE Send mail - > How to replace mail@myapp.appspotmail.com to mail@mydomain.com
According documentation Google App Engine could send mail but from restricted list of addresses -> http://code.google.com/intl/pl/appengine/docs/python/mail/emailmessagefields.html How to send email from Google App Engine with "from:" of custom domain i.e. mydomain.com? Is it need configuration or use of custom library...
[ "You should be able to send it as long as the email id is registered as an administrator of the App Engine app. See this post for more info.\n", "The sender address must be a verfied dev, owner or viewer of the app or a logged in google user. I can send emails from admin@mycustomdomain.net after adding that email...
[ 4, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008226787_google_app_engine_python.txt
Q: Decoding java objects in python Is it possible to decode java objects in python? I know the structure of the java class that returns the data. The data is returned with the header of 'Transfer-Encoding: chunked' Or do I need to get the return data sent as xml / json? This is an example of the response I get; (Not...
Decoding java objects in python
Is it possible to decode java objects in python? I know the structure of the java class that returns the data. The data is returned with the header of 'Transfer-Encoding: chunked' Or do I need to get the return data sent as xml / json? This is an example of the response I get; (Note some of the control characters are ...
[ "--- Edited as more details became available ---\nThe content of this HTTP response is a serialized Java object. \nJava serialization is a process by which an in-memory object gets packed into transport-friendly bytes for the purpose of being read by another JVM. In short, you need to read the serialization forma...
[ -1 ]
[]
[]
[ "decoding", "java", "javabeans", "json", "python" ]
stackoverflow_0008227332_decoding_java_javabeans_json_python.txt
Q: Python: substitution in subprocess call I do for in range(...):, and I need to substitute i in a subprocess call. I tried to do it like this: myStr = "'(insert \"%g\")'" %i subprocess.Popen(["emacs", "--batch", "+83:28", "md.mdp", "--eval", eval("myStr"), "-f", "save-buffer", "--kill"], ...
Python: substitution in subprocess call
I do for in range(...):, and I need to substitute i in a subprocess call. I tried to do it like this: myStr = "'(insert \"%g\")'" %i subprocess.Popen(["emacs", "--batch", "+83:28", "md.mdp", "--eval", eval("myStr"), "-f", "save-buffer", "--kill"], stdout=subprocess.PIPE)...
[ "I'd say that the problem is that you don't need to quote the insert statement part. The reason for this is that you use quotes in a shell to make it clear that the string between quotes is to be passed as a single argument.\nHowever, in subprocess.Popen you're using an array to perform the same functionality, so t...
[ 1, 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0008223137_python_subprocess.txt
Q: Strange "local" folder inside virtualenv folder After I create my virtualenv environment (VE), inside it there is a symbolic link named "local". It points to the VE folder, which means that if you open it you end up in the same folder that you started in. I wouldn't care about that, but it makes some autocompletio...
Strange "local" folder inside virtualenv folder
After I create my virtualenv environment (VE), inside it there is a symbolic link named "local". It points to the VE folder, which means that if you open it you end up in the same folder that you started in. I wouldn't care about that, but it makes some autocompletion "wizards" in PyCharm unusable (they show the same i...
[ "According to the source the local symlink was put in place as a fix for a bug\nthat affected platforms using the \"posix_local\" install scheme. This change was introduced in version 1.6.3.\nThe problem you described has been addressed by this pull request on github. This proposed patch changes the symlinks to poi...
[ 22 ]
[]
[]
[ "python", "virtualenv" ]
stackoverflow_0008227120_python_virtualenv.txt
Q: Alignment in a GridLayout in PyQt4 I'm trying to create a QGridLayout in PyQt4, and I can't figure out for the life of me how to change the alignment of the contents of the cells. The docs say that any nonzero value for the 5th (6th counting self) argument means that the element being added doesn't fill the grid ...
Alignment in a GridLayout in PyQt4
I'm trying to create a QGridLayout in PyQt4, and I can't figure out for the life of me how to change the alignment of the contents of the cells. The docs say that any nonzero value for the 5th (6th counting self) argument means that the element being added doesn't fill the grid space, but so far I've not found any val...
[ "import PyQt4.QtCore.Qt\n\nWon't work, since that last Qt isn't a module (it's most likely just a class providing namespacing). Do the following:\nfrom PyQt4 import QtCore\n\nThen for, say, right alignment:\nQtCore.Qt.AlignRight\n\nThis is what you should pass to the alignment argument of QGridLayout.addItem\n", ...
[ 13, 0 ]
[]
[]
[ "pyqt4", "python", "qtgui" ]
stackoverflow_0008227735_pyqt4_python_qtgui.txt
Q: What does `if name == "__main__"` mean in Python? Possible Duplicate: What does <if name==“main”:> do? I have wrote scripts in Python for quite a while now and I study more of Python as I need it. When reading other people's code I meet if name == "__main__": construct quite often. What is it good for? A: Thi...
What does `if name == "__main__"` mean in Python?
Possible Duplicate: What does <if name==“main”:> do? I have wrote scripts in Python for quite a while now and I study more of Python as I need it. When reading other people's code I meet if name == "__main__": construct quite often. What is it good for?
[ "This allows you to use the same file both as a library (by importing it) or as the starting point for an application.\nFor example, consider the following file:\n# hello.py\ndef hello(to=__name__):\n return \"hello, %s\" % to\n\nif __name__ == \"__main__\":\n print hello(\"world\")\n\nYou can use that code i...
[ 29, 4 ]
[]
[]
[ "module", "python", "scope" ]
stackoverflow_0008228257_module_python_scope.txt
Q: Can python function be called by a SQL server trigger? I have a database in MS SQL Server 2008 that has 3 tables. I want to create a trigger for INSERT, UPDATE and DELETE for each row for these tables. For the trigger function I want to call a python function. The python script needs to write some of the columns f...
Can python function be called by a SQL server trigger?
I have a database in MS SQL Server 2008 that has 3 tables. I want to create a trigger for INSERT, UPDATE and DELETE for each row for these tables. For the trigger function I want to call a python function. The python script needs to write some of the columns from the row for which the trigger occurred and write it to a...
[ "As explained here you can attach some .NET methods in SQL triggers, and then use IronPython to code your trigger, but it will cost you in term of security and performance.\nYou can also use Database Email which is able to send an email which the content of what you need to catch, and grab it elsewhere in your own ...
[ 4 ]
[]
[]
[ "python", "sql_server_2008" ]
stackoverflow_0008228160_python_sql_server_2008.txt
Q: Advice on how to design a datastructure I have a file from which I am reading the data. I need advice on how to design the data structure which does the following: So, the data is of form id_1::id_2::similiarity_score Now, though the data is in this form but it also means that id_2::id_1::same_similiarity_Score ...
Advice on how to design a datastructure
I have a file from which I am reading the data. I need advice on how to design the data structure which does the following: So, the data is of form id_1::id_2::similiarity_score Now, though the data is in this form but it also means that id_2::id_1::same_similiarity_Score So, what I want is a datastructure which whe...
[ "A general trick for this sort of thing is to find a canonicalisation - a function that maps all members of a particular class to the same object. In this case, you might achieve it by sorting the first two components, which will transform B::A::Score to A::B::Score, while leaving A::B::Score as it is.\n", "It se...
[ 3, 2, 0 ]
[]
[]
[ "algorithm", "data_structures", "python" ]
stackoverflow_0008216117_algorithm_data_structures_python.txt
Q: Override admin.TabularInline fields Possible Duplicate: Override django-admin edit form field values for encrypted data The inline model has encrypted data and I need to override the method that renders each field in admin.TabularInline to decrypt the data. A: You can add functions to your TabularInline and th...
Override admin.TabularInline fields
Possible Duplicate: Override django-admin edit form field values for encrypted data The inline model has encrypted data and I need to override the method that renders each field in admin.TabularInline to decrypt the data.
[ "You can add functions to your TabularInline and then show them as fields:\nclass MyTabularInline(admin.TabularInline):\n model = MyModel\n readonly_fields = ['decrypt_first_field', 'decrypt_second_field']\n\n def decrypt_first_field(self, obj):\n if obj.first_field:\n return decrypt(obj....
[ 4 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0008228274_django_django_admin_python.txt
Q: Pip NLTK install issue on Ubuntu using Virtualenv For reference here is the nltk installation documentation nltk here Is there a way to install nltk using pip and virtualenv? I have installed the dependencies using pip into my virtualenv but when I attempt to install nltk it fails. The error is that there is no se...
Pip NLTK install issue on Ubuntu using Virtualenv
For reference here is the nltk installation documentation nltk here Is there a way to install nltk using pip and virtualenv? I have installed the dependencies using pip into my virtualenv but when I attempt to install nltk it fails. The error is that there is no setup script. There is source installation instructions f...
[ "It looks like pip is grabbing the first .tar.gz package from PyPI. For nltk, this is a macosx binary. You will have to explicitly point pip to the correct package.\nThe easiest way to do this is to just provide the full path to the package.\npip install http://pypi.python.org/packages/source/n/nltk/nltk-2.0.1rc1...
[ 4 ]
[]
[]
[ "nltk", "pip", "python", "ubuntu", "virtualenv" ]
stackoverflow_0008190545_nltk_pip_python_ubuntu_virtualenv.txt
Q: How to visualize geocoordinates by dots with python I have a whole bunch of geocoordinates (around 125000 from all over the world) which I want to visualize in a coordinate system (for printing later). Which is the easiest way to go? A: For simple lon/lat [x/y] dots, the matplotlib does the job. If you need to ...
How to visualize geocoordinates by dots with python
I have a whole bunch of geocoordinates (around 125000 from all over the world) which I want to visualize in a coordinate system (for printing later). Which is the easiest way to go?
[ "For simple lon/lat [x/y] dots, the matplotlib does the job. If you need to have some simple map in the background (such as continent boundaries, major cities, rivers) or use a specific projection, check matplotlib.toolkits.basemap.basemap.\n" ]
[ 3 ]
[]
[]
[ "coordinates", "draw", "python", "visualization" ]
stackoverflow_0008228065_coordinates_draw_python_visualization.txt
Q: Keeping the WebSocket connection alive I'm doing a study on WebSocket protocol and trying to implement a simple ECHO service for now with Python on the backend. It seems to work fine but the connection drops right after being established. Here is my client: <!doctype html> <head> <script type="text/javascript" src...
Keeping the WebSocket connection alive
I'm doing a study on WebSocket protocol and trying to implement a simple ECHO service for now with Python on the backend. It seems to work fine but the connection drops right after being established. Here is my client: <!doctype html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/ja...
[ "The connection is closed each time after handle. You should rather stay there reading incoming data:\n# incoming connection\ndef setup(self):\n print \"connection established\", self.client_address\n\ndef handle(self):\n while 1:\n try:\n self.data = self.request.recv(1024).strip()\n\n ...
[ 7 ]
[]
[]
[ "http_headers", "javascript", "python", "sockets", "websocket" ]
stackoverflow_0008218936_http_headers_javascript_python_sockets_websocket.txt
Q: Is nose an extension of unittest? I'm about to use nose as a method for test discovery on my already implemented unittest classes in my rather large project. I was under the impression that nose is just used primarily for test discovery and test running (in parallel as well). But I see this question as if nose is ...
Is nose an extension of unittest?
I'm about to use nose as a method for test discovery on my already implemented unittest classes in my rather large project. I was under the impression that nose is just used primarily for test discovery and test running (in parallel as well). But I see this question as if nose is a replacement for unittest. Can someone...
[ "The docs for nose say:\n\nnose provides an alternate test discovery and running process for\n unittest, one that is intended to mimic the behavior of py.test as\n much as is reasonably possible without resorting to too much magic.\n\nIf you take a peek at the code, you will see that unittest is one of the depend...
[ 8, 7 ]
[]
[]
[ "nose", "python", "testing" ]
stackoverflow_0008228364_nose_python_testing.txt
Q: Python - Downsampling of a list of points, with given coordinates and distance between two adjacent points in the list I really hope someone can help me with this! I'm trying to make this script run as I want, but I cannot seem to get the hang of it. The file with the data to be handled is input from a GPS and lo...
Python - Downsampling of a list of points, with given coordinates and distance between two adjacent points in the list
I really hope someone can help me with this! I'm trying to make this script run as I want, but I cannot seem to get the hang of it. The file with the data to be handled is input from a GPS and looks like this: Line 20081002-1119.nmea $GPGGA,094406.00,5849.40174,N,01738.15828,E,2,08,00.9,00003.26,M,0024.93,M,005,0734*6...
[ "For point reduction in a curve, you probably want to use the Ramer–Douglas–Peucker algorithm. This maintains the overall shape of the curve, but removes the detail, the amount removed can be controlled by a parameter.\nNote that the code on the linked Wikipedia page is pseudo code, and not python.\n\nI've found a ...
[ 4, 2 ]
[]
[]
[ "coordinates", "downsampling", "gps", "io", "python" ]
stackoverflow_0008227421_coordinates_downsampling_gps_io_python.txt
Q: ORM for python that does not require we to define all properties for classes for database tables I have access to a large database system. I would like to talk with it in an efficient manner. Are there ORM framework like SQLAlchemy (I know SQLAlchemy) that does not require we to define all properties for classes f...
ORM for python that does not require we to define all properties for classes for database tables
I have access to a large database system. I would like to talk with it in an efficient manner. Are there ORM framework like SQLAlchemy (I know SQLAlchemy) that does not require we to define all properties for classes for each database tables? Because the database is already there, my aim is to avoid creating properties...
[ "Using SQLAlchemy's introspection features you can easily enough have a metaclass that gives you a new mapped class given a table name. The class still has to be defined, but you don't have to define it.\ndef introspect(tablename, *mapper_args, **mapper_kwargs):\n u'given a table name and optional mapper argument...
[ 4 ]
[]
[]
[ "database", "orm", "python" ]
stackoverflow_0008228941_database_orm_python.txt
Q: What is more efficient? A dict inside the class definition or dict inside a func definition? I have some object that will be always stored in memory and there will be thousands of instances, so it is important to use memory efficiently. This object will use some dict like: { 'text':doSomething, 'string':doAnotherT...
What is more efficient? A dict inside the class definition or dict inside a func definition?
I have some object that will be always stored in memory and there will be thousands of instances, so it is important to use memory efficiently. This object will use some dict like: { 'text':doSomething, 'string':doAnotherThing, 'int':doSomethingCrazy } Of course i can put it OUT of the class, on the module level, so i...
[ "If you put it inside a function, the dictionary will be recreated every single time the function is called. This is a bit of a waste, especially of the dictionary is large:\nclass MyClass(object):\n def someFunc(): \n thatDict={} # recreated every function call\n\nIf you put it in a class definiti...
[ 6 ]
[]
[]
[ "memory", "python" ]
stackoverflow_0008229423_memory_python.txt
Q: Including confidentiality information in Sphinx reST I have the confidentiality text in its own "copy.rst" document. How can I include it without it showing up in the toctree? A: The correct way would be Do not include copy.rst in any .. toctree:. This way this page will not come in next/previous. Write :orph...
Including confidentiality information in Sphinx reST
I have the confidentiality text in its own "copy.rst" document. How can I include it without it showing up in the toctree?
[ "The correct way would be \n\nDo not include copy.rst in any .. toctree:. This way this page will not come in next/previous.\nWrite :orphan: to the first line of copy.rst. This way you will not see any compiler warning.\n\n", "Add copy.rst to a separate toctree with the :hidden: option:\n.. toctree::\n\n doc1...
[ 3, 1 ]
[]
[]
[ "python", "python_sphinx", "restructuredtext" ]
stackoverflow_0008177637_python_python_sphinx_restructuredtext.txt
Q: embedding python Im trying to call python functions from C code, and i followed a sample from here I also have the correct include file directries, library directries, and linked the python32.lib (im using python 32) however the error was that python/C APIs such as PyString_FromString, PyInt_FromLong, PyInt_AsLong...
embedding python
Im trying to call python functions from C code, and i followed a sample from here I also have the correct include file directries, library directries, and linked the python32.lib (im using python 32) however the error was that python/C APIs such as PyString_FromString, PyInt_FromLong, PyInt_AsLong are undefined (error ...
[ "The example code you used is for ancient Python version, 2.3.2. Python 3.x line introduced a number of incompatibilites not only in the language but in the C API as well.\nThe functions you mention simply no longer exist in Python 3.2.\nPyString_ functions were renamed to PyBytes_.\nPyInt_ functions are gone, PyLo...
[ 18 ]
[]
[]
[ "c", "python", "python_c_api", "python_embedding" ]
stackoverflow_0008229597_c_python_python_c_api_python_embedding.txt
Q: How do I access imported local settings without a circular import? At the end of my settings.py file, I have: try: from local_settings import * except ImportError: pass I then have a local_settings.py file where I have some db settings, etc. In this file I would also like to do the following (in order to ...
How do I access imported local settings without a circular import?
At the end of my settings.py file, I have: try: from local_settings import * except ImportError: pass I then have a local_settings.py file where I have some db settings, etc. In this file I would also like to do the following (in order to use django_debug_toolbar): INTERNAL_IPS = ('127.0.0.1',) MIDDLEWARE_CLAS...
[ "You can't do this. The imported module is executed in it's own scope and has no way of knowing where (and if) it is has been imported in any way. An alternative way would be something like this:\nIn your local_settings:\nINTERNAL_IPS = ('127.0.0.1',)\nMIDDLEWARE_CLASSES = ('debug_toolbar.middleware.DebugToolbarMid...
[ 3, 3 ]
[]
[]
[ "django", "django_debug_toolbar", "python" ]
stackoverflow_0008219940_django_django_debug_toolbar_python.txt
Q: Notify celery task of worker shutdown I am using celery 2.4.1 with python 2.6, the rabbitmq backend, and django. I would like my task to be able to clean up properly if the worker shuts down. As far as I am aware you cannot supply a task destructor so I tried hooking into the worker_shutdown signal. Note: Abortab...
Notify celery task of worker shutdown
I am using celery 2.4.1 with python 2.6, the rabbitmq backend, and django. I would like my task to be able to clean up properly if the worker shuts down. As far as I am aware you cannot supply a task destructor so I tried hooking into the worker_shutdown signal. Note: AbortableTask only works with the database backend...
[ "worker_shutdown is only sent by the MainProcess, not the child pool workers.\nAll worker_* signals except for worker_process_init, refer to the MainProcess.\n\nHowever, the shutdown hook never gets called. Ctrl-C'ing the worker\n doesn't kill the task and I have to manually kill it from the shell.\n\nThe worker n...
[ 11 ]
[]
[]
[ "celery", "django_celery", "python", "rabbitmq" ]
stackoverflow_0008138642_celery_django_celery_python_rabbitmq.txt
Q: TypeError: unable to acces a wrapped function with double pointer argument Im very new to swig and got a strange TypeError when i access a function with an double pointer as argument. Here are my files: Example.hpp #ifndef _EXAMPLE_HPP #define _EXAMPLE_HPP class Example { public: void test_cc(char * c0, char ...
TypeError: unable to acces a wrapped function with double pointer argument
Im very new to swig and got a strange TypeError when i access a function with an double pointer as argument. Here are my files: Example.hpp #ifndef _EXAMPLE_HPP #define _EXAMPLE_HPP class Example { public: void test_cc(char * c0, char * c1); void test_cd(char * c0, double d0); void test_cdp(char * c0, doub...
[ "I think your problem is actually in:\nvoid test_cd(char * c0, double * d0);\n\nand that your argument should be a double, not a double*.\nIn reference to your comment\nYour code is:\nE.test_cc(\"Hello\",\"World\");\nE.test_cd(\"Hello\",42);\n\nYour prototypes are: \nvoid test_cc(char * c0, char * c1);\nvoid test_c...
[ 1 ]
[]
[]
[ "c++", "python", "swig" ]
stackoverflow_0008230627_c++_python_swig.txt
Q: relatively new programmer interested in using Celery, is this the right approach Essentially I have a large database of transactions and I am writing a script that will take some personal information and match a person to all of their past transactions. So I feed the script a name and it returns all of the transa...
relatively new programmer interested in using Celery, is this the right approach
Essentially I have a large database of transactions and I am writing a script that will take some personal information and match a person to all of their past transactions. So I feed the script a name and it returns all of the transactions that it has decided belong to that customer. The issue is that I have to do thi...
[ "No, there wouldn't be any problem multiple worker computers searching and writing to the same database since MySQL is designed to be able to handle this. Your approach is good.\n" ]
[ 2 ]
[]
[]
[ "celery", "mysql", "python" ]
stackoverflow_0008230617_celery_mysql_python.txt
Q: What do you call the elements of a module? I have this code from Learn Python The Hard Way and I need to comment it: from sys import argv So I did: #imports argv from the sys module I know what argv does, but I am having trouble figuring out what to call this element of the sys module? A variable, a method, a fun...
What do you call the elements of a module?
I have this code from Learn Python The Hard Way and I need to comment it: from sys import argv So I did: #imports argv from the sys module I know what argv does, but I am having trouble figuring out what to call this element of the sys module? A variable, a method, a function? Argument variable? Also, given that line ...
[ "argv is a variable in the sys module's namespace. It happens to be a list.\nThe statement\nfrom sys import argv\n\ncauses Python to parse the entire sys module (assuming it has not already been parsed, in which case it is not reloaded), and copy the argv variable into the current module's namespace.\n", "\nI kno...
[ 6, 2, 1 ]
[]
[]
[ "module", "python" ]
stackoverflow_0008230390_module_python.txt
Q: Building a multipart/form-data with binary image data in Django gives me a UnicodeDecodeError --- Edited below with some more testing, please read :) --- I'm struggling trying to build a multipart/form-data body in Python, basically I'm doing it with a buffer of strings in a list and then trying to join them, here...
Building a multipart/form-data with binary image data in Django gives me a UnicodeDecodeError
--- Edited below with some more testing, please read :) --- I'm struggling trying to build a multipart/form-data body in Python, basically I'm doing it with a buffer of strings in a list and then trying to join them, here's the code: fp = open(filename, 'rb') BOUNDARY = 's0m3r4ndomB0unD4ry' body = [] body.append('--'...
[ "You are most likely providing all str values when you test your code from the shell, while the Django app is returning form values (such as the filename) as unicode. Your join statement then attempts to convert the read file contents from str to unicode when joining them to the rest of the body, which throws the ...
[ 4 ]
[]
[]
[ "django", "file_upload", "multipartform_data", "python" ]
stackoverflow_0008190160_django_file_upload_multipartform_data_python.txt
Q: Create IPv6 socket in Windows XP, using python The following piece of code works on Windows7 and Linux, but gives an Error in Windows XP: import socket print(socket.has_ipv6) print("INET=",socket.AF_INET,"\nINET6=",socket.AF_INET6,"\nDGRAM=",socket.SOCK_DGRAM) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM...
Create IPv6 socket in Windows XP, using python
The following piece of code works on Windows7 and Linux, but gives an Error in Windows XP: import socket print(socket.has_ipv6) print("INET=",socket.AF_INET,"\nINET6=",socket.AF_INET6,"\nDGRAM=",socket.SOCK_DGRAM) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s6 = socket.socket(socket.AF_INET6, socket.SOCK_DG...
[ "IPv6 needs to be installed on your machine. Instructions are here. (Thanks, David)\n" ]
[ 2 ]
[]
[]
[ "ipv6", "python", "python_3.x", "sockets", "windows_xp" ]
stackoverflow_0008229851_ipv6_python_python_3.x_sockets_windows_xp.txt
Q: How to format date in Python and avoid XLDateAmbiguous and fix leap year I have an odd error raised in a script. XLDateAmbiguous: 15.0 I have tried formatting the date as such: sOutput += datetime.datetime(*xlrd.xldate_as_tuple(value, workbook.datemode)).strftime(sDateTimeFormat) but i am still recieving the sam...
How to format date in Python and avoid XLDateAmbiguous and fix leap year
I have an odd error raised in a script. XLDateAmbiguous: 15.0 I have tried formatting the date as such: sOutput += datetime.datetime(*xlrd.xldate_as_tuple(value, workbook.datemode)).strftime(sDateTimeFormat) but i am still recieving the same error, any help in any way is very greatly appreciated.
[ "The docs are very clear about when this is raised.\nIt will happen if the workbook.datemode == 0 and 1.0 <= value < 61.0\n" ]
[ -2 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0008231109_datetime_python.txt
Q: How to get two values from two seperate lists to print (python) Here’s my problem, I have two different lists, list a which contains the name of people and list b which contains their phone numbers: a = ["peter", "bob", "john", "jack"] b = ["8954 3434", "8999 4432", "8976 5443", "8990 3331"] What I need to do is...
How to get two values from two seperate lists to print (python)
Here’s my problem, I have two different lists, list a which contains the name of people and list b which contains their phone numbers: a = ["peter", "bob", "john", "jack"] b = ["8954 3434", "8999 4432", "8976 5443", "8990 3331"] What I need to do is prompt users for a input which will be a name from list a and then p...
[ "Put your data in a dictionary:\n>>> a = [\"peter\", \"bob\", \"john\", \"jack\"]\n>>> b = [\"8954 3434\", \"8999 4432\", \"8976 5443\", \"8990 3331\"]\n>>> phone_numbers = dict(zip(a,b))\n\nThen you can get someone's phone number from their name:\n>>> phone_numbers['john']\n'8976 5443'\n\nIf you want to do this on...
[ 4, 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "list", "python", "zip" ]
stackoverflow_0008230969_list_python_zip.txt
Q: how to access the member forms of a formset? I have an inline_formset for which I am using a custom form. That form has various functions that I would like to call. But, given an instance of the formset, how can I access that (those?) form(s)? Here is some pseudo-code: class MyModel(models.Model): my...
how to access the member forms of a formset?
I have an inline_formset for which I am using a custom form. That form has various functions that I would like to call. But, given an instance of the formset, how can I access that (those?) form(s)? Here is some pseudo-code: class MyModel(models.Model): myField = models.ForeignKey(MyOtherModel) class...
[ "You can access a formset's forms through formset.forms. \nIf myFormSet.forms[0].foo() fails then that probably means the formset does not have any forms. You haven't told us in what way it fails - IndexError?\nIf you are defining the formset in inlineformset_factory, have you made sure it inherits from BaseModelFo...
[ 1 ]
[]
[]
[ "django", "formset", "inline_formset", "python" ]
stackoverflow_0008231354_django_formset_inline_formset_python.txt
Q: Using Python's Pip in Virtualenv I have been using Heroku's cedar stack with Python for some time now, without any errors. Today, however, when I decided to update my dependencies locally, within my virtualenv via sudo bin/pip install -r requirements I received the following error: Traceback (most recent call last...
Using Python's Pip in Virtualenv
I have been using Heroku's cedar stack with Python for some time now, without any errors. Today, however, when I decided to update my dependencies locally, within my virtualenv via sudo bin/pip install -r requirements I received the following error: Traceback (most recent call last): File "/Users/alex/Desktop/dev/war...
[ "The error message you're receiving is due to the link you that virtualenv created to your system python. You'll now want to destroy the virtualenv and recreate it. To destroy it you'll want to:\nrm -r bin\nrm -r include\nrm -r lib\nrm .Python\n\nThen you should be able to re-create your virtualenv and then pip in...
[ 4 ]
[]
[]
[ "heroku", "pip", "python", "virtualenv" ]
stackoverflow_0008227249_heroku_pip_python_virtualenv.txt
Q: Is it possible to generate and execute Python code in a Python script? [Dynamic Python code] I am working on some reports (counts) and I have to fetch counts for different parameters. Pretty simple but tedious. A sample query for one parameter : qCountsEmployee = ( "select count(*) from %s where EmployeeName i...
Is it possible to generate and execute Python code in a Python script? [Dynamic Python code]
I am working on some reports (counts) and I have to fetch counts for different parameters. Pretty simple but tedious. A sample query for one parameter : qCountsEmployee = ( "select count(*) from %s where EmployeeName is not null" % (tablename) ) CountsEmployee = execute_query(qCountsEmployee) Now I have ...
[ "It would be possible, but is not useful here.\nJust do something like\ncolumnList = ['a', 'b', ............'zzzz']\n\nresults = {}\nfor column in columnList:\n query = (\n \"select count(*) from \" + tablename\n + \" where \" + column + \" is not null\"\n )\n result = execute...
[ 5, 2, 2 ]
[]
[]
[ "code_generation", "dynamic", "python" ]
stackoverflow_0008231384_code_generation_dynamic_python.txt
Q: How to create Rules in Scrapy Python? I am getting trouble while creating rule. let suppose my starting url is http://www.example.com/search?q=news when I open this url in web browser i get following source code: <html><head>...</head><body> <ul id="results-list"> <li class="result clearfix news"> <div class="su...
How to create Rules in Scrapy Python?
I am getting trouble while creating rule. let suppose my starting url is http://www.example.com/search?q=news when I open this url in web browser i get following source code: <html><head>...</head><body> <ul id="results-list"> <li class="result clearfix news"> <div class="summary"> <h3><a href="/sports/hockey/struggl...
[ "first, what results are you expecting exactly?\nsecond, maybe you should address the links in your rules, and not only the ul-container, which contains list item-nodes, which than has the required link-nodes!?\n", "According to documentation, SgmlLinkExtractor allow parameter - a single regular expression (or li...
[ 1, 0 ]
[]
[]
[ "python", "scrapy" ]
stackoverflow_0008211575_python_scrapy.txt
Q: Django installation has no __init__.py in django.core I have a ubuntu lucid VPS server where I try to run my django development server. Running python manage.py runserver gives me the following error: Traceback (most recent call last): File "manage.py", line 2, in <module> from django.core.management import ...
Django installation has no __init__.py in django.core
I have a ubuntu lucid VPS server where I try to run my django development server. Running python manage.py runserver gives me the following error: Traceback (most recent call last): File "manage.py", line 2, in <module> from django.core.management import execute_manager ImportError: No module named core.managemen...
[ "solved.\nThank you for all the suggestions. I installed django using the tar ball as instructed in the django website.\napt-get is not a good idea to install django. I also had to manually remove the left over django folder in /usr/lib/pymodules/python2.6 after using apt-get remove. \n" ]
[ 1 ]
[]
[]
[ "django", "python", "ubuntu" ]
stackoverflow_0008218511_django_python_ubuntu.txt
Q: Facebook, Twitter and Google login example in Rails/Django Iam looking for a Django or Rails example with Google login+Facebook+Twitter. My goal is to develop something like Nerddinner.com...The example should be updated (most of the examples I found was outdated) and working. Thanks for any advices. A: check ou...
Facebook, Twitter and Google login example in Rails/Django
Iam looking for a Django or Rails example with Google login+Facebook+Twitter. My goal is to develop something like Nerddinner.com...The example should be updated (most of the examples I found was outdated) and working. Thanks for any advices.
[ "check out devise for rails. it uses omniauth for such purposes and it's very well documented, you shouldn't have any problems with it\n", "You mean an app like django-social-auth?\nCheck Django Packages to find more.\n" ]
[ 1, 0 ]
[]
[]
[ "django", "facebook", "python", "ruby", "ruby_on_rails" ]
stackoverflow_0008231678_django_facebook_python_ruby_ruby_on_rails.txt
Q: What is correct method to execute curl from a subprocess? I was trying to invoke curl from subprocess to download images, but kept getting curl error (error code 2 ..which from doc refers to CURL_FAILED_INIT). I am not using urllib as i will eventually be executing a script using subprocess. Following is the code ...
What is correct method to execute curl from a subprocess?
I was trying to invoke curl from subprocess to download images, but kept getting curl error (error code 2 ..which from doc refers to CURL_FAILED_INIT). I am not using urllib as i will eventually be executing a script using subprocess. Following is the code snippet import subprocess import multiprocessing def worker(f...
[ "If you want to run a shell command, subprocess is the way to go. As this can start a shell command in its own process, use of multiprocessing is at best redundant. Multiprocessing comes in handy when you want to run a function of your python program in distinct process. You appear to intend to run a shell comma...
[ 7 ]
[]
[]
[ "curl", "python", "subprocess" ]
stackoverflow_0008231362_curl_python_subprocess.txt
Q: Confused about Python sub-sub-packages as the title says, I am confused about sub-subpackages. My package structure is the following: draw \ __init__.py base \ __init__.py utils.py events.py master.py basegui.py Now, the first line of draw.base.events is the follow...
Confused about Python sub-sub-packages
as the title says, I am confused about sub-subpackages. My package structure is the following: draw \ __init__.py base \ __init__.py utils.py events.py master.py basegui.py Now, the first line of draw.base.events is the following: import draw.base.utils as _utils And t...
[ "In order to import draw.base.utils in draw.base.events Python needs to import draw.base which is being imported now so there is no draw.base yet. You can replace import draw.base.utils with import utils (you can also use something like from ..base import utils in 2.7, 3.x or with from __future__ import absolute_im...
[ 2 ]
[]
[]
[ "module", "package", "python" ]
stackoverflow_0008231866_module_package_python.txt
Q: How to use try Exception block to save my code from abnormal termination? I'm writing a program that connects to my website via ftp. If the login authentication fails, I want it to continue on to do something else. But an authentication failure error automatically exits the program. Is there a way to ignore this a...
How to use try Exception block to save my code from abnormal termination?
I'm writing a program that connects to my website via ftp. If the login authentication fails, I want it to continue on to do something else. But an authentication failure error automatically exits the program. Is there a way to ignore this and continue on?
[ "You can use Python's Exception Handling:\ntry:\n do_something()\nexcept Exception, ex:\n print \"The process failed because\", ex\n do_something_else()\n\nreplace do_something() with code you first want to try.. Replace do_somthing_else() code with what you wish to try when do_something() part fails\nRefe...
[ 0 ]
[]
[]
[ "authentication", "ftp", "ftplib", "python" ]
stackoverflow_0008232089_authentication_ftp_ftplib_python.txt
Q: what are possible performance issues on using python over java for Android App development? I am new to Android and was seeking for an app (email client) which has a nice filter system, but after a lot of Googling and Android market browsing, its seems none of the email client available for Android provide such fe...
what are possible performance issues on using python over java for Android App development?
I am new to Android and was seeking for an app (email client) which has a nice filter system, but after a lot of Googling and Android market browsing, its seems none of the email client available for Android provide such features. (at least the free ones don't). So, finally I decided to develop one myself. Now the prob...
[ "You can install and run Python on Android, its just a linux box but if you doing anything graphical either use the android GUI/Java or openGL. Check out this link to install Python on Android. Python you can use for fast scripting and running some programs quickly. But for Android you might be hindered a little...
[ 2 ]
[]
[]
[ "android", "java", "performance", "python" ]
stackoverflow_0008231321_android_java_performance_python.txt
Q: Query database in Django for sum of two fields, sorting wrong I've got an object that have the counts for connections in twitter and facebook saved in the object's table. I'm trying to sort a list of these objects by the combined sum of the facebook and twitter counts using the .extra field. Some of the twitter / ...
Query database in Django for sum of two fields, sorting wrong
I've got an object that have the counts for connections in twitter and facebook saved in the object's table. I'm trying to sort a list of these objects by the combined sum of the facebook and twitter counts using the .extra field. Some of the twitter / facebook fields are empty (None) so the combined is blank. This is ...
[ "This is not tested, but can you do this?\nannotate(total_count=Sum(twitter_count) + Sum(facebook_count))\n\nIf not, you may need to do it in the model. For example, in the model add a \ndef get_total(self):\n if twitter_count == None and facebook_count == None:\n return 0\n elif twitter_count != None ...
[ 0 ]
[]
[]
[ "django", "django_models", "django_queryset", "python" ]
stackoverflow_0008232232_django_django_models_django_queryset_python.txt
Q: listing exceptions programmatically - Python Is there any way to programmatically determine which exceptions an object or method might raise? Like dir(obj) lists available methods, I'm looking for the equivalent dir_exceptions(obj). As far as I know, the only way to achieve this would be to parse the source. A: ...
listing exceptions programmatically - Python
Is there any way to programmatically determine which exceptions an object or method might raise? Like dir(obj) lists available methods, I'm looking for the equivalent dir_exceptions(obj). As far as I know, the only way to achieve this would be to parse the source.
[ "I don't think this is possible. An exception is a runtime phenomenon and you'll know what it possible (or what happens) only while running. Why would you want to do this though? \n", "It looks like you'll have to trust the code's developers on this one: if they did a good job, the method/class documentation sho...
[ 2, 2, 1 ]
[ "I don't think this is possible either, but if you trust that the programmer has named their exceptions with \"Exception\" or \"Error\" in the name, then you could do a dir on the class and search for elements that end with \"Exception\" or \"Error\". Aside from that (which is pretty hacky in itself), I don't see a...
[ -1 ]
[ "python" ]
stackoverflow_0008232218_python.txt
Q: How to handle slices in my C++ __getitem__ function (to be used by SWIG) I am developing Python bindings for a C++ class which extends a std::vector instantiation. To get a Python subscript operator working for this class I added __getitem__ function looking as follows (I cut irrelevant code and error handling): c...
How to handle slices in my C++ __getitem__ function (to be used by SWIG)
I am developing Python bindings for a C++ class which extends a std::vector instantiation. To get a Python subscript operator working for this class I added __getitem__ function looking as follows (I cut irrelevant code and error handling): class Column; typedef vector<Column*> MetaDataBase; class MetaData : public M...
[ "I think there's a much simpler solution to this for std::vector with SWIG+Python. SWIG's Python code generation already has support for doing quite a good job wrapping some STL containers.\nIf you add to the beginning of your module interface:\n%include \"pyabc.i\"\n%include \"std_vector.i\" // Assuming you don't ...
[ 3 ]
[]
[]
[ "c++", "python", "swig" ]
stackoverflow_0008218314_c++_python_swig.txt
Q: django module-level cache I am trying to store a value in a module level variable for later retrieval. This function when called with a GET method throws this error: local variable 'ICS_CACHE' referenced before assignment What am I doing wrong here? ICS_CACHE = None def ical_feed(request): if request.method ==...
django module-level cache
I am trying to store a value in a module level variable for later retrieval. This function when called with a GET method throws this error: local variable 'ICS_CACHE' referenced before assignment What am I doing wrong here? ICS_CACHE = None def ical_feed(request): if request.method == "POST": response = Htt...
[ "Add\nglobal ISC_CACHE\n\nas the first line of your function. You are assigning to it inside the function body, so python assumes that it is a local variable. As a local variable, though, you can't return it without assigning to it first.\nThe global statement lets the parser know that the variable comes from outsi...
[ 1 ]
[]
[]
[ "caching", "django", "python", "scope", "variables" ]
stackoverflow_0008232495_caching_django_python_scope_variables.txt
Q: How do I unserialize a java object on jython I have a java object which I retrieve using a HTTP request. How can I 'un-serialize' the java data in jython? A: I guess the project python-javaobj is what you are looking for. Alternatively you could perhaps consider using another, simpler format for serializing obje...
How do I unserialize a java object on jython
I have a java object which I retrieve using a HTTP request. How can I 'un-serialize' the java data in jython?
[ "I guess the project python-javaobj is what you are looking for.\nAlternatively you could perhaps consider using another, simpler format for serializing objects like JSON... ?!\n", "You just call the java methods to deserialize from Jython. \nLooks like you have to create an ObjectInputStream from your InputStrea...
[ 2, 2 ]
[]
[]
[ "java", "jython", "python", "serialization" ]
stackoverflow_0008232015_java_jython_python_serialization.txt
Q: post parameters in python I've tried a lot of codes to post parameters through urllib or httplib. So, this is my code: import httplib,urllib para = urllib.urlencode({"username":"test@msn.com","password":"test"}) conn = httplib.HTTPconnection("account.example.com") #consider it's https ! conn.request("POST","/en...
post parameters in python
I've tried a lot of codes to post parameters through urllib or httplib. So, this is my code: import httplib,urllib para = urllib.urlencode({"username":"test@msn.com","password":"test"}) conn = httplib.HTTPconnection("account.example.com") #consider it's https ! conn.request("POST","/eng/auth/login",para) res = conn....
[ "You need to encode the parameters:\nparams = urllib.urlencode({\"username\":\"test@msn.com\",\"password\":\"test\"})\n\nThe 301 might be totally legitimate, your example is posting to a login handler which will typically accept the POST, issue a Cookie and redirect you to the \"correct\" page to handle your sessio...
[ 1 ]
[]
[]
[ "authentication", "httplib", "parameters", "python", "urllib" ]
stackoverflow_0008232574_authentication_httplib_parameters_python_urllib.txt
Q: How do I efficiently store and query a raw JSON stream in MongoDB? I would like to store the raw JSON stream (either via Twitter or the NYTimes) efficiently in MongoDB, so that I can later index the data (NYTimes articles, or Tweets/usernames) with either Lucene or Hadoop. What's the smartest way of storing data i...
How do I efficiently store and query a raw JSON stream in MongoDB?
I would like to store the raw JSON stream (either via Twitter or the NYTimes) efficiently in MongoDB, so that I can later index the data (NYTimes articles, or Tweets/usernames) with either Lucene or Hadoop. What's the smartest way of storing data in Mongo? Should I just pipe in the JSON, or is there something better? I...
[ "\nIs there an efficient (smart) way of writing queries, or storing my data to better-optimize the search-queries?\n\nThis totally depends on what kind of queries you need to make and what the usage pattern of your application will be. \nIt would be pretty simple to store each tweet in a Mongo Document containing: ...
[ 7 ]
[]
[]
[ "mongodb", "pymongo", "python", "twitter" ]
stackoverflow_0008232380_mongodb_pymongo_python_twitter.txt
Q: How to put statement before for-loop in python How can one put statement before for-loop in python? Such as: print i for i in range(10) The above example may seems unnecessary. But when it comes to a more complicated generator, it might be handy and pythonic: print i for i in takewhile(lambda x: x < 100000, fibon...
How to put statement before for-loop in python
How can one put statement before for-loop in python? Such as: print i for i in range(10) The above example may seems unnecessary. But when it comes to a more complicated generator, it might be handy and pythonic: print i for i in takewhile(lambda x: x < 100000, fibonacci()) if i % 2 == 0 Of course the above statement...
[ "You can't do this in Python.\nYou can put it after instead:\nfor i in range(10): print i \n\nBut usually you would write this on two lines.\nfor i in range(10):\n print i \n\n", "I guess you don't like the easy way?\nfor i in range(10):\n print i\n\nIf you really want the syntax you're talking about, you c...
[ 2, 1, 0 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0008232965_for_loop_python.txt
Q: Django Debug Toolbar: understanding the time panel I'm running the Django Debug Toolbar to profile my site and try to figure out why certain views are taking so long. It's been immensely valuable with regards to seeing what queries I'm running and how much they're costing me, but I can't understand how to read the...
Django Debug Toolbar: understanding the time panel
I'm running the Django Debug Toolbar to profile my site and try to figure out why certain views are taking so long. It's been immensely valuable with regards to seeing what queries I'm running and how much they're costing me, but I can't understand how to read the time panel. I've looked around everywhere for some doc...
[ "User CPU time: The time your server-side code ran while processing the request\nSystem CPU time: The time operating system code called by your server-side code ran while processing the request\nTotal CPU time: total time to fully respond once request was received (user+system)\nElapsed time: Time since request was...
[ 51 ]
[]
[]
[ "django", "django_debug_toolbar", "python" ]
stackoverflow_0008232434_django_django_debug_toolbar_python.txt
Q: Automatic dictionary generation - Python I am trying to create a program which outputs all permutations of a string of length n whilst avoiding a defined substring, of length k. For example: Derive all possible strings, up to a length of 5 characters, that can be generated from an initial empty set, which can eith...
Automatic dictionary generation - Python
I am trying to create a program which outputs all permutations of a string of length n whilst avoiding a defined substring, of length k. For example: Derive all possible strings, up to a length of 5 characters, that can be generated from an initial empty set, which can either go to A or B, but the string cannot contain...
[ "The itertools module has a useful method called permutations():\n(from http://docs.python.org/library/itertools.html#itertools.permutations)\n\nitertools.permutations(iterable[, r])\nReturn successive r length permutations of elements in the iterable.\nIf r is not specified or is None, then r defaults to the lengt...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0008232733_python.txt
Q: Sqlite syntax error even though there's no syntax error. Help? Here's the code I use to update information in my sqlite database: self.c.execute("UPDATE proxydata (proxy, description) VALUES ('" + proxy + "', '" + description + "') WHERE proxy='" + proxy + "'") But I get this error: sqlite3.OperationalError: near...
Sqlite syntax error even though there's no syntax error. Help?
Here's the code I use to update information in my sqlite database: self.c.execute("UPDATE proxydata (proxy, description) VALUES ('" + proxy + "', '" + description + "') WHERE proxy='" + proxy + "'") But I get this error: sqlite3.OperationalError: near "(": syntax error For the life of mine I can't find an error. Both...
[ "Use a parametrized sql:\nsql='UPDATE proxydata SET description = ? WHERE proxy = ?'\nargs=[decription,proxy]\nself.c.execute(sql,args)\n\nThis is clearly easier, since you don't have to quote the arguments yourself, and thus less error-prone.\nIt is also safer, since parametrizing the sql allows sqlite3 to protect...
[ 6, 3 ]
[]
[]
[ "python", "sqlite", "syntax" ]
stackoverflow_0008233367_python_sqlite_syntax.txt
Q: change unicode string into list? I get the data as type <type 'unicode'> u'{0.128,0.128,0.133,0.137,0.141,0.146,0.15,0.155,0.159,0.164,0.169,0.174,0.179,0.185,0.19,0.196,0.202,0.208,0.214,0.22}' I want to convert this to list like [0.128,0.128,0.133,0.137,0.141,0.146,0.15,0.155,0.159,0.164,0.169,0.174,0.179,...
change unicode string into list?
I get the data as type <type 'unicode'> u'{0.128,0.128,0.133,0.137,0.141,0.146,0.15,0.155,0.159,0.164,0.169,0.174,0.179,0.185,0.19,0.196,0.202,0.208,0.214,0.22}' I want to convert this to list like [0.128,0.128,0.133,0.137,0.141,0.146,0.15,0.155,0.159,0.164,0.169,0.174,0.179,0.185,0.19,0.196,0.202,0.208,0.214,0.2...
[ "Just like that:\n>>> a = u'{0.128,0.128,0.133,0.137,0.141,0.146,0.15,0.155,0.159,0.164,0.169,0.174,0.179,0.185,0.19,0.196,0.202,0.208,0.214,0.22}'\n>>> [float(i) for i in a.strip('{}').split(',')]\n[0.128, 0.128, 0.133, 0.137, 0.141, 0.146, 0.15, 0.155, 0.159, 0.164, 0.169, 0.174, 0.179, 0.185, 0.19, 0.196, 0.202,...
[ 8, 4 ]
[]
[]
[ "python" ]
stackoverflow_0008233412_python.txt
Q: django admin duplicating objects I have been creating a permissions based on country part to my website for the admin console. I have overridden the save_model() method on my class, which inherits from the admin.ModelAdmin class, with this: def save_model(self, request, obj, form, change): try: form_c...
django admin duplicating objects
I have been creating a permissions based on country part to my website for the admin console. I have overridden the save_model() method on my class, which inherits from the admin.ModelAdmin class, with this: def save_model(self, request, obj, form, change): try: form_cleaned_countries = [self.get_field(c,s...
[ "I fixed my error actually. The queryset function i was overridding was returning duplicate results, and the admin was just freaking out, even tho the duplicate results weren't actually in the database. Just added a distinct() onto the end of my queryset and it seems to be working.\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008221743_django_python.txt
Q: Get the average number of occurrences in a list of dicts Given a list of dictionaries (a log JSON from MongoDB), where one of the values of the dict is a datetime value, I need to know the frequency it happens. Let's say: [ {"time": "2010-11-11 03:23:59"}, {"time": "2010-11-12 10:16:15"}, {"time": "2...
Get the average number of occurrences in a list of dicts
Given a list of dictionaries (a log JSON from MongoDB), where one of the values of the dict is a datetime value, I need to know the frequency it happens. Let's say: [ {"time": "2010-11-11 03:23:59"}, {"time": "2010-11-12 10:16:15"}, {"time": "2010-11-12 14:51:13"}, ... ] The frequency need to be like...
[ "You could parse the strings into datetimes, find the max and the min, subtract to find a timedelta, and designate the duration based on that timedelta:\nimport datetime as dt\ndata=[\n {\"time\": \"2010-11-11 03:23:59\"},\n {\"time\": \"2010-11-12 10:16:15\"},\n {\"time\": \"2010-11-12 14:51:13\"},\n ]...
[ 6 ]
[]
[]
[ "date", "formula", "frequency", "python" ]
stackoverflow_0008233665_date_formula_frequency_python.txt
Q: python script to pickle entire environment I'm working inside the Python REPL, and I want to save my work periodically. Does anybody have a script to dump all the variables I have defined? I'm looking for something like this: for o in dir(): f=open(o) pickle(o_as_object, f) This seems like something other...
python script to pickle entire environment
I'm working inside the Python REPL, and I want to save my work periodically. Does anybody have a script to dump all the variables I have defined? I'm looking for something like this: for o in dir(): f=open(o) pickle(o_as_object, f) This seems like something other people have done, so I wanted to ask before re-...
[ "I think you want Dill:\n\nIn addition to pickling python objects, dill provides the ability to\n save the state of an interpreter session in a single command. Hence,\n it would be feasable to save a interpreter session, close the\n interpreter, ship the pickled file to another computer, open a new\n interprete...
[ 4 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0008232798_pickle_python.txt
Q: We want to get the posixpath for Mac in Python... Is there any way to get this Suppose my file is on the Desktop: I want the path as /MAC OS X 10.7 US/Users/labuser/Desktop/abcd.txt When I am using any function to get the path, I get the path as: /Users/labuser/Desktop/abcd.txt Is there any way to get the path wit...
We want to get the posixpath for Mac in Python... Is there any way to get this
Suppose my file is on the Desktop: I want the path as /MAC OS X 10.7 US/Users/labuser/Desktop/abcd.txt When I am using any function to get the path, I get the path as: /Users/labuser/Desktop/abcd.txt Is there any way to get the path with the drive name?
[ "I've never seen this on a Mac. Mounted volumes are found in /Volumes. On my MacBook Pro running Mac OS X 10.7.2, this is what I see:\n% ls -l /Volumes\ntotal 8.0K\ndrwxrwxrwt+ 5 root admin 170 Nov 21 11:02 .\ndrwxr-xr-x 38 root wheel 1.4K Nov 21 20:40 ..\nlrwxr-xr-x 1 root admin 1 Nov 6 20:49 Mac...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008229128_python.txt
Q: Python Selecting Data in a List within a List list = [['John',3]['Carey',4]['Jake',3]] I'm looking for a way to select the data of a list within a list. I want to be able to get the values 3,4,3 and convert them into an int. If I try: print list[1::2] returns [['Carey',4] I only want every second value of a li...
Python Selecting Data in a List within a List
list = [['John',3]['Carey',4]['Jake',3]] I'm looking for a way to select the data of a list within a list. I want to be able to get the values 3,4,3 and convert them into an int. If I try: print list[1::2] returns [['Carey',4] I only want every second value of a list within a list. Any suggestions? (I can't use fil...
[ "You can fetch the numbers like so (and don't call it list; that's the name of the type):\n[ i for [_, i] in lst ]\n\nI'm afraid I don't know what you mean by, \"convert them into an int.\"\n", "This one is fine\nl = [['John','3'],['Carey','4'],['Jake','3']] \nfor i in xrange(len(l)):\n print int(l[i][1])\n\nI...
[ 1, 0 ]
[]
[]
[ "list", "python", "select" ]
stackoverflow_0008234417_list_python_select.txt
Q: Get mouse position in sizer? wxpython that it is possible to get the mouse position in wxpython using event.GetPosition() however, is it possible to get the position of a mouse in a sizer? Would this work even in an expanding sizer? Thanks. A: The X,Y position in a sizer is exactly the same as the window that t...
Get mouse position in sizer? wxpython
that it is possible to get the mouse position in wxpython using event.GetPosition() however, is it possible to get the position of a mouse in a sizer? Would this work even in an expanding sizer? Thanks.
[ "The X,Y position in a sizer is exactly the same as the window that the sizer belongs to, assuming that the sizer is the sizer assigned to that window. If you've got nested sizers then you can use sizer.GetPosition and sizer.GetSize to figure out if the position is inside that nested sizer. \nHowever I would gues...
[ 3, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0008221586_python_wxpython.txt
Q: pOpen with python This is baffling me. I have a python script that does some work on a Windows platform to generate an XML file, download some images and then call an external console application to generate a video using the xml and images the python script has generated. The application I call with pOPen is supp...
pOpen with python
This is baffling me. I have a python script that does some work on a Windows platform to generate an XML file, download some images and then call an external console application to generate a video using the xml and images the python script has generated. The application I call with pOPen is supposed to return a status...
[ "You're not closing the file. Your code says:\nxmlfileObj.close\n\nwhen it should be\nxmlfileObj.close()\n\nEdit: Just to clarify - the code xmlfileObj.close is a valid python expression which returns a reference to the built in close method of a file (or file like) object. Since it is a valid python expression it ...
[ 4 ]
[]
[]
[ "popen", "python" ]
stackoverflow_0008233739_popen_python.txt
Q: How to use Python to ensure a string is only numbers and then convert it to an integer If i have a string like this: asdf5493 I need the last four digits and i get it by doing this: strVar[-4:] Is it possible to then see if they are all numbers? A: strVar[-4:].isdigit() tests if all four characters are digits....
How to use Python to ensure a string is only numbers and then convert it to an integer
If i have a string like this: asdf5493 I need the last four digits and i get it by doing this: strVar[-4:] Is it possible to then see if they are all numbers?
[ "strVar[-4:].isdigit()\n\ntests if all four characters are digits. Documentation\nEDIT: If your actual goal is to convert this number to an integer, the usual idiom in Python is to just try to do this, and catch the exception in case it fails:\ns = strVar[-4:]\ntry:\n i = int(s)\nexcept ValueError:\n # handl...
[ 8, 4 ]
[]
[]
[ "python" ]
stackoverflow_0008234791_python.txt
Q: Colorful Python Interpreter for Windows Is there a colorful Python interpreter to download other than using the Windows Command Prompt? I am new to Python and don't know much. A: IDLE is a pretty friendly way to get started (it comes with Python) IPython is another possibility. The easiest way to install it is ...
Colorful Python Interpreter for Windows
Is there a colorful Python interpreter to download other than using the Windows Command Prompt? I am new to Python and don't know much.
[ "IDLE is a pretty friendly way to get started (it comes with Python)\nIPython is another possibility. The easiest way to install it is via EPD Free or Python(x,y).\n", "Try using IdleX. It provides a lot of additional functionality to IDLE and it's simple to get started. Download, extract, and then run idlex.py.\...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008233830_python.txt
Q: Irritating Python loop error? ive been attempting this problem for a while and I cant seem to get the issue out. listy2=['fun','super','Stop'] listy=['great','life','Stop','toys','nothing','Stop'] listpool=[listy,listy2] current=[] total=[] nested=True for i in listpool: for line in enumerate(i): if (l...
Irritating Python loop error?
ive been attempting this problem for a while and I cant seem to get the issue out. listy2=['fun','super','Stop'] listy=['great','life','Stop','toys','nothing','Stop'] listpool=[listy,listy2] current=[] total=[] nested=True for i in listpool: for line in enumerate(i): if (line[0]==0): current.app...
[ "You create one current list to which you append through all the iterations of your main loop. Probably you instead want to create a new current list in each iteration:\nfor i in listpool:\n current = []\n ...\n total.append(current)\n\n", "I don't quite understand everything you're trying to do here, bu...
[ 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008234526_python.txt
Q: Made a GUI with Pyside, but I still have a cmd window in the back? Possible Duplicate: How can I hide the console window in a PyQt app running on Windows? I made a GUI program using QT Designer and Pyside, and it works completely. The only problem is that whenever I run it, I get a cmd.exe window in the backgrou...
Made a GUI with Pyside, but I still have a cmd window in the back?
Possible Duplicate: How can I hide the console window in a PyQt app running on Windows? I made a GUI program using QT Designer and Pyside, and it works completely. The only problem is that whenever I run it, I get a cmd.exe window in the background. This is quite annoying. Is there any way to fix this?
[ "Try changing the file extension to .pyw. Double-clicking a .pyw will use pythonw.exe instead of python.exe.\n" ]
[ 8 ]
[]
[]
[ "cmd", "pyside", "python", "qt", "user_interface" ]
stackoverflow_0008222177_cmd_pyside_python_qt_user_interface.txt
Q: Is there a better way to monitor log files?(linux/python) I'm trying to monitor log files that some process are running on linux(to create a joint log file where log entries are grouped together by when they happen). Currently I'm thinking of opening the files being logged, polling with inotify(or wrapper) and the...
Is there a better way to monitor log files?(linux/python)
I'm trying to monitor log files that some process are running on linux(to create a joint log file where log entries are grouped together by when they happen). Currently I'm thinking of opening the files being logged, polling with inotify(or wrapper) and then checking if I can read any more of the file. Is there any be...
[ "Why won't a \"tail -f\" be sufficient? You could use popen and pipes to handle this from Python.\n", "Generator Tricks For Systems Programmers shows how to use Python generators to solve this type of problem; specifically, monitoring (large) log files. I recommend giving it a read.\n", "If you do it yourself,...
[ 3, 1, 0 ]
[]
[]
[ "linux", "logging", "python" ]
stackoverflow_0008227308_linux_logging_python.txt
Q: Serialize models in django with proper decimal data types into json Here is a sample model: class FooModel(models.Model): foo = models.DecimalField(max_digits=6, decimal_places=3, null=True) Serialize: from django.core import serializers obj = get_object_or_404(FooModel, pk=1) data = serializers.serialize("js...
Serialize models in django with proper decimal data types into json
Here is a sample model: class FooModel(models.Model): foo = models.DecimalField(max_digits=6, decimal_places=3, null=True) Serialize: from django.core import serializers obj = get_object_or_404(FooModel, pk=1) data = serializers.serialize("json", [obj]) That will return something like: [ { "pk": 1, ...
[ "If the value actually 50 vs. 50.0? A Decimal object maintains whatever was originally input, e.g. Decimal('50') yields 50.\n>>> from decimal import Decimal\n>>> d = Decimal('50')\n>>> print d\n50\n\nUnfortunately the arguments provided to the DecimalField constructor are only for restrictions on storing the values...
[ 4 ]
[]
[]
[ "django", "python", "serialization" ]
stackoverflow_0008235513_django_python_serialization.txt
Q: Django sessions with Oauth - cannot pass variables thru request.session I am building an app for making API calls to websites like (FB, LinkedIn, etc.) I need to use OAuth to authorize my application to request data on behalf of the user. I am stuck with a problem of storing the instance of my website interface li...
Django sessions with Oauth - cannot pass variables thru request.session
I am building an app for making API calls to websites like (FB, LinkedIn, etc.) I need to use OAuth to authorize my application to request data on behalf of the user. I am stuck with a problem of storing the instance of my website interface library (LinkedIn) across views. I used request.session - with file back end. ...
[ "hmm, i think its because you are saving the entire api python instance, i dont think that sessions support that kind of data, why not just redirect user to auth url without saving something in session, then in callback view, you instantiate the linkedin.LinkedIn class like so\nfrom django.conf import settings\n\nk...
[ 1 ]
[]
[]
[ "django", "oauth", "python", "session" ]
stackoverflow_0008232900_django_oauth_python_session.txt
Q: I've got a funky tab delimited file that I'd like to make less funky I have a lot of tab delimited data that is organized into multiple rows and should be all in two rows. Now it looks like this: Some Key Other key Foo Key Bar Key 0 5 18 12 More Key Dor key ...
I've got a funky tab delimited file that I'd like to make less funky
I have a lot of tab delimited data that is organized into multiple rows and should be all in two rows. Now it looks like this: Some Key Other key Foo Key Bar Key 0 5 18 12 More Key Dor key Gee Key Francis Scott Key 19 14 8 0 ...
[ "This should do it:\nimport csv\nimport sys\n\nkeys = []\nvalues = []\n\nreader = csv.reader(sys.stdin, delimiter=\"\\t\")\nfor row in reader:\n keys.extend(row)\n values.extend(next(reader))\n\n # skip empty line\n assert next(reader, []) == []\n\nwriter = csv.writer(sys.stdout, delimiter=\"\\t\")\nwri...
[ 3, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0008235568_csv_python.txt