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:
Exposing a "dumbed-down", read-only instance of a Model in GAE
Does anyone know a clever way, in Google App Engine, to return a wrapped Model instance that only exposes a few of the original properties, and does not allow saving the instance back to the datastore?
I'm not looking for ways of actually enforcing the... | Exposing a "dumbed-down", read-only instance of a Model in GAE | Does anyone know a clever way, in Google App Engine, to return a wrapped Model instance that only exposes a few of the original properties, and does not allow saving the instance back to the datastore?
I'm not looking for ways of actually enforcing these rules, obviously it'll still be possible to change the instance b... | [
"Could you not create a method within your User class which instantiates a ReadOnlyUser object and copies the values of member variables over as appropriate? Your call would be something like User.get_by_id(1).readonly() with the readonly method defined in the following form:\nclass User(db.Model):\n def readonl... | [
4
] | [] | [] | [
"google_app_engine",
"model",
"python"
] | stackoverflow_0002754721_google_app_engine_model_python.txt |
Q:
Until when will Python 2.5 be supported?
Apparently Python only supports 2 minor versions (like 2.X), so that would mean Python 2.5 would get phased out when Python 2.7 comes out (in June 2010?)
Is this correct? PEP 356 -- Python 2.5 Release Schedule doesn't give much answers to this question.
A:
Python 2.5 will... | Until when will Python 2.5 be supported? | Apparently Python only supports 2 minor versions (like 2.X), so that would mean Python 2.5 would get phased out when Python 2.7 comes out (in June 2010?)
Is this correct? PEP 356 -- Python 2.5 Release Schedule doesn't give much answers to this question.
| [
"Python 2.5 will continue to get security updates until September 2011. See this message by Martin v. Löwis, the Python 2.5 release manager.\n"
] | [
6
] | [] | [] | [
"python",
"python_2.5"
] | stackoverflow_0002754755_python_python_2.5.txt |
Q:
python: subclass a metaclass
For putting methods of various classes into a global registry I'm using a decorator with a metaclass. The decorator tags, the metaclass puts the function in the registry:
class ExposedMethod (object):
def __init__(self, decoratedFunction):
self._decoratedFunction = decorate... | python: subclass a metaclass | For putting methods of various classes into a global registry I'm using a decorator with a metaclass. The decorator tags, the metaclass puts the function in the registry:
class ExposedMethod (object):
def __init__(self, decoratedFunction):
self._decoratedFunction = decoratedFunction
def __call__(__self... | [
"Your ExposedMethod instances do not behave as normal instance methods but rather like static methods -- the fact that you're giving one of them a self argument hints that you're not aware of that. You may need to add a __get__ method to the ExposedMethod class to make it a descriptor, just like function objects a... | [
5,
0,
0
] | [] | [] | [
"metaclass",
"python"
] | stackoverflow_0002744687_metaclass_python.txt |
Q:
Merge decorator function as class
Need to create a class that will do all things as the "merge" function. In class i will change, process and add new arguments.
def merge(*arg, **kwarg): # get decorator args & kwargs
def func(f):
def tmp(*args, **kwargs): # get function args & kwargs
kw... | Merge decorator function as class | Need to create a class that will do all things as the "merge" function. In class i will change, process and add new arguments.
def merge(*arg, **kwarg): # get decorator args & kwargs
def func(f):
def tmp(*args, **kwargs): # get function args & kwargs
kwargs.update(kwarg) # merge two dictiona... | [
"I'm not sure I quite get what you're asking. Your implementation works fine, and you won't get around having two levels of indirection if you want to create a parametrized decorator of any kind.\nTo make merge a class you could do this\nclass Merge(object):\n def __init__(self, **extra_kws):\n self.extra... | [
2
] | [] | [] | [
"arguments",
"class",
"decorator",
"keyword_argument",
"python"
] | stackoverflow_0002754363_arguments_class_decorator_keyword_argument_python.txt |
Q:
str.format() raises KeyError
The following code raises a KeyError exception:
addr_list_formatted = []
addr_list_idx = 0
for addr in addr_list: # addr_list is a list
addr_list_idx = addr_list_idx + 1
addr_list_formatted.append("""
"{0}"
{
"gamedir" "str"
"address" "{1}"
... | str.format() raises KeyError | The following code raises a KeyError exception:
addr_list_formatted = []
addr_list_idx = 0
for addr in addr_list: # addr_list is a list
addr_list_idx = addr_list_idx + 1
addr_list_formatted.append("""
"{0}"
{
"gamedir" "str"
"address" "{1}"
}
""".format(addr_list_i... | [
"The problem is that those { and } characters you have there don't specify a key for formatting. You need to double them up, so change your code to:\naddr_list_formatted.append(\"\"\"\n \"{0}\"\n {{\n \"gamedir\" \"str\"\n \"address\" \"{1}\"\n }}\n\"\"\".format(addr_list_idx, addr))\n\n"
] | [
164
] | [] | [] | [
"delimiter",
"missing_data",
"python",
"string_formatting",
"syntax"
] | stackoverflow_0002755201_delimiter_missing_data_python_string_formatting_syntax.txt |
Q:
Reduce function calls
I profiled my python program and found that the following function was taking too long to run. Perhaps, I can use a different algorithm and make it run faster. However, I have read that I can also possibly increase the speed by reducing function calls, especially when it gets called repeatedl... | Reduce function calls | I profiled my python program and found that the following function was taking too long to run. Perhaps, I can use a different algorithm and make it run faster. However, I have read that I can also possibly increase the speed by reducing function calls, especially when it gets called repeatedly within a loop. I am a pyt... | [
"I doubt you can get much speedup in this case by hoisting the lookup of person.getUtility (by class, not by instances, as other instances have pointed out). Maybe...:\nreturn sum(1 for p in setOfPeople\n if p.periodCarPurchased is None\n and p.getUtility(theCar) >= price)\n\nbut I suspect most... | [
2,
1,
1,
1
] | [] | [] | [
"performance",
"python"
] | stackoverflow_0002751861_performance_python.txt |
Q:
Converting html entities into their values in python
I use this regex on some input,
[^a-zA-Z0-9@#]
However this ends up removing lots of html special characters within the input, such as
#227;, #1606;, #1588; (i had to remove the & prefix so that it wouldn't
show up as the actual value..)
is there a way that ... | Converting html entities into their values in python | I use this regex on some input,
[^a-zA-Z0-9@#]
However this ends up removing lots of html special characters within the input, such as
#227;, #1606;, #1588; (i had to remove the & prefix so that it wouldn't
show up as the actual value..)
is there a way that I can convert them to their values so that it will satisfy... | [
"Given that your text appears to have numeric-coded, not named, entities, you can first convert your byte string that includes xml entity defs (ampersand, hash, digits, semicolon) to unicode:\nimport re\nxed_re = re.compile(r'&#(\\d+);')\ndef usub(m): return unichr(int(m.group(1)))\n\ns = 'ã, ن, ش'... | [
4,
1,
0
] | [] | [] | [
"html_entities",
"python",
"special_characters"
] | stackoverflow_0002755432_html_entities_python_special_characters.txt |
Q:
Python Mechanize unable to avoid redirect when Post
I am trying to crawl a site using mechanize.
The site provides search results in different pages.
When posting to get the next set of results, something is wrong and the server redirects me to the first page, asking mechanize to update the SearchSession Cookie.
I... | Python Mechanize unable to avoid redirect when Post | I am trying to crawl a site using mechanize.
The site provides search results in different pages.
When posting to get the next set of results, something is wrong and the server redirects me to the first page, asking mechanize to update the SearchSession Cookie.
I have been debugging the requests using Firefox and they ... | [
"The SearchSession cookies are quite different: the working one has\nSearchSession=SessionGuid=71de63de-3bd0-4787-895d-b6b9e7c93801\n\nand the non-working one has\nSearchSession=SessionGuid=33e4e439-c2d6-423f-900f-574099310d5a\n\nDo you have any way to independently validate why the second one might not be acceptab... | [
1
] | [] | [] | [
"mechanize",
"post",
"python",
"redirect"
] | stackoverflow_0002754922_mechanize_post_python_redirect.txt |
Q:
Algorithm detect repeating/similiar strings in a corpus of data -- say email subjects, in Python
I'm downloading a long list of my email subject lines , with the intent of finding email lists that I was a member of years ago, and would want to purge them from my Gmail account (which is getting pretty slow.)
I'm sp... | Algorithm detect repeating/similiar strings in a corpus of data -- say email subjects, in Python | I'm downloading a long list of my email subject lines , with the intent of finding email lists that I was a member of years ago, and would want to purge them from my Gmail account (which is getting pretty slow.)
I'm specifically thinking of newsletters that often come from the same address, and repeat the product/servi... | [
"I would first turn each string of characters into a set or multiset of words (ignoring punctuation and differences in lower/upper case). (If that's not powerful enough, in a second pass I could try pairs or even triples of adjacent words, known as bigrams and trigrams). The key measure of similarity between stri... | [
4,
1
] | [] | [] | [
"data_mining",
"email",
"fuzzy_search",
"python",
"string"
] | stackoverflow_0002752022_data_mining_email_fuzzy_search_python_string.txt |
Q:
Python invalid syntax with "with" statement
I am working on writing a simple python application for linux (maemo). However I am getting SyntaxError: invalid syntax on line 23: with open(file,'w') as fileh:
The code can be seen here: http://pastebin.com/MPxfrsAp
I can not figure out what is wrong with my code, I am... | Python invalid syntax with "with" statement | I am working on writing a simple python application for linux (maemo). However I am getting SyntaxError: invalid syntax on line 23: with open(file,'w') as fileh:
The code can be seen here: http://pastebin.com/MPxfrsAp
I can not figure out what is wrong with my code, I am new to python and the "with" statement. So, what... | [
"Most likely, you are using an earlier version of Python that doesn't support the with statement. Here's how to do the same thing without using with:\nfileh = open(file, 'w')\ntry:\n # Do things with fileh here\nfinally:\n fileh.close()\n\n"
] | [
26
] | [] | [] | [
"python",
"syntax",
"syntax_error"
] | stackoverflow_0002755849_python_syntax_syntax_error.txt |
Q:
Python questions from beginner
I'm thinking about rewriting an MS Access db I wrote years ago into a stand-alone Python app.
Other than a college class called "Intro to C++" (console only, with OOP concepts) and the Access db itself, I have no experience, so I need to ask if the basis for my decision to go with Py... | Python questions from beginner | I'm thinking about rewriting an MS Access db I wrote years ago into a stand-alone Python app.
Other than a college class called "Intro to C++" (console only, with OOP concepts) and the Access db itself, I have no experience, so I need to ask if the basis for my decision to go with Python is correct. Is it true that:
1... | [
"Python is widely considered an easy language to learn, being simple and readable. For easy running of Python on any Windows PC I recommend Portable Python (other platforms such as Macs and Linux distros typically come with Python, so there's usually no need for such measures there). For running a pre-made, pre-p... | [
5,
2,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0002752055_python.txt |
Q:
How to pass elements of a list as arguments to a function?
I'm building a simple interpreter in python and I'm having trouble handling differing numbers of arguments to my functions. My current method is to get a list of the commands/arguments as follows.
args = str(raw_input('>> ')).split()
com = args.pop(0)
The... | How to pass elements of a list as arguments to a function? | I'm building a simple interpreter in python and I'm having trouble handling differing numbers of arguments to my functions. My current method is to get a list of the commands/arguments as follows.
args = str(raw_input('>> ')).split()
com = args.pop(0)
Then to execute com, I check to see if it is in my dictionary of co... | [
"Try unpacking your list into positional arguments:\ncommands[com](*args)\n\n"
] | [
14
] | [] | [] | [
"arguments",
"list",
"python"
] | stackoverflow_0002756116_arguments_list_python.txt |
Q:
How do I generate coverage xml report for a single package?
I'm using nose and coverage to generate coverage reports. I only have one package right now, ae, so I specify to only cover that:
nosetests -w tests/unit --with-xunit --with-coverage --cover-package=ae
And here are the results, which look good:
Name ... | How do I generate coverage xml report for a single package? | I'm using nose and coverage to generate coverage reports. I only have one package right now, ae, so I specify to only cover that:
nosetests -w tests/unit --with-xunit --with-coverage --cover-package=ae
And here are the results, which look good:
Name Stmts Exec Cover Missing
-------------------------... | [
"I had a similar problem and solved it with the --omit option. This made it run much faster and reduced the size of coverage.xml from 2MB to 70kB.\n--omit=PRE1,PRE2,... Omit files when their filename path starts with one of\n these prefixes.\n\nI'm on Mac OS X, so I omitted the /Library/ and /... | [
3,
0,
0
] | [] | [] | [
"code_coverage",
"coverage.py",
"nose",
"python"
] | stackoverflow_0002293647_code_coverage_coverage.py_nose_python.txt |
Q:
defining information out of class
is there a way to define a value within a class in the __init__ part, send it to some variable outside of the class without calling another function within the class?
like
class c:
def __init__(self, a):
self.a = a
b = 4 # do something like thi... | defining information out of class | is there a way to define a value within a class in the __init__ part, send it to some variable outside of the class without calling another function within the class?
like
class c:
def __init__(self, a):
self.a = a
b = 4 # do something like this so that outside of class c,
... | [
"I'm not sure I understood the question correctly, but try adding this line into the __init__:\nglobal b\n\nBefore assignment to b I mean. Like the first line of the function.\n",
"Since globals are bad, try a class variable. (Is there any reason you can't?) For example:\nclass C(object):\n def __init__(self,... | [
1,
1,
0
] | [] | [] | [
"class_design",
"python"
] | stackoverflow_0002755380_class_design_python.txt |
Q:
New at Python: GLPK not building properly / Python ImportError
This is a beginner question, and a follow-up to this one, where I was pointed to GLPK.
I'm trying to get PyGLPK, a Python binding for the GNU Linear Programming Kit up and running, but no matter what I do, I can't seem to build and install GLPK so tha... | New at Python: GLPK not building properly / Python ImportError | This is a beginner question, and a follow-up to this one, where I was pointed to GLPK.
I'm trying to get PyGLPK, a Python binding for the GNU Linear Programming Kit up and running, but no matter what I do, I can't seem to build and install GLPK so that Python finds it correctly. This comes after running ./configure, m... | [
"The problem isn't really specific to Python. The glpk module is an extension module, a C shared library that Python loads. That C shared library has a dependency on the GLPK C library that it wraps; loading the extension module should load the GLPK C library so that the extension module can reference symbols from ... | [
1,
1
] | [] | [] | [
"importerror",
"installation",
"module",
"python",
"unix"
] | stackoverflow_0002728385_importerror_installation_module_python_unix.txt |
Q:
Outputing json with well formed accents
I have an anoying problem that is giving me a hard time these days... I would like to develop a few webservices for my own usage and currently i am fighting with my damn french accents to be rendered correctly in my json outputs.
Here is my scenario: I retrieve a number of l... | Outputing json with well formed accents | I have an anoying problem that is giving me a hard time these days... I would like to develop a few webservices for my own usage and currently i am fighting with my damn french accents to be rendered correctly in my json outputs.
Here is my scenario: I retrieve a number of lines from my database that i put in a dict. W... | [
"Just like the docs say, pass ensure_ascii=False and encode manually.\n"
] | [
5
] | [] | [] | [
"diacritics",
"json",
"python",
"utf_8"
] | stackoverflow_0002757237_diacritics_json_python_utf_8.txt |
Q:
Cache the result of a MySQLdb database query in memory
Our application fetches the correct database server from a pool of database servers. So each query is really 2 queries, and they look like this:
Fetch the correct DB server
Execute the query
We do this so we can take DB servers online and offline as necessa... | Cache the result of a MySQLdb database query in memory | Our application fetches the correct database server from a pool of database servers. So each query is really 2 queries, and they look like this:
Fetch the correct DB server
Execute the query
We do this so we can take DB servers online and offline as necessary, as well as for load-balancing.
But the first query seems... | [
"Just make a cache(python dict) which stores the first query and return it everytime, clear the cache every N mins, for this you make a decorator or cache class e.g.\nimport time\n\ncache = {}\nlastTime = time.time()\n\ndef timedCacheDecorator(func):\n\n def wrap(*args, **kwargs):\n\n key = str(args)+str(... | [
5,
1
] | [] | [] | [
"caching",
"mysql",
"pylons",
"python"
] | stackoverflow_0002576867_caching_mysql_pylons_python.txt |
Q:
Django db encoding
I have a little problem with encoding. The data in db is ok, when I select the data in php its ok. Problem comes when I get the data and try to print it in the template, I get - Å port instead of Šport, etc.
Everything is set to utf-8 - in settings.py, meta tags in template, db table and I even ... | Django db encoding | I have a little problem with encoding. The data in db is ok, when I select the data in php its ok. Problem comes when I get the data and try to print it in the template, I get - Å port instead of Šport, etc.
Everything is set to utf-8 - in settings.py, meta tags in template, db table and I even have unicode method spec... | [
"It's definitely not Django issue. As far as I understood you try to introspect existing DB (I suppose it's MySQL because it looks like common problem after incorrect upgrade from 4.x to 5.x). You should find out necessary connect options and provide them via DATABASE_OPTIONS setting. Try something like this:\nDATA... | [
0
] | [] | [] | [
"django",
"encoding",
"python"
] | stackoverflow_0002757118_django_encoding_python.txt |
Q:
Load JSON in Python as header character set
I've always found character sets and encodings complicated to understand and here I'm faced with another problem. My apologies for any inaccuracies. I'll do my best.
I'm requesting data from a server which returns JSON. In the HTTP headers it also returns the character s... | Load JSON in Python as header character set | I've always found character sets and encodings complicated to understand and here I'm faced with another problem. My apologies for any inaccuracies. I'll do my best.
I'm requesting data from a server which returns JSON. In the HTTP headers it also returns the character set like so:
Content-Type: text/html; charset=UTF-... | [
"json.loads automatically handles strs that are passed to it in UTF-8, so, in this specific case, you shouldn't have to worry about charsets yourself. loads is already converting from UTF-8 to Python's UCS-2 Unicode representation for you.\nUnless you have some other reason why you really need to operate on the or... | [
2,
2
] | [] | [] | [
"character_encoding",
"json",
"python",
"unicode",
"utf_8"
] | stackoverflow_0002756847_character_encoding_json_python_unicode_utf_8.txt |
Q:
Renaming TurboGears 2's Repoze Fields with TGAdmin
I've been working on renaming TurboGears 2's Repoze 'groups' field to 'roles' to free the namespace and db tables for other purposes. Also roles makes much more sense to me then groups because I have a strong Drupal background.
Now I have found some of the docs to... | Renaming TurboGears 2's Repoze Fields with TGAdmin | I've been working on renaming TurboGears 2's Repoze 'groups' field to 'roles' to free the namespace and db tables for other purposes. Also roles makes much more sense to me then groups because I have a strong Drupal background.
Now I have found some of the docs to do this such as these:
http://www.turbogears.org/2.1/do... | [
"Why cross post with the TurboGears mailing list?\nhttp://groups.google.com/group/turbogears/browse_thread/thread/e6040eb194880fc6/\nThis just duplicates efforts for people trying to help you and is annoying for those who follow both the mailing list and Python related questions on StackOverflow.\n"
] | [
0
] | [] | [] | [
"pylons",
"python",
"repoze.who",
"turbogears2"
] | stackoverflow_0002755833_pylons_python_repoze.who_turbogears2.txt |
Q:
File mode for creating+reading+appending+binary
I need to open a file for reading and writing. If the file is not found, it should be created. It should also be treated as a binary for Windows. Can you tell me the file mode sequence I need to use for this?
I tried 'r+ab' but that doesn't create the files if they a... | File mode for creating+reading+appending+binary | I need to open a file for reading and writing. If the file is not found, it should be created. It should also be treated as a binary for Windows. Can you tell me the file mode sequence I need to use for this?
I tried 'r+ab' but that doesn't create the files if they are not found.
Thanks
| [
"The mode is ab+ the r is implied and 'a'ppend and ('w'rite '+' 'r'ead) are redundant. Since the CPython (i.e. regular python) file is based on the C stdio FILE type, here are the relevant lines from the fopen(3) man page:\n\nw+ Open for reading and writing. \nThe file is created if it does not\nexist, otherwise i... | [
64,
8
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0002757887_file_io_python.txt |
Q:
setfsuid() and python 2.5.4
I'm trying to use setfsuid() with python 2.5.4 and RHEL 5.4.
Since it's not included in the os module, I wrapped it in a C module of my own and installed it as a python extension module using distutils.
However when I try to use it I don't get the expected result.
setfsuid() returns val... | setfsuid() and python 2.5.4 | I'm trying to use setfsuid() with python 2.5.4 and RHEL 5.4.
Since it's not included in the os module, I wrapped it in a C module of my own and installed it as a python extension module using distutils.
However when I try to use it I don't get the expected result.
setfsuid() returns value indicating success (changing f... | [
"The ability to change the FSUID is limited to either root or non-root processes with the CAP_SETFCAP capability. These days it's usually considered bad practice to run a webserver with root permissions so, most likely, you'll need to set the capability on the file server (see man capabilities for details). Please ... | [
2
] | [] | [] | [
"operating_system",
"python"
] | stackoverflow_0002757991_operating_system_python.txt |
Q:
Not able to access parts of imported .PY in a .PSP
I'm trying to load a weather plugin for a website I'm working on. The weather plugin is a separate weather.py file located at /var/www/piss/plugins/base/weather.py. In the PSP it seems to import correctly, but I am unable to access any variables or objects from ... | Not able to access parts of imported .PY in a .PSP | I'm trying to load a weather plugin for a website I'm working on. The weather plugin is a separate weather.py file located at /var/www/piss/plugins/base/weather.py. In the PSP it seems to import correctly, but I am unable to access any variables or objects from the weather.py plugin in the PSP. Here's the code I hav... | [
"PSP isn't particularly popular in the Python world, and for good reason. Pretty much any other templating system is a better choice. It's been a very long time since I looked at PSP, and I may be misremembering how it works, but I'm not sure you expect PSP to know that pwd, html1 and currentWeather come from the w... | [
0
] | [] | [] | [
"mod_python",
"python",
"python_server_pages"
] | stackoverflow_0002757673_mod_python_python_python_server_pages.txt |
Q:
Declaring models elsewhere than in "models.py" AND dynamically
I have an application that splits models into different files.
Actually the folder looks like :
>myapp
__init__.py
models.py
>hooks
...
...
myapp don't care about what's in the hooks, folder, except that there are models, and t... | Declaring models elsewhere than in "models.py" AND dynamically | I have an application that splits models into different files.
Actually the folder looks like :
>myapp
__init__.py
models.py
>hooks
...
...
myapp don't care about what's in the hooks, folder, except that there are models, and that they have to be imported somehow, and installed by syncdb. So, I... | [
"Django know of all models that are defined anywhere in your project, so you only need to make sure that the code where they are defined gets executed. This usually happens when you import the module in which the models are defined.\nThe other thing which is important to know is that the app_label attribute of the ... | [
1,
0
] | [
"Assuming you have a file called users_models.py in hooks folder:\nYou could say from hooks.users_models import * in myapp.__init__.py right ? That will be picked up by syncdb for sure.\n"
] | [
-1
] | [
"django",
"python"
] | stackoverflow_0002737275_django_python.txt |
Q:
What are the elegant ways to do MixIns in Python?
I need to find an elegant way to do 2 kinds of MixIns.
First:
class A(object):
def method1(self):
do_something()
Now, a MixInClass should make method1 do this: do_other() -> A.method1() -> do_smth_else() - i.e. basically "wrap" the older function. I'm ... | What are the elegant ways to do MixIns in Python? | I need to find an elegant way to do 2 kinds of MixIns.
First:
class A(object):
def method1(self):
do_something()
Now, a MixInClass should make method1 do this: do_other() -> A.method1() -> do_smth_else() - i.e. basically "wrap" the older function. I'm pretty sure there must exist a good solution to this.
S... | [
"I think, that can be handled in quite a Pythonic way using decorators. (PEP 318, too)\n",
"Here is another way to implement MixInClass1, MixinClass2:\nDecorators are useful when you need to wrap many functions. Since MixinClass1 needs to wrap only one function, I think it is clearer to monkey-patch:\nUsing doubl... | [
5,
3
] | [] | [] | [
"mixins",
"python"
] | stackoverflow_0002757358_mixins_python.txt |
Q:
Linux distro name parsing
I chose this way to get linux distro name:
ls /etc/*release
And now I have to parse it for name:
/etc/<name>-release
def checkDistro():
p = Popen('ls /etc/*release' , shell = True, stdout = PIPE)
distroRelease = p.stdout.read()
distroName = re.search( ur"\/etc\/(.*)\-releas... | Linux distro name parsing | I chose this way to get linux distro name:
ls /etc/*release
And now I have to parse it for name:
/etc/<name>-release
def checkDistro():
p = Popen('ls /etc/*release' , shell = True, stdout = PIPE)
distroRelease = p.stdout.read()
distroName = re.search( ur"\/etc\/(.*)\-release", distroRelease).group()
... | [
"An alternative is to use the builtin method platform.linux_distribution() (available in Python 2.6+):\n>>> import platform\n>>> platform.linux_distribution()\n('Red Hat Enterprise Linux Server', '5.1', 'Tikanga')\n\nIn older versions of Python, platform.dist() can be used:\n>>> import platform\n>>> platform.dist()... | [
7,
5,
3,
2,
1
] | [] | [] | [
"linux",
"python",
"regex"
] | stackoverflow_0002756873_linux_python_regex.txt |
Q:
How do I read user input in python thread?
I'm trying to read from a thread in python as follows
import threading, time, random
var = True
class MyThread(threading.Thread):
def set_name(self, name):
self.name = name
def run(self):
global var
while var == True:
print "... | How do I read user input in python thread? | I'm trying to read from a thread in python as follows
import threading, time, random
var = True
class MyThread(threading.Thread):
def set_name(self, name):
self.name = name
def run(self):
global var
while var == True:
print "In mythread " + self.name
time.sleep... | [
"Your code is a bit strange. If you are using the reader strictly to quit the program, why not have it outside the threading code entirely? It doesn't need to be in the thread, for your purposes, and won't work in the thread.\nRegardless, I don't think you want to take this road. Consider this problem: multiple ... | [
1,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0002757318_multithreading_python.txt |
Q:
Google App Engine - Document Editor Creation/Tap Into Google Docs?
What is the best way to create a custom document editor in GAE? I'm making a website meant for a School Robotics Club (With support for any other organization - DRY).
We currently use Google services for online collaboration, I'm wondering if there... | Google App Engine - Document Editor Creation/Tap Into Google Docs? | What is the best way to create a custom document editor in GAE? I'm making a website meant for a School Robotics Club (With support for any other organization - DRY).
We currently use Google services for online collaboration, I'm wondering if there is a way to tap into Google Docs and allow users to edit a Google Docum... | [
"That depends on what you mean by 'use' - if you don't want Google Accounts, or the editor, it's hard to see what's left. You can use the document list data API to upload, download, and convert docs.\n",
"It sounds to me like you want to use the Google Docs editor like a widget within your application. To the be... | [
3,
2
] | [] | [] | [
"ajax",
"google_app_engine",
"python",
"text_editor",
"tinymce"
] | stackoverflow_0002755069_ajax_google_app_engine_python_text_editor_tinymce.txt |
Q:
Calling methods in super class constructor or subclass constructor?
1. Passing configuration to the __init__ method which calls register implicitely:
class Base:
def __init__(self, *verbs):
if not verbs:
verbs = "get", "post"
self._register(verbs)
def _register(self, *verbs):
... | Calling methods in super class constructor or subclass constructor? | 1. Passing configuration to the __init__ method which calls register implicitely:
class Base:
def __init__(self, *verbs):
if not verbs:
verbs = "get", "post"
self._register(verbs)
def _register(self, *verbs):
pass
class Sub(Base):
def __init__(self):
super().__... | [
"I think none of these options is good. The closest solution would probably be:\nclass Base(object):\n\n def __init__(self):\n self._register(\"get\", \"post\")\n\n\nclass Sub(Base):\n\n def __init__(self):\n super(Sub, self).__init__()\n self._register(\"put\")\n\nI'm also wondering if i... | [
3,
0,
0,
0
] | [] | [] | [
"constructor",
"oop",
"python"
] | stackoverflow_0002749327_constructor_oop_python.txt |
Q:
Exit Tks mainloop in Python?
I'm writing a slideshow program with Tkinter, but I don't know how to go to the next image without binding a key.
import os, sys
import Tkinter
import Image, ImageTk
import time
root = Tkinter.Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.overrideredirect(1)
roo... | Exit Tks mainloop in Python? | I'm writing a slideshow program with Tkinter, but I don't know how to go to the next image without binding a key.
import os, sys
import Tkinter
import Image, ImageTk
import time
root = Tkinter.Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.overrideredirect(1)
root.geometry("%dx%d+0+0" % (w, h))
r... | [
"You can try\nroot.after(10*1000, root.quit)\n\n",
"There's no need to do a loop over your images -- you're already running in a loop (mainloop) so take advantage of it. The typical way to do this is to create a method that draws something, waits for a period of time, then calls itself. This isn't recursion, it's... | [
5,
5
] | [] | [] | [
"python",
"tk_toolkit",
"tkinter"
] | stackoverflow_0002732847_python_tk_toolkit_tkinter.txt |
Q:
Correct way to create a shell like environment in python?
I'm trying to create a shell like environment, where a user is presented with ">>>" and can type in any of a number of pre-defined commands. However, the only way I can think of implementing this is with a dictionary mapping commands->code and python's "exe... | Correct way to create a shell like environment in python? | I'm trying to create a shell like environment, where a user is presented with ">>>" and can type in any of a number of pre-defined commands. However, the only way I can think of implementing this is with a dictionary mapping commands->code and python's "exec".
Is there a more correct way of doing this?
| [
"The standard library module cmd is specifically for this.\nIf you do end up rolling your own solution, there's no need to involve exec. Your dictionary mapping commands to code should map strings to strings. It can map strings to actual functions. In fact, a class is a mapping of strings to code (method names t... | [
6,
0
] | [] | [] | [
"exec",
"python",
"shell"
] | stackoverflow_0002755660_exec_python_shell.txt |
Q:
default values for variable argument list in Python
Is it possible to set a default value for a variable argument list in Python 3?
Something like:
def do_it(*args=(2, 5, 21)):
pass
I wonder that a variable argument list is of type tuple but no tuple is accepted here.
A:
If not syntactically, then dependin... | default values for variable argument list in Python | Is it possible to set a default value for a variable argument list in Python 3?
Something like:
def do_it(*args=(2, 5, 21)):
pass
I wonder that a variable argument list is of type tuple but no tuple is accepted here.
| [
"If not syntactically, then depending on what behavior you want:\ndef do_it(*args):\n if not args: args = (2, 5, 21)\n\nor\ndef do_it(a=2, b=5, c=21, *args):\n args = (a,b,c)+args\n\nshould do it. \n",
"Initializing a list like that usually isn't a good idea.\nThe default value is evaluated only once. This ... | [
7,
1
] | [] | [] | [
"arguments",
"function",
"python"
] | stackoverflow_0002759464_arguments_function_python.txt |
Q:
Django models: Use multiple values as a key?
Here is a simple model:
class TakingCourse(models.Model):
course = models.ForeignKey(Course)
term = models.ForeignKey(Term)
Instead of Django creating a default primary key, I would like to use both course and term as the primary key - taken together, they uniq... | Django models: Use multiple values as a key? | Here is a simple model:
class TakingCourse(models.Model):
course = models.ForeignKey(Course)
term = models.ForeignKey(Term)
Instead of Django creating a default primary key, I would like to use both course and term as the primary key - taken together, they uniquely identify a tuple. Is this allowed by Django?
... | [
"You can use the unique_together option.\nclass TakingCourse(models.Model):\n course = models.ForeignKey(Course)\n term = models.ForeignKey(Term)\n\n class Meta:\n unique_together = ('course', 'term')\n\nIt would be better if you do something like this, though:\nclass MyUser(models.Model):\n user... | [
5
] | [] | [] | [
"database",
"django",
"models",
"python"
] | stackoverflow_0002759503_database_django_models_python.txt |
Q:
Sorting numbers in string format with Python
I have a list that has some chapter numbers in string.
When I sort the keys using keys function, it gives me wrong results.
keys = ['1.1', '1.2', '2.1', '10.1']
keys.sort()
print keys
['1.1', '1.2', '10.1', '2.1']
How can I use the sort function to get
['1.1', '1... | Sorting numbers in string format with Python | I have a list that has some chapter numbers in string.
When I sort the keys using keys function, it gives me wrong results.
keys = ['1.1', '1.2', '2.1', '10.1']
keys.sort()
print keys
['1.1', '1.2', '10.1', '2.1']
How can I use the sort function to get
['1.1', '1.2', '2.1', '10.1']
What if the array has somethi... | [
"keys.sort(key=lambda x: [int(y) for y in x.split('.')])\n\n",
"from distutils.version import StrictVersion\nkeys.sort(key=StrictVersion)\n\nSince chapter numbers are a subset of version numbers, this covers your needs.\n",
"This works:\nkeys.sort(key=lambda x: map(int, x.split('.')))\n\n",
"Provide a custom ... | [
10,
4,
2,
1
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0002597099_python_sorting.txt |
Q:
Django: Admin with multiple sites & languages
I'm supposed to build some Django apps, that allow you to administer multiple sites through one backend. The contrib.sites framework is quite perfect for my purposes. I can run multiple instances of manage.py with different settings for each site; but how should django... | Django: Admin with multiple sites & languages | I'm supposed to build some Django apps, that allow you to administer multiple sites through one backend. The contrib.sites framework is quite perfect for my purposes. I can run multiple instances of manage.py with different settings for each site; but how should django's admin deal with different settings for different... | [
"There is an old blog post by James Bennet which might be helpful:\n\n\nCreate a new Site object in your admin for each domain, and put the id of that Site into its settings file as SITE_ID so Django knows which site in the database corresponds to this settings file.\nIn the settings file for your original site (th... | [
1
] | [] | [] | [
"django",
"multilingual",
"multiple_sites",
"python",
"sites"
] | stackoverflow_0002755087_django_multilingual_multiple_sites_python_sites.txt |
Q:
app_label in an abstract Django model
I'm trying to get an abstract model working in Django and I hit a brick wall trying to set the related_name per the recommendation here: http://docs.djangoproject.com/en/dev/topics/db/models/#be-careful-with-related-name
This is what my abstract model looks like:
class CommonM... | app_label in an abstract Django model | I'm trying to get an abstract model working in Django and I hit a brick wall trying to set the related_name per the recommendation here: http://docs.djangoproject.com/en/dev/topics/db/models/#be-careful-with-related-name
This is what my abstract model looks like:
class CommonModel(models.Model):
created_on = model... | [
"Note the bold text on your link: \"Changed in development version\". If you're not using a recent checkout of Django trunk - for instance, you're on the latest released version, 1.1 - you should be using this link for the documentation. That version of the text makes no reference to app_label, because it had not y... | [
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0002759824_django_django_models_python.txt |
Q:
Regex optional match in python fails
tickettypepat = (r'MIS Notes:.*(//p//)?.*')
retype = re.search(tickettypepat,line)
if retype:
print retype.group(0)
print retype.group(1)
Given the input.
MIS Notes: //p//
Can anyone tell me why group(0) is
MIS Notes: //p//
and group(1) is returning as None?
I was origi... | Regex optional match in python fails | tickettypepat = (r'MIS Notes:.*(//p//)?.*')
retype = re.search(tickettypepat,line)
if retype:
print retype.group(0)
print retype.group(1)
Given the input.
MIS Notes: //p//
Can anyone tell me why group(0) is
MIS Notes: //p//
and group(1) is returning as None?
I was originally using regex because, before I ran in... | [
"MIS Notes:.*(//p//)?.* works like this, on the example of \"MIS Notes: //p//\" as the target:\n\nMIS Notes: matches \"MIS Notes:\", no surprises here.\n.* immediately runs to the end of the string (match so far \"MIS Notes: //p//\")\n(//p//)? is optional. Nothing happens.\n.* has nothing left to match, we are at t... | [
4,
1,
0
] | [] | [] | [
"option_type",
"python",
"regex",
"regex_group"
] | stackoverflow_0002760083_option_type_python_regex_regex_group.txt |
Q:
limiting the rate of emails using python
I have a python script which reads email addresses from a database for a particular date, example today, and sends out an email message to them one by one. It reads data from MySQL using the MySQLdb module and stores all results in a dictionary and sends out emails using : ... | limiting the rate of emails using python | I have a python script which reads email addresses from a database for a particular date, example today, and sends out an email message to them one by one. It reads data from MySQL using the MySQLdb module and stores all results in a dictionary and sends out emails using :
rows = cursor.fetchall () #All email addresse... | [
"If you don't mind if the script is running for hours on end, you can just pause for a few seconds between each email.\nfrom time import sleep\n\nif address_count < 500:\n sleep_time = 0\nelse:\n sleep_time = 7.5\n\nfor address in addresses:\n send_message(address)\n sleep(sleep_time)\n\n(Note: This was... | [
3,
0,
0
] | [] | [] | [
"email",
"mysql",
"python"
] | stackoverflow_0002760351_email_mysql_python.txt |
Q:
str is not callable error in python
import sys
import md5
from TOSSIM import *
from RadioCountMsg import *
t = Tossim([]) #The Tossim object is defined here
m = t.mac()#The mac layer is defined here , in which the communication takes place
r = t.radio()#The radio communication link object is defined here , as ... | str is not callable error in python | import sys
import md5
from TOSSIM import *
from RadioCountMsg import *
t = Tossim([]) #The Tossim object is defined here
m = t.mac()#The mac layer is defined here , in which the communication takes place
r = t.radio()#The radio communication link object is defined here , as the communication needs Rf frequency to tr... | [
"On line 35 you reassign 'str' from the built-in it originally references to a different object. Then, on line 53, you try to use it as the original built-in again. If you want to use 'str' as 'str()' on line 53, you need to use a different variable name up on line 35 (and 36, and 37)\nDon't use 'str' here:\nfor li... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0002760526_python.txt |
Q:
how to pass a command line argument to a c++ file through a python code?
i am compiling a c++ file in python code using this os.system("rc.cpp") and then os.system("./a.out") . I would like to pass a command line argument to the rc file . how do i do it?
A:
You should be using the subprocess module to call other... | how to pass a command line argument to a c++ file through a python code? | i am compiling a c++ file in python code using this os.system("rc.cpp") and then os.system("./a.out") . I would like to pass a command line argument to the rc file . how do i do it?
| [
"You should be using the subprocess module to call other executables. subprocess.Popen takes a list as it's first argument. The first item in the list is the executable you'd like to call. All list items are the arguments passed to the executable.\nfrom subprocess import Popen\np = Popen(['/usr/bin/foo', 'arg1', 'a... | [
1,
0
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0002760541_c++_python.txt |
Q:
Bypass django form validation on new form instance
I have a situation where we are trying to autofill some form data on the second page of a signup and I was wondering if there's a way to bypass the entire form validation when we pass in only a couple of fields?
so we have something like
form = NewForm(request.POS... | Bypass django form validation on new form instance | I have a situation where we are trying to autofill some form data on the second page of a signup and I was wondering if there's a way to bypass the entire form validation when we pass in only a couple of fields?
so we have something like
form = NewForm(request.POST)
Where request.POST only contains some of the fields ... | [
"If you're passing in initial values, you should use the initial parameter, not data (ie the first positional argument). This does not trigger validation.\nform = NewForm(initial=dict_of_field_values)\n\n"
] | [
6
] | [] | [] | [
"django",
"python",
"validation"
] | stackoverflow_0002760793_django_python_validation.txt |
Q:
Navigation graphics overlayed over video
Imagine I have a video playing.. Can I have some sort of motion graphics being played 'over' that video.. Like say the moving graphics is on an upper layer than the video, which would be the lower layer..
I am comfortable in a C++ and Python, so a solution that uses these t... | Navigation graphics overlayed over video | Imagine I have a video playing.. Can I have some sort of motion graphics being played 'over' that video.. Like say the moving graphics is on an upper layer than the video, which would be the lower layer..
I am comfortable in a C++ and Python, so a solution that uses these two will be highly appreciated..
Thank you in ... | [
"I'm not sure I understand the question correctly but a video file is a sequence of pictures that you can extract (for instance with the opencv library C++ interface) and then you can use it wherever you want. You can play the video on the sides of an opengl 3D cube (available in all opengl tutorials) and other 3D ... | [
0
] | [] | [] | [
"c++",
"graphics",
"python",
"video",
"video_processing"
] | stackoverflow_0002759738_c++_graphics_python_video_video_processing.txt |
Q:
Problem with list slice syntax in python
The extended indexing syntax is mentioned in python's doc.
slice([start], stop[, step])
Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns... | Problem with list slice syntax in python | The extended indexing syntax is mentioned in python's doc.
slice([start], stop[, step])
Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator.
a[start:stop:step] works as desc... | [
"a[start:stop,i] calls the method a.__getitem__((slice(start,stop,None), i)).\nThis raises a TypeError if a is a list, but it is valid and useful notation if a is a numpy array. In fact, I believe the developers of Numpy asked the developers of Python to extend valid Python slicing notation precisely so that numpy ... | [
12,
4
] | [] | [] | [
"python",
"slice",
"syntax"
] | stackoverflow_0002761003_python_slice_syntax.txt |
Q:
In python beyond 'exec string' is there a way to 'import' using the db as a filesystem
Although it does not seem possible, I wanted to put this out there to see if others had some innovative solutions to 'dynamically loading and executing code in python'
So if one saved code in a database, one could read it and 'e... | In python beyond 'exec string' is there a way to 'import' using the db as a filesystem | Although it does not seem possible, I wanted to put this out there to see if others had some innovative solutions to 'dynamically loading and executing code in python'
So if one saved code in a database, one could read it and 'exec it', however if one wanted to use it in a similar fashion to the filesystem, one would n... | [
"See PEP 302: New Import Hooks, for details on how to hook the importer.\nPython 3.1 has an importlib, designed to make hooking the importer a bit easier.\n",
"It is possible to implement customized import hooks and register them into sys.meta_path. See PEP 302 for the details.\n"
] | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002761013_python.txt |
Q:
Writing a file shredder in python or ruby?
In the effort to learn python and/or ruby, I was wondering how a file shredder would be implemented? I would like it to take in a file as an argument and then employ an algorithm to make that file unrecoverable. Would possibly add the support for multiple files or even wh... | Writing a file shredder in python or ruby? | In the effort to learn python and/or ruby, I was wondering how a file shredder would be implemented? I would like it to take in a file as an argument and then employ an algorithm to make that file unrecoverable. Would possibly add the support for multiple files or even whole directories later.
| [
"Just as a warning, shredders generally will have varying levels of success on modern systems, thanks to journals, copy-on-write file systems, wear leveling (flash), and other techniques used in modern system. Might wanna check out wikipedia on some of the pitfalls.\n\nIn short, you'd need to be able to write direc... | [
4,
1
] | [] | [] | [
"python",
"ruby",
"shred"
] | stackoverflow_0002758868_python_ruby_shred.txt |
Q:
Getting a RichTextCtrl's default font size in wxPython
I have a RichTextCtrl, which I've modified to accept HTML input. The HTML parsing code needs to be able to increase and decrease the font size as it gets tags like <font size="-1">, but I can't work out how to get the control's default font size to adjust.
I t... | Getting a RichTextCtrl's default font size in wxPython | I have a RichTextCtrl, which I've modified to accept HTML input. The HTML parsing code needs to be able to increase and decrease the font size as it gets tags like <font size="-1">, but I can't work out how to get the control's default font size to adjust.
I tried the following (where self is my RichTextCtrl):
fred = w... | [
"Worked this out. Before any data is written to the control:\nself.defaultstyle = wx.richtext.RichTextAttr()\nself.GetStyle(self.GetInsertionPoint(), self.defaultstyle)\nself.defaultsize = self.defaultstyle.GetFont().GetPointSize()\n\n"
] | [
0
] | [] | [] | [
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0002751943_python_wxpython_wxwidgets.txt |
Q:
Are classes necessary for creating methods (defs) in Python?
Are classes necessary for creating methods (defs) in Python?
A:
No. However, def's which aren't part of a class are usually called functions, not methods - but they are exactly the same thing, aside from not being associated with a class.
def myFunctio... | Are classes necessary for creating methods (defs) in Python? | Are classes necessary for creating methods (defs) in Python?
| [
"No. However, def's which aren't part of a class are usually called functions, not methods - but they are exactly the same thing, aside from not being associated with a class.\ndef myFunction(arg1, arg2):\n # do something here\n\n",
"No, you can create functions using def without having to wrap them in classes... | [
12,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0002761145_python.txt |
Q:
taking a character input in python from a file?
in python , suppose i have file data.txt . which has 6 lines of data . I want to calculate the no of lines which i am planning to do by going through each character and finding out the number of '\n' in the file . How to take one character input from the file ? Readl... | taking a character input in python from a file? | in python , suppose i have file data.txt . which has 6 lines of data . I want to calculate the no of lines which i am planning to do by going through each character and finding out the number of '\n' in the file . How to take one character input from the file ? Readline takes the whole line .
| [
"I think the method you're looking for is readlines, as in \nlines = open(\"inputfilex.txt\", \"r\").readlines()\n\nThis will give you a list of each of the lines in the file. To find out how many lines, you can just do:\nlen(lines)\n\nAnd then access it using indexes, like lines[3] or lines[-1] as you would any no... | [
3,
1,
0,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0002761245_file_python.txt |
Q:
Third-party titlecase method in Python
The standard string title() method in Python is pretty naive and doesn't correctly handle converting even fairly simple words and phrases to title case (hyphenated words, phrases with quotes, phrases with prepositions, etc.).
In Googling around, I found a few solutions in dif... | Third-party titlecase method in Python | The standard string title() method in Python is pretty naive and doesn't correctly handle converting even fairly simple words and phrases to title case (hyphenated words, phrases with quotes, phrases with prepositions, etc.).
In Googling around, I found a few solutions in different languages to this problem. Can anyone... | [
"Found this via Google: http://muffinresearch.co.uk/archives/2008/05/27/titlecasepy-titlecase-in-python/\n"
] | [
2
] | [] | [] | [
"capitalization",
"python",
"string"
] | stackoverflow_0002761160_capitalization_python_string.txt |
Q:
Python iterator question
I have this list:
names = ['john','Jonh','james','James','Jardel']
I want loop over the list and handle consecutive names with a case insensitive match in the same iteration. So in the first iteration I would do something with'john' and 'John' and I want the next iteration to start at 'ja... | Python iterator question | I have this list:
names = ['john','Jonh','james','James','Jardel']
I want loop over the list and handle consecutive names with a case insensitive match in the same iteration. So in the first iteration I would do something with'john' and 'John' and I want the next iteration to start at 'james'.
I can't think of a way t... | [
"This would be one for itertools.groupby, which groups consecutive equal elements from a list or other iterable. you can specify a function to do the comparison, so that, in your case, the same name in different cases can still be counted as the same thing.\nfor k, g in itertools.groupby(names, lambda s: s.lower())... | [
6,
2,
0,
0,
0
] | [] | [] | [
"for_in_loop",
"for_loop",
"python"
] | stackoverflow_0002760183_for_in_loop_for_loop_python.txt |
Q:
python blocking sockets, send returns immediately
I am writing a multithreaded socket application in Python using the socket module.
the server listens for connections and when it gets one it spawns a thread for that socket.
the server thread sends some data to the client. but the client is not yet ready to receiv... | python blocking sockets, send returns immediately | I am writing a multithreaded socket application in Python using the socket module.
the server listens for connections and when it gets one it spawns a thread for that socket.
the server thread sends some data to the client. but the client is not yet ready to receive it. I thought this would have caused the server to wa... | [
"\nany ideas why send() is returning straight away?\n\nall send() does is fill the network buffer and return the ammount of bytes sent.\nif you want a send that blocks just recv an acknowledgement message from the client. \n",
"The client doesn't have to be ready to receive data - data will queue up in the soc... | [
4,
1,
1
] | [] | [] | [
"blocking",
"multithreading",
"python",
"send",
"sockets"
] | stackoverflow_0002432814_blocking_multithreading_python_send_sockets.txt |
Q:
RSA encrypted data block size
how do you store an rsa encrypted data block? the output might be significantly greater than the original input data block size, and i dont think people waste memory by padding bucket loads of 0s in front of each data block. besides, how would they be removed? or is each block stored ... | RSA encrypted data block size | how do you store an rsa encrypted data block? the output might be significantly greater than the original input data block size, and i dont think people waste memory by padding bucket loads of 0s in front of each data block. besides, how would they be removed? or is each block stored on new lines within the file? if th... | [
"You are missing that they do indeed pad with bucket loads of random bits.\nSome padding schemes use the first few bytes to describe how many bytes are padding; others have \"everything until the first 0x00\" is padding.\n"
] | [
1
] | [] | [] | [
"cryptography",
"python",
"rsa"
] | stackoverflow_0002761529_cryptography_python_rsa.txt |
Q:
Need a workaround to filter on related model and aggregated fields in Django
I opened a ticket for this problem.
In a nutshell here is my model:
class Plan(models.Model):
cap = models.IntegerField()
class Phone(models.Model):
plan = models.ForeignKey(Plan, related_name='phones')
class Call(models.Model):
phon... | Need a workaround to filter on related model and aggregated fields in Django | I opened a ticket for this problem.
In a nutshell here is my model:
class Plan(models.Model):
cap = models.IntegerField()
class Phone(models.Model):
plan = models.ForeignKey(Plan, related_name='phones')
class Call(models.Model):
phone = models.ForeignKey(Phone, related_name='calls')
cost = models.IntegerField()
... | [
"When aggregating, SQL requires any value in a field either be unique within a group, or that the field be wrapped in an aggregation function which ensures that only one value will come out for each group. The problem here is that \"app_plan.cap\" could have many different values for each combination of \"app_phon... | [
1
] | [] | [] | [
"django",
"orm",
"python",
"sql"
] | stackoverflow_0002755382_django_orm_python_sql.txt |
Q:
Import module stored in a cStringIO data structure vs. physical disk file
Is there a way to import a Python module stored in a cStringIO data structure vs. physical disk file?
It looks like "imp.load_compiled(name, pathname[, file])" is what I need, but the description of this method (and similar methods) has the ... | Import module stored in a cStringIO data structure vs. physical disk file | Is there a way to import a Python module stored in a cStringIO data structure vs. physical disk file?
It looks like "imp.load_compiled(name, pathname[, file])" is what I need, but the description of this method (and similar methods) has the following disclaimer:
Quote: "The file argument is the byte-compiled code file,... | [
"Something like this perhaps?\nimport types\nimport sys\n\nsrc = \"\"\"\ndef hello(who):\n print 'hello', who\n\"\"\"\n\ndef module_from_text(modulename, src):\n if modulename in sys.modules:\n module = sys.modules[modulename]\n else:\n module = sys.modules[modulename] = types.ModuleType(modu... | [
3
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0002761490_import_module_python.txt |
Q:
changing .emacs to use IronPython.exe and using code completion for IronPython modules?
I configured my Emacs for code completion and other help using this link (from another question here on SO). I am a complete newbie to emacs.
Can anyone tell me what should I change so it (rope, ropemacs, pymacs, yasnippet etc)... | changing .emacs to use IronPython.exe and using code completion for IronPython modules? | I configured my Emacs for code completion and other help using this link (from another question here on SO). I am a complete newbie to emacs.
Can anyone tell me what should I change so it (rope, ropemacs, pymacs, yasnippet etc) picks up symbols of IronPython modules for code completion and snippets.
Also I want to map... | [
"The variable python-command contains the path of the python interpreter to be run. By default, this is usually just set to \"python\", which runs the first python in your path.\nTry changing it to point directly to the IronPython exe file:\n(setq python-command \"C:/Program Files/IronPython 2.6/ipy.exe\")\n\n"
] | [
1
] | [] | [] | [
"cygwin",
"emacs",
"ironpython",
"python"
] | stackoverflow_0002752209_cygwin_emacs_ironpython_python.txt |
Q:
Set language code inside a view in django
How do I set the language code inside a view (in django)?
I'm sending a HttpResponse that contains a python-date.strftime("%A").
%A is the day (e.g. 'Monday'), but I want to get the day in Swedish instead of English.
A:
The documentation for locale suggests that fiddling... | Set language code inside a view in django | How do I set the language code inside a view (in django)?
I'm sending a HttpResponse that contains a python-date.strftime("%A").
%A is the day (e.g. 'Monday'), but I want to get the day in Swedish instead of English.
| [
"The documentation for locale suggests that fiddling with the locale too much is a bad idea:\n\nIt is generally a bad idea to call\n setlocale() in some library routine,\n since as a side effect it affects the\n entire program. Saving and restoring\n it is almost as bad: it is expensive\n and affects other th... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002760783_django_python.txt |
Q:
Splitting a filename into words and numbers in Python
The following code splits a string into a list of words but does not include numbers:
txt="there_once was,a-monkey.called phillip?09.txt"
sep=re.compile(r"[\s\.,-_\?]+")
sep.split(txt)
['there', 'once', 'was', 'a', 'monkey', 'called', 'phillip', 't... | Splitting a filename into words and numbers in Python | The following code splits a string into a list of words but does not include numbers:
txt="there_once was,a-monkey.called phillip?09.txt"
sep=re.compile(r"[\s\.,-_\?]+")
sep.split(txt)
['there', 'once', 'was', 'a', 'monkey', 'called', 'phillip', 'txt']
This code gives me words and numbers but still includ... | [
"Here's a quick way that should do it:\nre.findall(r\"[a-zA-Z0-9]+\",txt)\n\nHere's another:\nre.split(r\"[\\s\\.,\\-_\\?]+\",txt)\n\n(you just needed to escape the hyphen because it has a special meaning in a character class)\n",
"For the example case,\nsep = re.compile(r\"[^a-zA-Z0-9]+\")\nsea.split(txt)\n\nsho... | [
2,
2
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0002762292_python_regex_string.txt |
Q:
How should I check that a given argument is a datetime.date object?
I'm currently using an assert statement with isinstance. Because datetime is a subclass of date, I also need to check that it isn't an instance of datetime. Surely there's a better way?
from datetime import date, datetime
def some_func(arg):
... | How should I check that a given argument is a datetime.date object? | I'm currently using an assert statement with isinstance. Because datetime is a subclass of date, I also need to check that it isn't an instance of datetime. Surely there's a better way?
from datetime import date, datetime
def some_func(arg):
assert isinstance(arg, date) and not isinstance(arg, datetime),\
... | [
"I don't understand your motivation for rejecting instances of subclasses (given that by definition they support all the behavior the superclass supports!), but if that's really what you insist on doing, then:\nif type(arg) is not datetime.date:\n raise TypeError('arg must be a datetime.date, not a %s' % type(ar... | [
33,
5,
4
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0002762265_datetime_python.txt |
Q:
Installing Mercurial on Mac OS X 10.6 Snow Leopard
Installing Mercurial on Mac OS X 10.6 Snow Leopard
I installed Mercurial 1.3.1 on Mac OS X 10.6 Snow Leopard from source using the following:
cd ~/src
curl -O https://www.mercurial-scm.org/release/mercurial-1.3.1.tar.gz
tar -xzvf mercurial-1.3.1.tar.gz
cd mercuria... | Installing Mercurial on Mac OS X 10.6 Snow Leopard | Installing Mercurial on Mac OS X 10.6 Snow Leopard
I installed Mercurial 1.3.1 on Mac OS X 10.6 Snow Leopard from source using the following:
cd ~/src
curl -O https://www.mercurial-scm.org/release/mercurial-1.3.1.tar.gz
tar -xzvf mercurial-1.3.1.tar.gz
cd mercurial-1.3.1
make all
sudo make install
This installs the si... | [
"Why need to use macports? python easy_install is the easiest way and error free:\neasy_install -U mercurial\n\nIt's just a simple gold bullet, all the time.\n",
"Especially since you have Python 2.6 available you can do something like python setup.py install --user, which will install Mercurial with ~/.local as ... | [
13,
8,
8,
5,
1
] | [] | [] | [
"macos",
"mercurial",
"osx_snow_leopard",
"python"
] | stackoverflow_0001461374_macos_mercurial_osx_snow_leopard_python.txt |
Q:
how can i randomly print an element from a list in python
So far i have this, which prints out every word in my list, but i am trying to print only one word at random. Any suggestions?
def main():
# open a file
wordsf = open('words.txt', 'r')
word=random.choice('wordsf')
words_count=0
for line ... | how can i randomly print an element from a list in python | So far i have this, which prints out every word in my list, but i am trying to print only one word at random. Any suggestions?
def main():
# open a file
wordsf = open('words.txt', 'r')
word=random.choice('wordsf')
words_count=0
for line in wordsf:
word= line.rstrip('\n')
print(word)
... | [
"Try:\nprint random.choice([x.rstrip() for x in open(\"words.txt\")])\n\nNote that this strips the '\\n' from every line before choosing a random one; a better solution is left as an exercise for the reader.\n",
"To print one random word per line, your loop could be:\nfor line in wordsf:\n word = random.choice... | [
3,
1,
0
] | [] | [] | [
"file",
"python",
"random"
] | stackoverflow_0002762365_file_python_random.txt |
Q:
Access to module denied from within GAE dev server
I am developing an app for GAE.
Having installed the "feedparser" module with setuptools, I tried importing it (with "import feedparser") statement. However, the module does not load and when I look at the dev_appserver.py debug log on screen, I see the following:... | Access to module denied from within GAE dev server | I am developing an app for GAE.
Having installed the "feedparser" module with setuptools, I tried importing it (with "import feedparser") statement. However, the module does not load and when I look at the dev_appserver.py debug log on screen, I see the following:
Access to module file denied: /usr/local/lib/python2.6/... | [
"App Engine runs Python code in a sandbox, and only authorized standard library modules & packages can be imported from your application.\nas @mg has mentioned, if you want to allow for 3rd-party modules & packages, you need to bundle them with your application. to do that specifically for feedparser, just drop the... | [
6,
1
] | [] | [] | [
"django",
"google_app_engine",
"permissions",
"python"
] | stackoverflow_0002756790_django_google_app_engine_permissions_python.txt |
Q:
pyobj access to iTunes application
Let's say I managed to get the dictionary opened for iTunes in the Applescript editor:
How would I access the "search" commands using Python with pyobjc?
I know I get can hold of the iTunes application using:
iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTu... | pyobj access to iTunes application | Let's say I managed to get the dictionary opened for iTunes in the Applescript editor:
How would I access the "search" commands using Python with pyobjc?
I know I get can hold of the iTunes application using:
iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
but after I do a dir on it, I don'... | [
"Use appscript instead of Scripting Bridge. There are versions available for Python, Ruby and Objective-C. Unlike Scripting Bridge, appscript is designed to work with Apple Events rather than make it pretend to be something it isn't; it's also quite a bit more flexible and less buggy. As a bonus, you don't have ... | [
3
] | [] | [] | [
"applescript",
"itunes",
"macos",
"pyobjc",
"python"
] | stackoverflow_0002762358_applescript_itunes_macos_pyobjc_python.txt |
Q:
ImportError: No module named optparse in jython
getting
Traceback (most recent call last):
File "C:\projects\myproject\convert.py", line 139, in <module>
import optparse
ImportError: No module named optparse.
when executing it using jython. Same module works fine when i execute it through python.
I am usin... | ImportError: No module named optparse in jython | getting
Traceback (most recent call last):
File "C:\projects\myproject\convert.py", line 139, in <module>
import optparse
ImportError: No module named optparse.
when executing it using jython. Same module works fine when i execute it through python.
I am usinng window7 operating system. The same modle works fin... | [
"My guess is that you're using Jython 2.2, which, according to the FAQ:\n\nJython 2.2 does not implement any features added to CPython in version 2.3 or later.\n\nWhere optparse was added in Python 2.3.\nThe newest version of Jython is 2.5.1, so you'll probably want to go ahead and download it.\n"
] | [
1
] | [] | [] | [
"jython",
"python"
] | stackoverflow_0002762571_jython_python.txt |
Q:
Python: cleaner list comprehension
Is there a cleaner way to write this:
for w in [w for w in words if w != '']:
I want to loop over a dictionary words, but only words that != ''. Thanks!
A:
You don't need a listcomp here. Just write:
for w in words:
if w != '':
# ...
A:
Assuming that you are aft... | Python: cleaner list comprehension | Is there a cleaner way to write this:
for w in [w for w in words if w != '']:
I want to loop over a dictionary words, but only words that != ''. Thanks!
| [
"You don't need a listcomp here. Just write:\nfor w in words:\n if w != '':\n # ...\n\n",
"Assuming that you are after the keys, why not try:\n[w for w in words if w]\n\n",
"filter(lambda w: w != '', words) or filter(None, words)\nthis is suggestion, it may not be the best solution for your problem.\... | [
6,
2,
1,
1,
1,
0
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0002762623_list_comprehension_python.txt |
Q:
Retrieving my own data via FaceBook API
I am building a website for a comedy group which uses Facebook as one of their marketing platforms; one of the requirements for the new site is to display all of their Facebook events on a calendar.
Currently, I am just trying to put together a Python script which can pull s... | Retrieving my own data via FaceBook API | I am building a website for a comedy group which uses Facebook as one of their marketing platforms; one of the requirements for the new site is to display all of their Facebook events on a calendar.
Currently, I am just trying to put together a Python script which can pull some data from my own Facebook account, like a... | [
"Just posting up my notes on the successful advice, should others find this post;\nPer Daniel and William's advice, I obtained the right permissions using the Connect options. From William, this link explains how the Facebook connection works\nhttps://developers.facebook.com/docs/authentication/\nThis section on s... | [
7,
2,
0,
0
] | [] | [] | [
"facebook",
"python"
] | stackoverflow_0002756237_facebook_python.txt |
Q:
Python modules not updating after restarting the main module
I've recently come back to a project having had to stop for about 6 months, and after reinstalling my operating system and coming back to it I'm having all kinds of crazy things happen. I made sure to install the same version(2.6) of python that I was us... | Python modules not updating after restarting the main module | I've recently come back to a project having had to stop for about 6 months, and after reinstalling my operating system and coming back to it I'm having all kinds of crazy things happen. I made sure to install the same version(2.6) of python that I was using before.
It started by giving me strange tkinter error that I h... | [
"I've had something similar happen. The cause for my problems was that my source control software (hg) was setting the date of files to a date in the past. Because of this, python chose to use previously generated .pyc files which had newer timestamps.\nThe solution was to delete all the .pyc files before testing... | [
2,
0
] | [] | [] | [
"interface",
"python",
"tkinter"
] | stackoverflow_0002762883_interface_python_tkinter.txt |
Q:
Horizontal scrolling in a wx.RichTextCtrl
I have a RichTextCtrl created as follows:
self.userlist = wx.richtext.RichTextCtrl(self, style=wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL)
It all works fine, except for the wx.HSCROLL style. If I change the RichTextCtrl to a regular TextCtrl, it correctly horizontal scroll... | Horizontal scrolling in a wx.RichTextCtrl | I have a RichTextCtrl created as follows:
self.userlist = wx.richtext.RichTextCtrl(self, style=wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL)
It all works fine, except for the wx.HSCROLL style. If I change the RichTextCtrl to a regular TextCtrl, it correctly horizontal scrolls on long lines, rather than wrapping, but on t... | [
"sorry, I can't post this as a comment as I don't have the reputation, and I'm not sure this is an answer per se\nhttp://trac.wxwidgets.org/ticket/9382 it looks old, but I confirm the behaviour you are seeing. \nDoes setting the wx.TE_RICH or wx.TE_RICH2 on a regular TextCtrl give you the behaviour you need?\n",
... | [
0,
0
] | [] | [] | [
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0002759409_python_wxpython_wxwidgets.txt |
Q:
how to create http headers from scratch
So, I made a simple socket server using python. And now I'm trying to structure a proper http response. However, I can't seem to find any sort of tutorial or spec that discusses how to format http responses.
Could someone point me to the right place?
A:
RFC 2616.
A:
Yo... | how to create http headers from scratch | So, I made a simple socket server using python. And now I'm trying to structure a proper http response. However, I can't seem to find any sort of tutorial or spec that discusses how to format http responses.
Could someone point me to the right place?
| [
"RFC 2616.\n",
"You may want to check out the following article:\n\nHTTP Made Really Easy: A Practical Guide to Writing Clients and Servers\n\nThe section Sample HTTP Exchange could help you getting started. Quoting:\n\nThe server should respond with something like the following, sent back through the same socket... | [
3,
2,
2
] | [] | [] | [
"http",
"http_headers",
"python",
"sockets"
] | stackoverflow_0002763265_http_http_headers_python_sockets.txt |
Q:
Likelihood of IOError during print vs. write
I recently encountered an IOError writing to a file on NFS. There wasn't a disk space or permission issue, so I assume this was just a network hiccup. The obvious solution is to wrap the write in a try-except, but I was curious whether the implementation of print and wr... | Likelihood of IOError during print vs. write | I recently encountered an IOError writing to a file on NFS. There wasn't a disk space or permission issue, so I assume this was just a network hiccup. The obvious solution is to wrap the write in a try-except, but I was curious whether the implementation of print and write in Python make either of the following more or... | [
"prints are implemented in terms of writes which ultimately result in a write(2) call to the kernel. You could run strace on those two samples and (after wading through a lot of chaff) see the same resultant calls to write(2).\nIndeed, I just did that and omitting 2000+ lines of output yielded:\nexecve(\"/usr/bin/p... | [
1
] | [] | [] | [
"exception",
"file_io",
"python"
] | stackoverflow_0002763120_exception_file_io_python.txt |
Q:
How do I use Python to prevent a file from being copied?
I have a file that I need to "protect" so that it cannot be copied! I am using Python on Windows XP.
I think it may just be changing file permissions??
A:
You can prevent the file being copied only by removing read permission from the user that shouldn't b... | How do I use Python to prevent a file from being copied? | I have a file that I need to "protect" so that it cannot be copied! I am using Python on Windows XP.
I think it may just be changing file permissions??
| [
"You can prevent the file being copied only by removing read permission from the user that shouldn't be able to copy the file. You can use os.chmod for this, or see this page explaining to set permissions with the full Windows security model.\n",
"Is this a temporary or a permanent file? If it's temporary, take a... | [
2,
0
] | [] | [] | [
"copy",
"file",
"python",
"windows"
] | stackoverflow_0002763350_copy_file_python_windows.txt |
Q:
Python New-style Classes and the Super Function
This is not the result I expect to see:
class A(dict):
def __init__(self, *args, **kwargs):
self['args'] = args
self['kwargs'] = kwargs
class B(A):
def __init__(self, *args, **kwargs):
super(B, self).__init__(args, kwargs)
print 'Ins... | Python New-style Classes and the Super Function | This is not the result I expect to see:
class A(dict):
def __init__(self, *args, **kwargs):
self['args'] = args
self['kwargs'] = kwargs
class B(A):
def __init__(self, *args, **kwargs):
super(B, self).__init__(args, kwargs)
print 'Instance A:', A('monkey', banana=True)
#Instance A: {'ar... | [
"Try this instead:\nsuper(B, self).__init__(*args, **kwargs)\n\nSince the init function for A is expecting actual args/kwargs (and not just two arguments), you have to actually pass it the unpacked versions of args/kwargs so that they'll be repacked properly.\nOtherwise, the already-packed list of args and dict of ... | [
14,
2
] | [] | [] | [
"class",
"python"
] | stackoverflow_0002763335_class_python.txt |
Q:
Grid within a frame?
Is it possible to place a grid of buttons in Tkinter inside another frame?
I'm wanting to create a tic-tac-toe like game and want to use the grid feature to put gamesquares (that will be buttons). However, I'd like to have other stuff in the GUI other than just the game board so it's not idea... | Grid within a frame? | Is it possible to place a grid of buttons in Tkinter inside another frame?
I'm wanting to create a tic-tac-toe like game and want to use the grid feature to put gamesquares (that will be buttons). However, I'd like to have other stuff in the GUI other than just the game board so it's not ideal to just have everything ... | [
"Figured out a way to do it finally:\nfrom Tkinter import * \n\nroot = Tk()\n\nf = Frame(root, bg = \"orange\", width = 500, height = 500)\nf.pack(side=LEFT, expand = 1)\n\nf3 = Frame(f, bg = \"red\", width = 500)\nf3.pack(side=LEFT, expand = 1, pady = 50, padx = 50)\n\nf2 = Frame(root, bg = \"black\", height=100, ... | [
10,
1
] | [] | [] | [
"frame",
"grid",
"python",
"tkinter"
] | stackoverflow_0002763266_frame_grid_python_tkinter.txt |
Q:
I am using Python on Windows. How do I delete my script after it is run?
I have written a Python script and compiled it into a MS Windows EXE file. I can modify the code, but how do I make it remove itself after running?
A:
I think the easiest solution is make an external .bat file that executes your exe file an... | I am using Python on Windows. How do I delete my script after it is run? | I have written a Python script and compiled it into a MS Windows EXE file. I can modify the code, but how do I make it remove itself after running?
| [
"I think the easiest solution is make an external .bat file that executes your exe file and deletes it when finished.\n"
] | [
3
] | [] | [] | [
"python",
"scripting",
"windows"
] | stackoverflow_0002763541_python_scripting_windows.txt |
Q:
Python: How to write data in file in specific format?
i have an array called MAC1_Val:
MAC1_Val
array([ 1.00000000e+00, -1.00000000e+01, -2.06306600e+02,
2.22635749e+02, 1.00000000e+00, 1.00000000e+01,
1.00000000e+01, -2.06306600e+02, 2.22635749e+02,
0.... | Python: How to write data in file in specific format? | i have an array called MAC1_Val:
MAC1_Val
array([ 1.00000000e+00, -1.00000000e+01, -2.06306600e+02,
2.22635749e+02, 1.00000000e+00, 1.00000000e+01,
1.00000000e+01, -2.06306600e+02, 2.22635749e+02,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
... | [
"printf standard is your friend:\nfor i in MAC1_Val:\n print \"%.6e\" % i\n\n1.000000e+00\n-1.000000e+01\n-2.063066e+02\n2.226357e+02\n1.000000e+00\n1.000000e+01\n1.000000e+01\n\n",
"Use string interpolation to format the number.\n'%.3f' % (1.23456,)\n\n"
] | [
2,
1
] | [] | [] | [
"python",
"string_formatting"
] | stackoverflow_0002763784_python_string_formatting.txt |
Q:
Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?
Is it guaranteed that False == 0 and True == 1, in Python (assuming that they are not reassigned by the user)? For instance, is it in any way guaranteed that the following code will always produce the same results, whatever ... | Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language? | Is it guaranteed that False == 0 and True == 1, in Python (assuming that they are not reassigned by the user)? For instance, is it in any way guaranteed that the following code will always produce the same results, whatever the version of Python (both existing and, likely, future ones)?
0 == False # True
1 == True ... | [
"In Python 2.x this is not guaranteed as it is possible for True and False to be reassigned. However, even if this happens, boolean True and boolean False are still properly returned for comparisons.\nIn Python 3.x True and False are keywords and will always be equal to 1 and 0.\nUnder normal circumstances in Pyth... | [
228,
84,
23
] | [] | [] | [
"boolean",
"equality",
"language_specifications",
"python"
] | stackoverflow_0002764017_boolean_equality_language_specifications_python.txt |
Q:
Python fCGI + sqlAlchemy = malformed header from script. Bad header=FROM tags : index.py
I'm writing an Fast-CGI application that makes use of sqlAlchemy & MySQL for persistent data storage. I have no problem connecting to the DB and setting up ORM (so that tables get mapped to classes); I can even add data to ta... | Python fCGI + sqlAlchemy = malformed header from script. Bad header=FROM tags : index.py | I'm writing an Fast-CGI application that makes use of sqlAlchemy & MySQL for persistent data storage. I have no problem connecting to the DB and setting up ORM (so that tables get mapped to classes); I can even add data to tables (in memory).
But, as soon as I query the DB (and push any changes from memory to storag... | [
"Looks like SQLalchemy is pushing or echoing the query to your output (where fast-cgi) is instead looking for headers, then body. Maybe setting sqlalchemy.echo to False can help.\n",
"Instead of setting echo=True you can configure logging to output debugging information. SQLAlchemy has very flexible loggers hier... | [
2,
0
] | [] | [] | [
"apache",
"fastcgi",
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0002751957_apache_fastcgi_mysql_python_sqlalchemy.txt |
Q:
Python get raw_input but manually decide when string is done
I want someone to type words in the console, and autocomplete from a list when they hit "tab" key. However, raw_input won't return a string until someone hits [Enter].
How do I read characters into a variable until the user hits [Enter]?
*Note: I don't ... | Python get raw_input but manually decide when string is done | I want someone to type words in the console, and autocomplete from a list when they hit "tab" key. However, raw_input won't return a string until someone hits [Enter].
How do I read characters into a variable until the user hits [Enter]?
*Note: I don't want to use import readline for autocompletion because of OS issue... | [
"There is an official FAQ entry on this question, for Unix: http://www.python.org/doc/faq/library/#how-do-i-get-a-single-keypress-at-a-time\nEdit (copied from Donal Fellows' comment below): \"The problem is that the terminal is in “cooked” mode by default (allowing simple line editing) and that to get the keys as t... | [
5,
1
] | [] | [] | [
"console",
"python",
"user_input"
] | stackoverflow_0002764121_console_python_user_input.txt |
Q:
How do I read binary pickle data first, then unpickle it?
I'm unpickling a NetworkX object that's about 1GB in size on disk. Although I saved it in the binary format (using protocol 2), it is taking a very long time to unpickle this file---at least half an hour. The system I'm running on has plenty of system memor... | How do I read binary pickle data first, then unpickle it? | I'm unpickling a NetworkX object that's about 1GB in size on disk. Although I saved it in the binary format (using protocol 2), it is taking a very long time to unpickle this file---at least half an hour. The system I'm running on has plenty of system memory (128 GB), so that's not the bottleneck.
I've read here that p... | [
"pickle.load(file) expects a file-like object. Instead, use:\npickle.loads(string)\n\nRead a pickled object hierarchy from a string. Characters in the string past the pickled object’s representation are ignored.\n\n",
"The documentation mentions StringIO, which I think is one possible solution.\nTry:\nf = open(\"... | [
8,
1
] | [] | [] | [
"pickle",
"python",
"serialization"
] | stackoverflow_0002764237_pickle_python_serialization.txt |
Q:
How to decode javascript code within
I would like to implement a Python script which has the same functionality as http://www.greymagic.com/security/tools/decoder/
Is the encoding rule open for this type of javascript code encoding?
Thanks.
An example of this:
<Script LANGUAGE="JScript.Encode">#@~^TBQAAA==-mD~kk9... | How to decode javascript code within | I would like to implement a Python script which has the same functionality as http://www.greymagic.com/security/tools/decoder/
Is the encoding rule open for this type of javascript code encoding?
Thanks.
An example of this:
<Script LANGUAGE="JScript.Encode">#@~^TBQAAA==-mD~kk9P'8*R0%p\CD,wr[&fP{~xhPz..lH`EFTc+{W*v~Eq!W... | [
"No, its not open, its just broken. Google \"windows script decoder\" for examples.\n"
] | [
1
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0002764229_javascript_python.txt |
Q:
making urllib request in Python from the client side
I've written a Python application that makes web requests using the urllib2 library after which it scrapes the data. I could deploy this as a web application which means all urllib2 requests go through my web-server. This leads to the danger of the server's IP b... | making urllib request in Python from the client side | I've written a Python application that makes web requests using the urllib2 library after which it scrapes the data. I could deploy this as a web application which means all urllib2 requests go through my web-server. This leads to the danger of the server's IP being banned due to the high number of web requests for man... | [
"You probably can use AJAX requests made from JavaScript that is a part of client-side.\n\nUse server → client communication to give commands and necessary data to make a request\n…and use AJAX communication from client to 3rd party server then.\n\n",
"You can use a signed Java applet, they can use the Java secur... | [
1,
1,
0
] | [] | [] | [
"python",
"urllib",
"urllib2"
] | stackoverflow_0002763274_python_urllib_urllib2.txt |
Q:
Is there a neater way to get the first occurrence of something?
I have a list which contains a number of things:
lista = ['a', 'b', 'foo', 'c', 'd', 'e', 'bar']
I'd like to get the first item in the list that fulfils a predicate, say len(item) > 2. Is there a neater way to do it than itertools' dropwhile and next... | Is there a neater way to get the first occurrence of something? | I have a list which contains a number of things:
lista = ['a', 'b', 'foo', 'c', 'd', 'e', 'bar']
I'd like to get the first item in the list that fulfils a predicate, say len(item) > 2. Is there a neater way to do it than itertools' dropwhile and next?
first = next(itertools.dropwhile(lambda x: len(x) <= 2, lista))
I ... | [
">>> lista = ['a', 'b', 'foo', 'c', 'd', 'e', 'bar']\n>>> next(i for i in lista if len(i) > 2)\n'foo'\n\n"
] | [
6
] | [] | [] | [
"iterator",
"python",
"python_itertools"
] | stackoverflow_0002764328_iterator_python_python_itertools.txt |
Q:
How can I handle dynamic calculated attributes in a model in Django?
In Django I calculate the breadcrumb (a list of fathers) for an geographical object. Since it is not going to change very often, I am thinking of pre calculating it once the object is saved or initialized.
1.) What would be better? Which solution... | How can I handle dynamic calculated attributes in a model in Django? | In Django I calculate the breadcrumb (a list of fathers) for an geographical object. Since it is not going to change very often, I am thinking of pre calculating it once the object is saved or initialized.
1.) What would be better? Which solution would have a better performance? To calculate it at ____init____ or to ca... | [
"By calling both the _breadcrumb method with x.father and assigning x = x.father in the beginning of the while loop you jump over one father. Try exchanging \nself.crumb = self._breadcrumb(father) \n\nwith\nself.crumb = self._breadcrumb(self)\n\nBy defining _breadcrumb within the model class you can clean it up lik... | [
0
] | [] | [] | [
"django",
"django_models",
"django_signals",
"oop",
"python"
] | stackoverflow_0002763623_django_django_models_django_signals_oop_python.txt |
Q:
Not enough arguments for format string
I have such code in Python:
def send_start(self, player):
for p in self.players:
player["socket"].send_cmd('<player id="%s" name="%s" you="%s" avatar="*.png" bank="%s" />'%(self.players.index(p)+1, p['name'], int(player["pid"]==p["pid"]), 0))
player["socket"].... | Not enough arguments for format string | I have such code in Python:
def send_start(self, player):
for p in self.players:
player["socket"].send_cmd('<player id="%s" name="%s" you="%s" avatar="*.png" bank="%s" />'%(self.players.index(p)+1, p['name'], int(player["pid"]==p["pid"]), 0))
player["socket"].send_cmd('<game playerid="%s" />'%(self.turn... | [
"Your code would fail if self.turnnow is an empty tuple:\n>>> var = ()\n>>> print \"%s\" % (var)\nTraceback (most recent call last):\n File \"<stdin>\", line 2, in <module>\nTypeError: not enough arguments for format string\n>>> print \"%s\" % (var,)\n()\n\nThis is because a parenthesized expression in Python does... | [
18,
4
] | [] | [] | [
"format",
"python"
] | stackoverflow_0002764520_format_python.txt |
Q:
how to traverse a file in python and c++ in backward way? And also store data in backward (bottom to top) way?
Suppose i want to store 3 lines in a file both in python and C++ .
I want to store it like this
aaa
bbb
ccc ..
But i am giving ccc input first then bbb then aaa. How will I traverse the file from bott... | how to traverse a file in python and c++ in backward way? And also store data in backward (bottom to top) way? | Suppose i want to store 3 lines in a file both in python and C++ .
I want to store it like this
aaa
bbb
ccc ..
But i am giving ccc input first then bbb then aaa. How will I traverse the file from bottom to top and also store from bottom to top/?
| [
"It isn't obvious from the title and question whether you want to store to a file, load from a file, or both, so I'll cover both cases:\nReading\nIf it's OK to load it all into memory at once (in Python):\nlist(reversed(list(open('foo.txt'))))\n\nOtherwise, it gets a lot more difficult. Processing a file backwards ... | [
3,
1,
0
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0002764607_c++_python.txt |
Q:
what is the correct way to close a socket in python 2.6?
i have a simple server/client. and i am using the netcat as the client to test the server. if i stop the server before the client exit, i will not be able to start the server again for a while and i go this error:
"
[Errno 98] Address already in use
"
but if... | what is the correct way to close a socket in python 2.6? | i have a simple server/client. and i am using the netcat as the client to test the server. if i stop the server before the client exit, i will not be able to start the server again for a while and i go this error:
"
[Errno 98] Address already in use
"
but if i close the client first, then the server stops, i will not h... | [
"You're closing the socket just fine. However, the socket continues to use resources for a few minutes after the socket closes, so that if the remote end missed a packet the packet can be re-sent.\nYou should be able to work around it by calling the following before you call bind:\ns.setsockopt(socket.SOL_SOCKET, ... | [
9
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0002765152_python_sockets.txt |
Q:
Add windows commands in python
Can anyone tell me how to add the shutdown.exe to python and how . i also want to set and variables like shutdown.exe -f -s -t 60
A:
The subprocess module allows you to run external programs from inside python. In particular subprocess.call is a really convenient way to run program... | Add windows commands in python | Can anyone tell me how to add the shutdown.exe to python and how . i also want to set and variables like shutdown.exe -f -s -t 60
| [
"The subprocess module allows you to run external programs from inside python. In particular subprocess.call is a really convenient way to run programs where you don't care about anything other than the return code:\nimport subprocess\nsubprocess.call([\"shutdown.exe\", \"-f\", \"-s\", \"-t\", \"60\"])\n\nUpdate:\n... | [
8
] | [] | [] | [
"python",
"shutdown"
] | stackoverflow_0002765405_python_shutdown.txt |
Q:
google app engine db.Model in python only display user-defined fields
I'm a python newbie so I apologize in advance if this question has been asked before.
I am building out an application in GAE and need to generate a report that contains the values for a user-defined subset of fields.
For example, in my db model... | google app engine db.Model in python only display user-defined fields | I'm a python newbie so I apologize in advance if this question has been asked before.
I am building out an application in GAE and need to generate a report that contains the values for a user-defined subset of fields.
For example, in my db model, CrashReport, I have the following fields:
entry_type
entry_date
instance... | [
"Given a model instance mi and an attribute name an, getattr(mi, an) will fetch the value of attribute an for object mi. It will raise AttributeError if object mi has no attribute by that name; if you want to avoid this, try e.g. getattr(mi, an, None).\nSo if you have a list of attribute names la,\n[getattr(mi, x,... | [
2
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0002765955_google_app_engine_google_cloud_datastore_python.txt |
Q:
error in writing data into file in python
a='aa'
>>> f=open("key.txt","w")
>>> s=str(a)
>>> f.write(s)
and still the key.txt file remains blank .. why?
A:
Use
f.flush()
to flush the write to disk. Or, if you are done using f, you could use
f.close()
to flush and close the file.
A:
This issue can be avoi... | error in writing data into file in python | a='aa'
>>> f=open("key.txt","w")
>>> s=str(a)
>>> f.write(s)
and still the key.txt file remains blank .. why?
| [
"Use \nf.flush()\n\nto flush the write to disk. Or, if you are done using f, you could use\nf.close()\n\nto flush and close the file.\n",
"This issue can be avoided completely by making use of the with statement:\nwith open(\"key.txt\",\"w\") as f:\n s=str(a)\n f.write(s)\n\nThe file will be automatically c... | [
10,
2
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0002765617_file_io_python.txt |
Q:
Possible to use pyplot without DISPLAY?
I'm working remotely on a machine that's pretty restrictive. I can't install any software, and it won't accept my X11 session, so I have no display. The machine currently has pylab installed, and I'd like to use it to plot something and then save it for viewing on another co... | Possible to use pyplot without DISPLAY? | I'm working remotely on a machine that's pretty restrictive. I can't install any software, and it won't accept my X11 session, so I have no display. The machine currently has pylab installed, and I'd like to use it to plot something and then save it for viewing on another computer. However, it seems there's no way to e... | [
"Use another backend, for example Agg or SVG:\nimport matplotlib\nmatplotlib.use('Agg')\n...\nmatplotlib.savefig('out.png')\n\n"
] | [
25
] | [
"Yes, after creating the plots etc., instead of calling\npylab.show()\n\ncall\npylab.savefig('filename.XXX')\n\nwhere XXX is one of the common image extensions (png, jpg...)\n"
] | [
-1
] | [
"matplotlib",
"python",
"x11"
] | stackoverflow_0002766149_matplotlib_python_x11.txt |
Q:
I need to authenticate against one db with python and openfire. How do I do this?
How would one go about authenticating against a single db using Python and openfire? Is there a simple module that will do this?
A:
Openfire uses a SQL database. So talking to the database from python is probably the easiest way.
... | I need to authenticate against one db with python and openfire. How do I do this? | How would one go about authenticating against a single db using Python and openfire? Is there a simple module that will do this?
| [
"Openfire uses a SQL database. So talking to the database from python is probably the easiest way.\nYou could also try to connect/authenticate via XMPP - there's probably an xmpp library for python somewhere.\n"
] | [
0
] | [] | [] | [
"database",
"openfire",
"python"
] | stackoverflow_0002752047_database_openfire_python.txt |
Q:
Pass in a value into Python Class through command line
I have got some code to pass in a variable into a script from the command line. I can pass any value into function for the var arg. The problem is that when I put function into a class the variable doesn't get read into function. The script is:
import sys, os
... | Pass in a value into Python Class through command line | I have got some code to pass in a variable into a script from the command line. I can pass any value into function for the var arg. The problem is that when I put function into a class the variable doesn't get read into function. The script is:
import sys, os
def function(var):
print var
class function_call(objec... | [
"you might find getattr useful:\n>>> argv = ['function.py', 'run', 'Hello']\n>>> class A:\n def run(self, *args):\n print(*args)\n\n\n>>> getattr(A(), argv[1])(*argv[2:])\nHello\n\n",
"It sounds like rather than:\nself.function = self.module.__dict__[self.functionName]\n\nyou want to do something like (... | [
4,
1
] | [] | [] | [
"class",
"command_line_arguments",
"python"
] | stackoverflow_0002765664_class_command_line_arguments_python.txt |
Q:
Google App Engine (GAE) cron url: url?keyword=abc
I would like to run cron job on GAE and using python
In the cron.yaml, how do i insert the "url" field if consist of some "get" info
The:
description: whatever
url: url?keyword=a
schedule: every day 15:00
give me error when deploy
A:
I have tried the following ... | Google App Engine (GAE) cron url: url?keyword=abc | I would like to run cron job on GAE and using python
In the cron.yaml, how do i insert the "url" field if consist of some "get" info
The:
description: whatever
url: url?keyword=a
schedule: every day 15:00
give me error when deploy
| [
"I have tried the following cron.yaml and it worked fine. At least on the dev_appserver:\ncron:\n- description: url test\n url: /tasks?keyword=test\n schedule: every day 15:00\n\n"
] | [
1
] | [] | [] | [
"cron",
"google_app_engine",
"python"
] | stackoverflow_0002763960_cron_google_app_engine_python.txt |
Q:
Jythonc missing
I just installed Jython 2.5.1. I want to convert my Python file into Java class file and it is instructed on the website to use the jythonc command-line tool but I can't find it. Does anyone know where I could find it?
Basically what i was trying to accomplish is to get my Python code running clien... | Jythonc missing | I just installed Jython 2.5.1. I want to convert my Python file into Java class file and it is instructed on the website to use the jythonc command-line tool but I can't find it. Does anyone know where I could find it?
Basically what i was trying to accomplish is to get my Python code running client-side in a browser a... | [
"You can still compile your python-code to class-files:\nimport compileall; \ncompileall.compile_dir('Lib'); # to compile yor Lib-Dir \n\nshould work with 2.5 jython\ni use it to create class-files to put in jars :-)\n",
"Jythonc was removed in Jython 2.2 and is no longer supported. The official way to embed Jyt... | [
26,
9
] | [] | [] | [
"jython",
"python"
] | stackoverflow_0002763129_jython_python.txt |
Q:
How to pass a variable from a function to a class python
I am trying to pass a variable from a function to a class. Example code is below:
def hello(var):
return var
class test():
def __init__(self):
pass
def value(self):
print var
hello(var)
test = test()
test.value()
I would like... | How to pass a variable from a function to a class python | I am trying to pass a variable from a function to a class. Example code is below:
def hello(var):
return var
class test():
def __init__(self):
pass
def value(self):
print var
hello(var)
test = test()
test.value()
I would like to pass var into the class test().
Thanks for any help.
| [
"You need to modify your class like this:\nclass test():\n def __init__(self, var):\n self.var = var\n\n def value(self):\n print self.var\n\ntest_inst = test(var)\ntest_inst.value()\n\nAlso, you cannot use the same exact name to refer to both class instance and a class itself.\n",
"class test... | [
7,
0,
0,
0
] | [] | [] | [
"class",
"python"
] | stackoverflow_0002766239_class_python.txt |
Q:
is a there md5 decrypt function in python?
Possible Duplicate:
Is it possible to decrypt md5 hashes?
i used md5.new(); md5.update("aaa"), md5.digest()
to form a md5 hash of the data "aaa" . How to get back the data using python?
A:
You cannot decode an md5 hash, as hashing is a process that is best thought of ... | is a there md5 decrypt function in python? |
Possible Duplicate:
Is it possible to decrypt md5 hashes?
i used md5.new(); md5.update("aaa"), md5.digest()
to form a md5 hash of the data "aaa" . How to get back the data using python?
| [
"You cannot decode an md5 hash, as hashing is a process that is best thought of as one-way encoding (that is to say what is hashed cannot be de-hashed; one can only determine what was hashed, either by examining a list of known hashes, or by hashing a set of inputs and matching the resulting hashes with the hash yo... | [
22,
14,
3,
3,
1,
0,
0
] | [] | [] | [
"md5",
"python"
] | stackoverflow_0002760911_md5_python.txt |
Q:
Template strings python 2.5 error
#!/usr/bin/python
from string import Template
s = Template('$x, go home $x')
s.substitute(x='lee')
print s
error i get is
<string.Template object at 0x81abdcc>
desired results i am looking for is : lee, go home lee
A:
You need to look at the return value of substitute. I... | Template strings python 2.5 error | #!/usr/bin/python
from string import Template
s = Template('$x, go home $x')
s.substitute(x='lee')
print s
error i get is
<string.Template object at 0x81abdcc>
desired results i am looking for is : lee, go home lee
| [
"You need to look at the return value of substitute. It gives you the string with substitutions performed.\nprint s.substitute(x='lee')\n\nThe template object itself (s) is not changed. This gives you the ability to perform multiple substitutions with the same template object.\n",
"You're not getting an error: y... | [
7,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0002766872_python.txt |
Q:
When to use "property" builtin: auxiliary functions and generators
I recently discovered Python's property built-in, which disguises class method getters and setters as a class's property. I'm now being tempted to use it in ways that I'm pretty sure are inappropriate.
Using the property keyword is clearly the righ... | When to use "property" builtin: auxiliary functions and generators | I recently discovered Python's property built-in, which disguises class method getters and setters as a class's property. I'm now being tempted to use it in ways that I'm pretty sure are inappropriate.
Using the property keyword is clearly the right thing to do if class A has a property _x whose allowable values you wa... | [
"\nWhen you have a normal attribute and getting and/or setting it makes sense for a class's user, expose the attribute directly. One big reason that public members are anathema in some languages is that if you need to do something more complex later you would need an API change; in Python you can just define a prop... | [
16,
3
] | [] | [] | [
"properties",
"python"
] | stackoverflow_0002766601_properties_python.txt |
Q:
giving garbage value while trying to store a md5 hash in a file in python
m=md5.new()
a=10111011
>>> m.update(str(a))
>>> k=m.digest()
>>> k
'\xec\x9d1\x89e\x08\xa1\xc2Y\xf6\xbf6\xfe\xe4\xe2M'
>>> f.write(str(k))
>>> f.flush()
the file f is filled with garbage value which i cant use to read again for further use... | giving garbage value while trying to store a md5 hash in a file in python | m=md5.new()
a=10111011
>>> m.update(str(a))
>>> k=m.digest()
>>> k
'\xec\x9d1\x89e\x08\xa1\xc2Y\xf6\xbf6\xfe\xe4\xe2M'
>>> f.write(str(k))
>>> f.flush()
the file f is filled with garbage value which i cant use to read again for further use of the hash . Why does it give the garbage value when on the python terminal i... | [
"If you want further clues where your \"garbage\" (your digest!) is coming from, try print k versus print repr(k)!\nYou have a raw byte string. I think you want to insert a hexdigest instead? Either use k = m.hexdigest() or k = repr(m.digest()) and write that to your file.\nBasically, you can choose your representa... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0002766961_python.txt |
Q:
Implicitly invoking parent class initializer
class A(object):
def __init__(self, a, b, c):
#super(A, self).__init__()
super(self.__class__, self).__init__()
class B(A):
def __init__(self, b, c):
print super(B, self)
print super(self.__class__, self)
#super(B, self).... | Implicitly invoking parent class initializer | class A(object):
def __init__(self, a, b, c):
#super(A, self).__init__()
super(self.__class__, self).__init__()
class B(A):
def __init__(self, b, c):
print super(B, self)
print super(self.__class__, self)
#super(B, self).__init__(1, b, c)
super(self.__class__, s... | [
"Short answer: no, there's no way to implicitly invoke the right __init__ with the right arguments of the right parent class in Python 2.x.\nIncidentally, the code as shown here is incorrect: if you use super().__init__, then all classes in your hierarchy must have the same signature in their __init__ methods. Oth... | [
3,
1,
1,
0
] | [] | [] | [
"constructor",
"method_resolution_order",
"python",
"python_2.x",
"super"
] | stackoverflow_0002354769_constructor_method_resolution_order_python_python_2.x_super.txt |
Q:
When deploying python, what web server options do we have? is the process inefficient at all?
I think in the past python scripts would run off CGI, which would create a new thread for each process.
I am a newbie so I'm not really sure, what options do we have?
Is the web server pipeline that python works under any... | When deploying python, what web server options do we have? is the process inefficient at all? | I think in the past python scripts would run off CGI, which would create a new thread for each process.
I am a newbie so I'm not really sure, what options do we have?
Is the web server pipeline that python works under any more/less effecient than say php?
| [
"You can still use CGI if you want, but the normal approach these days is using WSGI on the Python side, e.g. through mod_wsgi on Apache or via bridges to FastCGI on other web servers. At least with mod_wsgi, I know of no inefficiencies with this approach.\nBTW, your description of CGI (\"create a new thread for e... | [
6,
2,
1
] | [] | [] | [
"python",
"webserver"
] | stackoverflow_0002767013_python_webserver.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.