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:
Query on Table View - Model/View programming
I'm practicing some examples on model-view programming and have a query why the colors are not correctly represented.
The code is as follows:
I have created a Table View
table_view = QTableView()
table_view.show()
table_view.setModel(model)
test_data = data(4,5)
model... | Query on Table View - Model/View programming | I'm practicing some examples on model-view programming and have a query why the colors are not correctly represented.
The code is as follows:
I have created a Table View
table_view = QTableView()
table_view.show()
table_view.setModel(model)
test_data = data(4,5)
model = paletteTableview(test_data)
class paletteTable... | [
"I test your code and there is no problem but the colors is nearly the same on my display. I think you may meet the same problem, which seems all the color is red without any clear difference. I suggest to use another way to generate the color data ( return by \"data\" function ).\nI give my whole test code, you ca... | [
1
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"tableview"
] | stackoverflow_0005321219_pyqt_pyqt4_python_tableview.txt |
Q:
how to access python object in javascript function?
that means now i am working on python with cherryypy and genshi framework with help of this i send python variable to html file using genshi but i want to access variable that variable in javascript function so how can i do?..
html file is:
<!DOCTYPE html>
<html ... | how to access python object in javascript function? | that means now i am working on python with cherryypy and genshi framework with help of this i send python variable to html file using genshi but i want to access variable that variable in javascript function so how can i do?..
html file is:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:xi="http... | [
"The proper way to pass values from python to javascript is - especially if they can contain more than just plain numbers or a very restricted charset (basically [a-zA-Z0-9] and non-quoting symbols) - running the value through a json encoder (json.dumps(...)) to ensure they do not break anything.\n"
] | [
1
] | [] | [] | [
"cherrypy",
"genshi",
"javascript",
"python"
] | stackoverflow_0005322239_cherrypy_genshi_javascript_python.txt |
Q:
Python Database Error
When I put my database file (which is a .sdb) into a directory and try to access it from that directory, I receive an error. The error reads "unable to open database file". For example, let's say my .sdb file is in the "data" directory and I use the command "con = lite.connect('data\noktalar.... | Python Database Error | When I put my database file (which is a .sdb) into a directory and try to access it from that directory, I receive an error. The error reads "unable to open database file". For example, let's say my .sdb file is in the "data" directory and I use the command "con = lite.connect('data\noktalar.sdb')", this error occurs. ... | [
"Where is your python process running from? Try to point to the absolute path of the file. And when pointing to path use raw string r'c:\\\\mypath\\data\\notktalar.sub'\n",
"\\ is the escape character in python strings. You have to use double backslashes:\ncon = lite.connect('data\\\\noktalar.sdb')\n\nOr like Sen... | [
1,
1
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0005321699_python_sqlite.txt |
Q:
fabric.api.run converts stderr to stdout for SSH
I run compilation on serve using fabric, server is Linux and client is Windows, channel is SSH.
On server 'scons' prints compilation errors to stderr. It is okay.
But fabric.api.run('scons') executed from client prints compilation errors to STDOUT. It is not good a... | fabric.api.run converts stderr to stdout for SSH | I run compilation on serve using fabric, server is Linux and client is Windows, channel is SSH.
On server 'scons' prints compilation errors to stderr. It is okay.
But fabric.api.run('scons') executed from client prints compilation errors to STDOUT. It is not good and because of this my IDE fails to detect them.
| [
"You could use combine_stderr=False (at least in 1.0).\nSee also: \n\nhttp://docs.fabfile.org/en/1.0.0/api/core/operations.html#fabric.operations.run\nhttp://docs.fabfile.org/en/1.0.0/usage/interactivity.html#combining-stdout-and-stderr\n\n",
"By default, fabric.api.run combines stdout and stderr to the same stre... | [
1,
0
] | [] | [] | [
"fabric",
"python",
"ssh"
] | stackoverflow_0005322416_fabric_python_ssh.txt |
Q:
Can I use google app engine to run the python program in the background for chrome extension?
I have a python program which has to execute when i click on the chrome extension.Can I use the Google app engine to do the same??
A:
What kind of program is to be executed? You could very well send a request from Chrom... | Can I use google app engine to run the python program in the background for chrome extension? | I have a python program which has to execute when i click on the chrome extension.Can I use the Google app engine to do the same??
| [
"What kind of program is to be executed? You could very well send a request from Chrome extension to your appengine server, process and return the response.\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"google_chrome",
"python"
] | stackoverflow_0005321079_google_app_engine_google_chrome_python.txt |
Q:
how to detect quickly if a string is zlib compressed?
What's the quickest way in python to determine if a string was compressed by zlib. I am using this currently.
def iscompressed(data):
result = True
try:
s =zlib.decompress(data)
except:
result = False
return result
I am sure t... | how to detect quickly if a string is zlib compressed? | What's the quickest way in python to determine if a string was compressed by zlib. I am using this currently.
def iscompressed(data):
result = True
try:
s =zlib.decompress(data)
except:
result = False
return result
I am sure there is a more elegant way.
| [
"You can check the first 2 Byte for the header information - it is, however, not 100% safe.\nSee http://www.faqs.org/rfcs/rfc1950.html, chapter 2.2\n",
"While the only way to be 100% sure is to actually try to decompress it, you can make a reasonable guess by looking for the zlib compression method + flags heade... | [
11,
3
] | [] | [] | [
"python",
"zlib"
] | stackoverflow_0005322860_python_zlib.txt |
Q:
to_python() never gets called (even in case of __metaclass__ = models.SubfieldBase)
Some time ago, as part of the process of learning Python+Django, I decided to write a custom MySQL-specific model field for the BIT column type. Unfortunately, I've ran into a problem.
The project: contains a single "main" app
The ... | to_python() never gets called (even in case of __metaclass__ = models.SubfieldBase) | Some time ago, as part of the process of learning Python+Django, I decided to write a custom MySQL-specific model field for the BIT column type. Unfortunately, I've ran into a problem.
The project: contains a single "main" app
The "main" app: contains all of the standard files created by "python manage.py startapp", pl... | [
"You don't need to do anything special in the QuerySet to support a custom field. You currently defer() your field and then add a raw extra(select=) attribute that coincidentally has the same name as your field. \nIf you just remove the custom manager (or the .defer().extra() calls) you should be fine.\n"
] | [
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0005318837_django_django_models_python.txt |
Q:
mapping in SD in python
Hi I want to map the sd keys and values from the result of two different query. to make it more clear i have written code.
rv = plpy.execute(select id from ABC);
if this returns 1, 2, 3
rv = plpy.execute(select name from XYZ);
if this returns A,B,C
Now I need a way where I can map these ... | mapping in SD in python | Hi I want to map the sd keys and values from the result of two different query. to make it more clear i have written code.
rv = plpy.execute(select id from ABC);
if this returns 1, 2, 3
rv = plpy.execute(select name from XYZ);
if this returns A,B,C
Now I need a way where I can map these two ids, so that id retrieved... | [
"I'm unfamiliar with plpy, so maybe I'm totally off. But if what you want to do is to create a python dictionary with key:value-pairs based on results from two queries this is my suggestion:\nIf these are your queries:\na = [a, b, c]\nb = [1, 2, 3] \n\nThen:\ndict(zip(a, b))\n\nGives you a dictionary like this:\n{'... | [
2
] | [] | [] | [
"plpy",
"plpython",
"postgresql",
"python"
] | stackoverflow_0005322767_plpy_plpython_postgresql_python.txt |
Q:
How to do paging/pagination in Django for 3rd party REST services
To use flickr as an example, a request URL looks something like this:
'http://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos&api_key=' + settings.FLICKR_API_KEY + '&user_id=' + userid + '&format=json&per_page' + per_page + '&pag... | How to do paging/pagination in Django for 3rd party REST services | To use flickr as an example, a request URL looks something like this:
'http://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos&api_key=' + settings.FLICKR_API_KEY + '&user_id=' + userid + '&format=json&per_page' + per_page + '&page=' + page + '&nojsoncallback=1'
where page controls which page to dis... | [
"Django-pagination will work with any list of objects -- not just calls from the database. The example here actually starts off with an example that has nothing to do with local models or databases.\nFor an API-type call, you'd just need to read your objects into a list, and then create a new Paginator objects bas... | [
3,
0
] | [] | [] | [
"api",
"django",
"pagination",
"python",
"rest"
] | stackoverflow_0005323110_api_django_pagination_python_rest.txt |
Q:
Python ElementTree duplicate checker
So I have to write a "duplicate checker" to compare two XMLs and see if they are the same (contain the same data). Now because they come from the same class and are generated form an XSD the structure the order of the elements inside will most likely be the same.
The best way I... | Python ElementTree duplicate checker | So I have to write a "duplicate checker" to compare two XMLs and see if they are the same (contain the same data). Now because they come from the same class and are generated form an XSD the structure the order of the elements inside will most likely be the same.
The best way I can think of doing the duplicate check is... | [
"OK, so I had to make a decision and went with this:\nforeach path in xpathlist\n find entries for path for both xml1 and xml2\n foreach entry in xmlentries1\n dict1[path#entry.value]++\n foreach entry in xmlentries2\n dict2[path#entry.value]++\n\n if dict1 and dict2 are not equal\n return false\nretur... | [
1,
0,
0,
0
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0005300649_elementtree_python_xml.txt |
Q:
Occasional 500 error
We use Apache+mod_wsgi to host our Django application.
Apache:
WSGIScriptAlias / /home/rls/django_wsgi.py
django_wsgi.py:
import os, sys
sys.path.append('data/misc/django')
os.environ['DJANGO_SETTINGS_MODULE'] = 'rls.settings'
import django.core.handlers.wsgi
application = django.core.handle... | Occasional 500 error | We use Apache+mod_wsgi to host our Django application.
Apache:
WSGIScriptAlias / /home/rls/django_wsgi.py
django_wsgi.py:
import os, sys
sys.path.append('data/misc/django')
os.environ['DJANGO_SETTINGS_MODULE'] = 'rls.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
Eve... | [
"Try to set the absolute path to the directory that contains the file settings.py.\nIn your case should be something like:\nsys.path.append('/%s/data/misc/django'%ROOT_2_DATA)\n\nYou must also check that apache group has permissions to read/write the folder.\n"
] | [
2
] | [] | [] | [
"django_wsgi",
"mod_wsgi",
"python"
] | stackoverflow_0005170294_django_wsgi_mod_wsgi_python.txt |
Q:
get MSWord paragraph number via COM
I process MSWord document with Python
for paragraph in MSWord.Documents[0].ListParagraphs:
print(paragraph.ID+' '+paragraph.Range.Text.replace('\u206d','?')+'\n\n')
I Don't find how get MSWord paragraph number in API documentation
cf. http://msdn.microsoft.com/en-us/library... | get MSWord paragraph number via COM | I process MSWord document with Python
for paragraph in MSWord.Documents[0].ListParagraphs:
print(paragraph.ID+' '+paragraph.Range.Text.replace('\u206d','?')+'\n\n')
I Don't find how get MSWord paragraph number in API documentation
cf. http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.paragraph_... | [
"Here you can find a VBA macro that finds the paragraph number, you could call it via COM\n",
"You could try:\nprint paragraph.Range.ListFormat.ListString\n\n"
] | [
0,
0
] | [] | [] | [
"com",
"ms_word",
"python"
] | stackoverflow_0005313519_com_ms_word_python.txt |
Q:
Django-piston: Difference between returning a queryset and a list?
I created this simple project to illustrate my problem.
These are my models:
class Zoo(models.Model):
name = models.CharField(max_length=30)
class Animal(models.Model):
name = models.CharField(max_length=30)
zoo = models.ForeignKey(... | Django-piston: Difference between returning a queryset and a list? | I created this simple project to illustrate my problem.
These are my models:
class Zoo(models.Model):
name = models.CharField(max_length=30)
class Animal(models.Model):
name = models.CharField(max_length=30)
zoo = models.ForeignKey(Zoo)
def speak(zelf):
return 'woof woof'
This is my base h... | [
"Because you are not actually serializing Zoo objects, but Animal objects. Piston sees that you have a queryset of Animals, and tries to find an Animal handler - not finding one, it just serializes all the built-in objects, but not the custom method.\nDefine an AnimalHandler class and move the fields tuple to there... | [
2
] | [] | [] | [
"django",
"django_piston",
"python"
] | stackoverflow_0005323749_django_django_piston_python.txt |
Q:
Is this a Python closure? (or, why does this code work?)
I am wondering why the following Python code works:
def sum(a, b):
return a+b+c
c=3
print sum(1,2)
# result: 6
I would have expected an compiling error.
How can the sum function already be defined when variable c is not (I would say that c is not in sco... | Is this a Python closure? (or, why does this code work?) | I am wondering why the following Python code works:
def sum(a, b):
return a+b+c
c=3
print sum(1,2)
# result: 6
I would have expected an compiling error.
How can the sum function already be defined when variable c is not (I would say that c is not in scope of the sum function) ?
Is this what they call a closure?
As... | [
"In this case, c is found in the globals table. If you try to call sum(1,2) and c cannot be found in the function's scope, or it's parent scope (the global scope), then you will get a NameError exception.\nWhilst this is similar to a closure, accessing global variables inside a function body is generally frowned up... | [
6,
4,
3
] | [] | [] | [
"closures",
"python"
] | stackoverflow_0005324093_closures_python.txt |
Q:
Regex: How to match sequence of key-value pairs at end of string
I am trying to match key-value pairs that appear at the end of (long) strings. The strings look like (I replaced the "\n")
my_str = "lots of blah
key1: val1-words
key2: val2-words
key3: val3-words"
so I expect matches "... | Regex: How to match sequence of key-value pairs at end of string | I am trying to match key-value pairs that appear at the end of (long) strings. The strings look like (I replaced the "\n")
my_str = "lots of blah
key1: val1-words
key2: val2-words
key3: val3-words"
so I expect matches "key1: val1-words", "key2: val2-words" and "key3: val3-words".
The set... | [
"The negative zero-width lookahead is (?!pattern).\nIt's mentioned part-way down the re module documentation page.\n(?!...)\n\nMatches if ... doesn’t match next. This is a negative lookahead assertion. For example, Isaac (?!Asimov) will match 'Isaac ' only if it’s not followed by 'Asimov'.\n\nSo you could use it to... | [
12
] | [] | [] | [
"key_value",
"python",
"regex"
] | stackoverflow_0005323703_key_value_python_regex.txt |
Q:
What's the closest thing to SLIME for python ? / What's the best way to use python from EMACS?
I'm trying to write some python, and I'm used to the lispy way of doing things, a REPL in EMACS and the ability to send arbitrary code snippets to the REPL. I like this way of developing code, and python's built-in IDLE ... | What's the closest thing to SLIME for python ? / What's the best way to use python from EMACS? | I'm trying to write some python, and I'm used to the lispy way of doing things, a REPL in EMACS and the ability to send arbitrary code snippets to the REPL. I like this way of developing code, and python's built-in IDLE seems to do it pretty well. However I do like EMACS as an editor.
What's the best thing analogous to... | [
"There is ipython.el which you can use for some extended functionality over the vanilla python-mode. Ropemacs provides a few extra completion and refactoring related options that might help you. This is discussed here. However, I don't expect you're going to get anything close to SLIME.\n",
"I think the new pytho... | [
5,
4,
3
] | [] | [] | [
"emacs",
"python",
"slime"
] | stackoverflow_0005316175_emacs_python_slime.txt |
Q:
How to erase everything from the tkinter text widget?
Im working on a GUI for some chat programme. For user's input I have Text() widget, messages are sent via "Return" and after that I clean the Text(). But as hard as I tried I cant remove the last "\n" which Return button creates.
Here is my code for this part:... | How to erase everything from the tkinter text widget? | Im working on a GUI for some chat programme. For user's input I have Text() widget, messages are sent via "Return" and after that I clean the Text(). But as hard as I tried I cant remove the last "\n" which Return button creates.
Here is my code for this part:
def Send(Event):
MSG_to_send=Tex2.get("1.0",END)
cli... | [
"Most likely your problem is that your binding is happening before the newline is inserted. You delete everything, but then the newline is inserted. This is due to the nature of how the text widget works -- widget bindings happen before class bindings, and class bindings are where user input is actually inserted in... | [
7,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0005322027_python_tkinter.txt |
Q:
Speed comparisons between Chameleon and Jinja2
Has anyone here done any benchmarking of Chameleon versus Jinja2, in respect to performance? I'm more used to the Jinja syntax, since I come from Django, but as Pyramid suggests to use Chameleon, I'm thinking if it would be nice to give it a try - despite having an aw... | Speed comparisons between Chameleon and Jinja2 | Has anyone here done any benchmarking of Chameleon versus Jinja2, in respect to performance? I'm more used to the Jinja syntax, since I come from Django, but as Pyramid suggests to use Chameleon, I'm thinking if it would be nice to give it a try - despite having an awkward syntax, IMO.
| [
"Template engines are rarely the cause of performance problems, even if chameleon is slightly faster than Jinja2 I doubt the effort of learning a new template language etc. is worth it. \nOptimization of database queries and caching will probably result in more performance than you could gain by switching the templ... | [
19,
5,
4
] | [] | [] | [
"chameleon",
"jinja2",
"performance",
"pyramid",
"python"
] | stackoverflow_0005321789_chameleon_jinja2_performance_pyramid_python.txt |
Q:
Iteration over n values
I'd like to make an iteration to calculate all the possibilities of a given formula. I need to write down nested iteration but couldn't make it right. I am not good at algorithm :(
For calculating all the possibilities(%0-%100) 3 constant{z1,z2,z3} values, I prepared:
a=frange(0,1.0,0.01)
... | Iteration over n values | I'd like to make an iteration to calculate all the possibilities of a given formula. I need to write down nested iteration but couldn't make it right. I am not good at algorithm :(
For calculating all the possibilities(%0-%100) 3 constant{z1,z2,z3} values, I prepared:
a=frange(0,1.0,0.01)
for z1 in a:
for z2 in a:
... | [
"The easiest way is to use itertools.product():\na=frange(0,1.0,0.01)\nfor z in itertools.product(a, repeat=n):\n calculate(*z)\n\nIf n really would be 30, this would iterate over 100**30 = 10**60 values. Be prepared to wait.\n",
"itertools.product will do what you want (and more). Unfortunately it wants the ... | [
6,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0005324633_algorithm_python.txt |
Q:
Django/python indexerror
Exception Type: IndexError
Exception Value: list index out of range
i Have a form which inherits a model from , on saving the form instance i am getting the above error. Can you please suggest the cause of this error?
A:
The list has n elements, and you're trying to index it at n... | Django/python indexerror | Exception Type: IndexError
Exception Value: list index out of range
i Have a form which inherits a model from , on saving the form instance i am getting the above error. Can you please suggest the cause of this error?
| [
"The list has n elements, and you're trying to index it at n or greater. Restrict the index to between 0 and n-1 inclusive.\n",
"In such cases, there is a dictionary of elemnents , let me say:\nlst = {1:\"1\",\n 2:\"2\",\n 3:\"3\",\n 4:\"4\",\n 5:\"5\",\n 7:\"7\",\n 8:\"8\",\n ... | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0005323814_python.txt |
Q:
file reading in python
So my whole problem is that I have two files one with following format(for Python 2.6):
#comments
config = {
#comments
'name': 'hello',
'see?': 'world':'ABC',CLASS=3
}
This file has number of sections like this. Second file has format:
[23]
[config]
'name'='abc'
'see?'=
[23]
... | file reading in python | So my whole problem is that I have two files one with following format(for Python 2.6):
#comments
config = {
#comments
'name': 'hello',
'see?': 'world':'ABC',CLASS=3
}
This file has number of sections like this. Second file has format:
[23]
[config]
'name'='abc'
'see?'=
[23]
Now the requirement is that ... | [
"Was unable to find a beautiful solution due to the comments. This is tested and works for me, but requires Python 3.1 or higher:\nfrom collections import OrderedDict\n\nindenting = '\\t'\n\ndef almost_py_read(f):\n sections = OrderedDict()\n contents = None\n active = sections\n for line in f:\n ... | [
1,
1,
0
] | [] | [] | [
"config",
"file",
"merge",
"mod_python",
"python"
] | stackoverflow_0005312693_config_file_merge_mod_python_python.txt |
Q:
WindowsError: [Error 2] The system cannot find the file specified
I am having a problem with this code. I am trying to rename all of the filenames within a folder so that they no longer have +'s in them! This has worked many times before but suddenly I get the error:
WindowsError: [Error 2] The system cannot find... | WindowsError: [Error 2] The system cannot find the file specified | I am having a problem with this code. I am trying to rename all of the filenames within a folder so that they no longer have +'s in them! This has worked many times before but suddenly I get the error:
WindowsError: [Error 2] The system cannot find the file specified at line 26
Line 26 is the last line in the code.
D... | [
"I suspect that you may be having issues with subdirectories.\nIf you have a directory with files \"a\", \"b\" and subdirectory \"dir\" with files \"sub+1\" and \"sub+2\", the call to os.walk() will yield the following values:\n(('.',), ('dir',), ('a', 'b'))\n(('dir',), (,), ('sub+1', 'sub+2'))\n\nWhen you process ... | [
12,
4
] | [] | [] | [
"python",
"renaming"
] | stackoverflow_0005324107_python_renaming.txt |
Q:
pyqt - how to remove the boder from a widget in the statusbar?
I am using QLabel widgets to display error messages to the user in the status bar. This is working fine with the following code;
self.statusbar = self.statusBar()
label = QtGui.QLabel("this is a test error message")
stylesheet = """
QLabel {
font-wei... | pyqt - how to remove the boder from a widget in the statusbar? | I am using QLabel widgets to display error messages to the user in the status bar. This is working fine with the following code;
self.statusbar = self.statusBar()
label = QtGui.QLabel("this is a test error message")
stylesheet = """
QLabel {
font-weight: bold;
color: #FF0000;
}
"""
label.setStyleSheet(stylesheet)
sel... | [
"You do this with Style sheets. You probably have a line like this\nApplication app(argc, argv);\nunderneath that, add one like this:\napp.setStyleSheet(\"QStatusBar::item { border: 0px solid black }; \");\nand those pesky boxes will be gone.\n",
"try using self.statusbar.showMessage('this is a test error message... | [
2,
0
] | [] | [] | [
"border",
"pyqt4",
"python",
"statusbar"
] | stackoverflow_0005259161_border_pyqt4_python_statusbar.txt |
Q:
Cherokee causing problems spawning multiple uwsgi instances
I am running cherokee to serve a django app using uwsgi. I have been having some strange behavior since upgrading to cherokee 1.2.x.
The setup worked fine prior to cherokee 1.2.x and I haven't changed any of my configuration.
The problem is that now, whe... | Cherokee causing problems spawning multiple uwsgi instances | I am running cherokee to serve a django app using uwsgi. I have been having some strange behavior since upgrading to cherokee 1.2.x.
The setup worked fine prior to cherokee 1.2.x and I haven't changed any of my configuration.
The problem is that now, when uwsgi is not running and I try to load the django app site, I f... | [
"Looks like this is a cherokee bug fixed in trunk:\nhttp://svn.cherokee-project.com/listing.php?repname=Cherokee&peg=6382&rev=6380\nI downloaded trunk from SVN and I am no longer experiencing the problem.\n"
] | [
1
] | [] | [] | [
"cherokee",
"django",
"python",
"uwsgi"
] | stackoverflow_0005322395_cherokee_django_python_uwsgi.txt |
Q:
Problem using PYTHONPATH
I'm trying to use PYTHONPATH to let Python know where my library is located, but it seems to ignore it:
$ PYTHONPATH=/home/osqa/EC2/backup/src/boto/
$ ls /home/osqa/EC2/backup/src/boto/boto/ec2/connection.py
/home/osqa/EC2/backup/src/boto/boto/ec2/connection.py
$ python backup.py
Tracebac... | Problem using PYTHONPATH | I'm trying to use PYTHONPATH to let Python know where my library is located, but it seems to ignore it:
$ PYTHONPATH=/home/osqa/EC2/backup/src/boto/
$ ls /home/osqa/EC2/backup/src/boto/boto/ec2/connection.py
/home/osqa/EC2/backup/src/boto/boto/ec2/connection.py
$ python backup.py
Traceback (most recent call last):
F... | [
"Try\nexport PYTHONPATH=/home/osqa/EC2/backup/src/\n\ninstead, i.e. use export and remove the last path component.\n"
] | [
3
] | [] | [] | [
"python",
"pythonpath"
] | stackoverflow_0005325908_python_pythonpath.txt |
Q:
How to make PyInstaller work on wxPython using 2 stage creation with XRC?
Everyone suggests switch from py2exe to PyInstaller for making a standalone executable from Python scripts. Our first trial is to make a wxPython application which makes usage of lots of 2 stage creation with XRC. It seems the building proce... | How to make PyInstaller work on wxPython using 2 stage creation with XRC? | Everyone suggests switch from py2exe to PyInstaller for making a standalone executable from Python scripts. Our first trial is to make a wxPython application which makes usage of lots of 2 stage creation with XRC. It seems the building process of PyInstaller doesn't include those modules specified in .xrc files and I a... | [
"You might find this helpful: http://www.blog.pythonlibrary.org/2010/08/10/a-pyinstaller-tutorial-build-a-binary-series/\nPyInstaller's documentation also explains how to include and exclude stuff:\nhttp://www.pyinstaller.org/export/latest/tags/1.4/doc/Manual.html?format=raw#create-a-spec-file-for-your-project\nMy ... | [
0
] | [] | [] | [
"pyinstaller",
"python",
"wxpython",
"xrc"
] | stackoverflow_0005320156_pyinstaller_python_wxpython_xrc.txt |
Q:
Excluding words in Conditions in Python
I'm currently trying to write a program where I have several conditions. I wanted to exclude a list of words (det) from a list of tokens. Up to if len(W) <=8:, it worked just as I wanted it to. However, I could not get the program to find any of words in det in my list of t... | Excluding words in Conditions in Python | I'm currently trying to write a program where I have several conditions. I wanted to exclude a list of words (det) from a list of tokens. Up to if len(W) <=8:, it worked just as I wanted it to. However, I could not get the program to find any of words in det in my list of tokens, and exclude them from the printing.
Th... | [
"Your det seems to be invalid (check the quotes).\nIf you want to check often whether an element is in a list, you can use a set(), which is much faster to check for content.\nThe whole could look like this:\ndet = set([\"the\", \"a\", \"an\", \"'s\"])\n\nfor w in tkV:\n if 3 <= len(w) <= 8 and w not in det and ... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0005326295_python.txt |
Q:
Grab html from memcached if found, if not render and save to memcached
For a specific controller's action, how would I first check to see HTML is in memcached, and yes then render from cache.
If not found, render the view page's html, then take that html and store it in memcached for future requests.
I actually wa... | Grab html from memcached if found, if not render and save to memcached | For a specific controller's action, how would I first check to see HTML is in memcached, and yes then render from cache.
If not found, render the view page's html, then take that html and store it in memcached for future requests.
I actually want to do it in the controller's action, because I want to see what role the ... | [
"http://docs.djangoproject.com/en/dev/topics/cache/#the-per-view-cache\n",
"The easiest way is to use the cache_page decorator from django.views.decorators.cache.\nfrom django.views.decorators.cache import cache_page\n\n@cache_page(3600) #1 hour cache time in seconds\ndef a_view_to_cache(request):\n ...\n\nYo... | [
1,
1
] | [] | [] | [
"django",
"memcachedb",
"python"
] | stackoverflow_0005325239_django_memcachedb_python.txt |
Q:
Understanding the "tail -f in python"
I have created a very simple python script:
def read_then_follow(file):
for line in file:
yield line
while True:
line = file.readline()
if not line:
time.sleep(1.0)
continue
yield line
for line in read_then_follo... | Understanding the "tail -f in python" | I have created a very simple python script:
def read_then_follow(file):
for line in file:
yield line
while True:
line = file.readline()
if not line:
time.sleep(1.0)
continue
yield line
for line in read_then_follow("some_file.txt"): print line
The file "s... | [
"(I'm assuming you are on some Unix-like operating system.)\nSaving in vim will actually create a new file with the same name on the disk. The file handle held by your script still points to the old file, which does not have a directory entry anymore. If your script terminates, the reference counter of the old fi... | [
8
] | [] | [] | [
"file",
"file_io",
"python",
"tail"
] | stackoverflow_0005326405_file_file_io_python_tail.txt |
Q:
Django: Force a field to be unique for all model objects with the same foreign key
Suppose I have the following Models defined in django (not tested):
class CarMaker(models.Model):
name = models.CharField("Name of car maker",
max_length=40)
class Car(models.Model):
car_id = model... | Django: Force a field to be unique for all model objects with the same foreign key | Suppose I have the following Models defined in django (not tested):
class CarMaker(models.Model):
name = models.CharField("Name of car maker",
max_length=40)
class Car(models.Model):
car_id = models.IntegerField("ID for this particular car")
maker = models.ForeignKey("Maker of thi... | [
"You can use the model options unique_together to create this type of constraint. See the Django docs: http://docs.djangoproject.com/en/1.2/ref/models/options/#unique-together\nclass Car(models.Model):\n car_id = models.IntegerField(\"ID for this particular car\")\n maker = models.ForeignKey(\"Maker of this c... | [
13
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0005326727_django_django_models_python.txt |
Q:
Any issues with using ".django." for django applications?
I know Django applications are typically named django-appname, however, our non-django packages are released under a namespace for our company (eg. company.modulename). Our Django applications are currently structured in a "django" namespace within that nam... | Any issues with using ".django." for django applications? | I know Django applications are typically named django-appname, however, our non-django packages are released under a namespace for our company (eg. company.modulename). Our Django applications are currently structured in a "django" namespace within that namespace (eg. company.django.appname).
We are evaluating our str... | [
"We use a company.modulename style namespace for a few django apps and have encountered no problems.\nIn the __init__.py files we declare the namespace.\nimport pkg_resources\n\npkg_resources.declare_namespace(__name__)\n\nand it's worked fine so far.\n",
"Forcing absolute imports will remove any chance of issues... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005325837_django_python.txt |
Q:
Disable logging for a particular package
I am implementing python logging in my application, and I want to be able to leverage the "default" root settings. I want to use root settings because I dont want to have to define a logger per module in a config file.
When I turn on DEBUG level logging for the root logg... | Disable logging for a particular package | I am implementing python logging in my application, and I want to be able to leverage the "default" root settings. I want to use root settings because I dont want to have to define a logger per module in a config file.
When I turn on DEBUG level logging for the root logger, I am running into an issue with the QPID P... | [
"With python2.7 you can set NullHandler to qpid logger:\n[logger_qpid]\nlevel=NOTSET\nhandlers=nullHandler\nqualname=qpid\npropagate=0\n\n"
] | [
3
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0005326012_logging_python.txt |
Q:
Method for dry runs?
at the moment my python code often looks like this:
...
if not dry_run:
result = shutil.copyfile(...)
else:
print " DRY-RUN: shutil.copyfile(...) "
...
I now think about writting something like a dry runner method:
def dry_runner(cmd, dry_run, message, before="", after=""):
if d... | Method for dry runs? | at the moment my python code often looks like this:
...
if not dry_run:
result = shutil.copyfile(...)
else:
print " DRY-RUN: shutil.copyfile(...) "
...
I now think about writting something like a dry runner method:
def dry_runner(cmd, dry_run, message, before="", after=""):
if dry_run:
print befo... | [
"You could use this generic wrapper function:\ndef execute(func, *args):\n print 'before', func\n if not dry:\n func(*args)\n print 'after', func\n\n>>> execute(shutil.copyfile, 'src', 'dst')\n\n",
"This isn't perfect in its display, but the functionality works. Hopefully this is clear enough:\nd... | [
4,
4
] | [] | [] | [
"python"
] | stackoverflow_0003279806_python.txt |
Q:
How can I refactor these two functions to be more DRY?
I have the following two Python functions:
@classmethod
def serialize_dict(cls, d):
values = []
for column_name in cls().distinguishing_column_names():
value = str(d[column_name])
if value == 'None':
value = ''
value... | How can I refactor these two functions to be more DRY? | I have the following two Python functions:
@classmethod
def serialize_dict(cls, d):
values = []
for column_name in cls().distinguishing_column_names():
value = str(d[column_name])
if value == 'None':
value = ''
values.append(value)
return ' '.join(values)
@classmethod
de... | [
"Why don't you just implement the relevant bits of the dict interface in your custom type?\nSo that row[column_name] results in the code you want?\nYou use the __getitem__ special method for this.\n",
"Add an if isinstance(arg, dict) to determine whether to treat it as a row or dict, then merge the two methods to... | [
4,
3,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0005326763_python.txt |
Q:
Problem with command-line registeration with PyPI in Windows 7
When I type c:\python32\python.exe setup.py register and press ENTER I get the following:
running register
running check
We need to know who you are, so please choose either:
1. use your existing login,
2. register as a new user,
3. have the serve... | Problem with command-line registeration with PyPI in Windows 7 | When I type c:\python32\python.exe setup.py register and press ENTER I get the following:
running register
running check
We need to know who you are, so please choose either:
1. use your existing login,
2. register as a new user,
3. have the server generate a new password for you (and email it to you), or
4. qui... | [
"I added .pypirc file with my username and password in my home folder. That is, C:\\Users\\*****.\n[distutils] \nindex-servers = pypi \n\n[pypi] \nusername: *****\npassword: *****\n\nI was then able to register and upload my module. \nNote: This is a workaround.\n"
] | [
1
] | [] | [] | [
"pypi",
"python",
"windows_7"
] | stackoverflow_0005302058_pypi_python_windows_7.txt |
Q:
Crash in PyScripter with PyQT
I begin to use PYQT and my IDE PyScripter is systematically closed when I launch for the second time ! Even for very simple code like :
#!/usr/bin/env python
import sys
from PyQt4.QtGui import QLabel, QApplication
if __name__=='__main__':
App = QApplication(sys.argv)
Label ... | Crash in PyScripter with PyQT | I begin to use PYQT and my IDE PyScripter is systematically closed when I launch for the second time ! Even for very simple code like :
#!/usr/bin/env python
import sys
from PyQt4.QtGui import QLabel, QApplication
if __name__=='__main__':
App = QApplication(sys.argv)
Label = QLabel( "Hello World!" )
Labe... | [
"You have to use the Remote Engine. See http://code.google.com/p/pyscripter/wiki/RemoteEngines\n"
] | [
1
] | [] | [] | [
"pyqt",
"pyqt4",
"pyscripter",
"python"
] | stackoverflow_0005327298_pyqt_pyqt4_pyscripter_python.txt |
Q:
OpenCV Python QueryFrame function leaks memory
I'm using the Python interface for OpenCV 2.2.0. The following code works correctly for grabbing frames from a video file:
for f in range(1, frameCount):
# grab the left and right frames
frameL = cv.QueryFrame(videoL)
frameR = cv.QueryFrame(videoR)
# c... | OpenCV Python QueryFrame function leaks memory | I'm using the Python interface for OpenCV 2.2.0. The following code works correctly for grabbing frames from a video file:
for f in range(1, frameCount):
# grab the left and right frames
frameL = cv.QueryFrame(videoL)
frameR = cv.QueryFrame(videoR)
# create the image for the first frame
if f==1:
... | [
"You should allocate memory for both images once:\n imageL = cv.CreateImageHeader(cv.GetSize(frameL), frameL.depth, frameL.channels)\n imageR = cv.CreateImageHeader(cv.GetSize(frameR), frameR.depth, frameR.channels)\nthen begin your loop and set the data:\ncv.SetData(frameL, imageL)\ncv.SetData(frameR, imageR)\... | [
1
] | [] | [] | [
"opencv",
"python",
"video"
] | stackoverflow_0005318311_opencv_python_video.txt |
Q:
Trouble finding library that supports http PUT in Python 2.7
I need to perform http PUT operations from python Which libraries have been proven to support this? More specifically I need to perform PUT on keypairs, not file upload.
I have been trying to work with the restful_lib.py, but I get invalid results from t... | Trouble finding library that supports http PUT in Python 2.7 | I need to perform http PUT operations from python Which libraries have been proven to support this? More specifically I need to perform PUT on keypairs, not file upload.
I have been trying to work with the restful_lib.py, but I get invalid results from the API that I am testing. (I know the results are invalid because... | [
"httplib should manage.\nhttp://docs.python.org/library/httplib.html\nThere's an example on this page http://effbot.org/librarybook/httplib.htm\n",
"urllib and urllib2 are also suggested. \n",
"Thank you all for your assistance. I think I have found an answer. \nMy code now looks like this:\nimport urllib\nim... | [
3,
2,
0
] | [] | [] | [
"http",
"http_put",
"pycurl",
"python"
] | stackoverflow_0005325858_http_http_put_pycurl_python.txt |
Q:
how add new line in CSV file using python
I have a csv file that contains time (hh:mm:ss) and date (mm/dd/yyyy) fields, and sixteen more fields.
Generally the time field display time every 30'', but sometime the separation might be more (minutes or even hours).
For instance:
1/27/2011 12:10:00
1/27/2011 12:10:30 ... | how add new line in CSV file using python | I have a csv file that contains time (hh:mm:ss) and date (mm/dd/yyyy) fields, and sixteen more fields.
Generally the time field display time every 30'', but sometime the separation might be more (minutes or even hours).
For instance:
1/27/2011 12:10:00
1/27/2011 12:10:30
1/27/2011 12:11:00
1/27/2011 12:15:00
I need... | [
"Buffer the last two lines, calculate the time difference between them, and write output based upon the results of a conditional test on that time difference.\n",
"Have you checked the manual?\nhttp://docs.python.org/library/csv.html\nthere are also examples at the end\nThe first idea that comes to my mind is ite... | [
1,
0,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0005327547_csv_python.txt |
Q:
sqlalchemy + mysql deadlocks
I insert rows with random data into mysql database. After inserting some rows, greenlet hangs on connecting. Statistics printing greenlet keeps running
This happens with any number of workers (including one), both with mysql-connector and mysqldb drivers.
sqlite works fine.
This has no... | sqlalchemy + mysql deadlocks | I insert rows with random data into mysql database. After inserting some rows, greenlet hangs on connecting. Statistics printing greenlet keeps running
This happens with any number of workers (including one), both with mysql-connector and mysqldb drivers.
sqlite works fine.
This has no effect (as i understand it is alr... | [
"I just forgot to release used connections, so connections where never checked-in back into pool.\n ...\ndef add(self, junk, i):\n print i, 'connecting'\n c = self.e.connect()\n ...\n try:\n ...\n except Exception as e:\n ...\n finally:\n c.close() # <-- this returns conenc... | [
1
] | [] | [] | [
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0005324410_mysql_python_sqlalchemy.txt |
Q:
Logging lock acquire and release calls in multi-threaded application
I am trying to debug a multi-threaded Python application that uses various locks.
Rather than place log.debug(...) statements all over the shot to track where and when the locks are acquired and released, my idea is to decorate the methods threa... | Logging lock acquire and release calls in multi-threaded application | I am trying to debug a multi-threaded Python application that uses various locks.
Rather than place log.debug(...) statements all over the shot to track where and when the locks are acquired and released, my idea is to decorate the methods threading.Lock.acquire() and threading.Lock.release(), and prefix their invocat... | [
"I recently had just your problem. I set up my logger to automatically log thread name, like in this answer. I found out it was not possible to subclass Lock, so I had to wrap it, like this:\nclass LogLock(object):\n def __init__(self, name):\n self.name = str(name)\n self.lock = Lock()\n\n def ... | [
5
] | [] | [] | [
"debugging",
"decorator",
"locks",
"multithreading",
"python"
] | stackoverflow_0005327614_debugging_decorator_locks_multithreading_python.txt |
Q:
django to send AND receive email?
I have gotten quite familiar with django's email sending abilities, but I havn't seen anything about it receiving and processing emails from users. Is this functionality available?
A few google searches have not turned up very promising results. Though I did find this: Receive an... | django to send AND receive email? | I have gotten quite familiar with django's email sending abilities, but I havn't seen anything about it receiving and processing emails from users. Is this functionality available?
A few google searches have not turned up very promising results. Though I did find this: Receive and send emails in python
Am I going to h... | [
"There's an app called jutda-helpdesk that uses Python's poplib and imaplib to process incoming emails. You just have to have an account somewhere with POP3 or IMAP access.\nThis is adapted from their get_email.py:\ndef process_mail(mb):\n print \"Processing: %s\" % q\n if mb.email_box_type == 'pop3':\n ... | [
20,
6,
1
] | [] | [] | [
"django",
"django_email",
"email",
"pop3",
"python"
] | stackoverflow_0000730573_django_django_email_email_pop3_python.txt |
Q:
Execute function without sending 'self' to it
Is that possible to define a function without referencing to self this way?
def myfunc(var_a,var_b)
But so that it could also get sender data, like if I defined it like this:
def myfunc(self, var_a,var_b)
That self is always the same so it looks a little redundant he... | Execute function without sending 'self' to it | Is that possible to define a function without referencing to self this way?
def myfunc(var_a,var_b)
But so that it could also get sender data, like if I defined it like this:
def myfunc(self, var_a,var_b)
That self is always the same so it looks a little redundant here always to run a function this way: myfunc(self,'... | [
"If you don't need self, you can use the staticmethod decorator to create a method which does not receive the object as its first argument:\nclass Foo(object):\n @staticmethod\n def foo(bar, baz, qux):\n pass\n\nIf you're writing code which deals only with class-global data, by contrast, you can use a ... | [
9,
2,
1,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0005313364_google_app_engine_python.txt |
Q:
Shell script to run Python program with command line arguments
I have some files in a directory which are input files for my python script:
<1.in>
<1.in.xml>
<2.in>
<2.in.xml>
<3.in>
<3.in.xml>
...
..
.
I have the following till now:
for i in $(ls dir/*.in)
do
new = ${i%%.in}
test.py -i $new.in.xm... | Shell script to run Python program with command line arguments | I have some files in a directory which are input files for my python script:
<1.in>
<1.in.xml>
<2.in>
<2.in.xml>
<3.in>
<3.in.xml>
...
..
.
I have the following till now:
for i in $(ls dir/*.in)
do
new = ${i%%.in}
test.py -i $new.in.xml -o out_$new -x $new.in -c 56
done
When I run this, it does not cr... | [
"Make sure you are opening the file for output as open(file_name, 'w') or else the file will not be created.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0005328122_python.txt |
Q:
How to get emacs to ignore the shebang (#!/some/interpreter) when determining what mode to open a file
I'm editing python files which are intended to be executed by Jython so they the appropriate shebang at the top of the file:
#!/usr/bin/jython
This results in the files being opened in jython-mode. However, I w... | How to get emacs to ignore the shebang (#!/some/interpreter) when determining what mode to open a file | I'm editing python files which are intended to be executed by Jython so they the appropriate shebang at the top of the file:
#!/usr/bin/jython
This results in the files being opened in jython-mode. However, I want to use python-mode. I can not seem to get the buffer into python-mode and out of jython-mode in anyway ... | [
"Add the following to your .emacs:\n(delq (assoc \"jython\" interpreter-mode-alist) interpreter-mode-alist)\n\nSee the documentation for How Emacs Chooses a Major Mode. Or you can use the heavy hammer and get rid of shebang handling altogether:\n(setq interpreter-mode-alist nil)\n\n"
] | [
4
] | [] | [] | [
"emacs",
"jython",
"python"
] | stackoverflow_0005327764_emacs_jython_python.txt |
Q:
Python+suds : xsd_base64Binary type?
I'm trying to attach some files to a Jira using the Soap API.
I have python 2.6 and SOAPpy isn't working any more, so, I'm using suds. Everything is fine except for the attachements ... I don't know how to rewrite this piece of code : http://confluence.atlassian.com/display/JI... | Python+suds : xsd_base64Binary type? | I'm trying to attach some files to a Jira using the Soap API.
I have python 2.6 and SOAPpy isn't working any more, so, I'm using suds. Everything is fine except for the attachements ... I don't know how to rewrite this piece of code : http://confluence.atlassian.com/display/JIRA/Creating+a+SOAP+Client?focusedCommentId... | [
"If you do not want to use the Java CLI, below is how to add and attachment in Python.\nfrom suds.client import Client\nclient = Client(url_to_wsdl_file)\nauth = client.service.login(username, password)\n\nclient.service.addBase64EncodedAttachmentsToIssue(auth, issue_key, [filename.encode(\"utf-8\")], [open(full_pa... | [
1,
0,
0
] | [] | [] | [
"jira",
"python",
"soap",
"suds"
] | stackoverflow_0002283219_jira_python_soap_suds.txt |
Q:
Saving many Django objects with one big INSERT statement
Imagine you have the following situation:
for i in xrange(100000):
account = Account()
account.foo = i
account.save
Obviously, the 100,000 INSERT statements executed by Django are going to take some time. It would be nicer to be able to combine all th... | Saving many Django objects with one big INSERT statement | Imagine you have the following situation:
for i in xrange(100000):
account = Account()
account.foo = i
account.save
Obviously, the 100,000 INSERT statements executed by Django are going to take some time. It would be nicer to be able to combine all those INSERTs into one big INSERT. Here's the kind of thing I'm ... | [
"As shown in this related question, one can use @transaction.commit_manually to combine all the .save() operations as a single commit to greatly improve performance.\n@transaction.commit_manually\ndef your_view(request):\n try:\n for i in xrange(100000):\n account = Account()\n accou... | [
8,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005328301_django_python.txt |
Q:
Problem using break command in Python tutorial
I'm following the python tutorial at their site and I'm currently at the break continue section. I just tried this sample code.
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print n, 'equals', x, '*', n/x
... ... | Problem using break command in Python tutorial | I'm following the python tutorial at their site and I'm currently at the break continue section. I just tried this sample code.
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print n, 'equals', x, '*', n/x
... break
... else:
... # loop fell t... | [
"The output which you show contains ten times the string \"x is a prime number\". However, this string is printed in the else clause of the inner loop, and is as such executed at most once for each execution of the inner loop.\nSince the outer loop performs eight iterations, \"x is a prime number\" cannot be printe... | [
4,
1,
0,
0,
0
] | [] | [] | [
"break",
"for_loop",
"python"
] | stackoverflow_0001625174_break_for_loop_python.txt |
Q:
How should I go about writing a naive Bayesian classifier in Python?
I need to create a weather prediction system in Python. What it will do is take in a file which contains weather data — such as temperature (mean, max, min), wind, dew point, humidity, condition (fog, rain, snow, none) etc. — and use this to tra... | How should I go about writing a naive Bayesian classifier in Python? | I need to create a weather prediction system in Python. What it will do is take in a file which contains weather data — such as temperature (mean, max, min), wind, dew point, humidity, condition (fog, rain, snow, none) etc. — and use this to train a naive Bayesian model so it can then predict the condition of the next... | [
"The nltk.classify.naivebayes module may be what you're looking for. Here is a page with examples of how to use nltk classifiers. It shows how to classify text, but should provide some hints as to how to train a classifier based on your weather features.\n",
"Paul Graham described Bayesian classification, in the... | [
3,
2
] | [] | [] | [
"classification",
"python"
] | stackoverflow_0005329024_classification_python.txt |
Q:
Python interpeter that randomly changes type or varrible
So I am learning python for fun and I have come across an error that completely stumps me. When I am running my code I get the following error:
TypeError: unsupported operand type(s) for /: 'int' and 'type'
this error is triggered by the division in:
for i ... | Python interpeter that randomly changes type or varrible | So I am learning python for fun and I have come across an error that completely stumps me. When I am running my code I get the following error:
TypeError: unsupported operand type(s) for /: 'int' and 'type'
this error is triggered by the division in:
for i in items:
print i[1]
multiplier = WeightLeft / i[1]
t... | [
"i[1] is the type object int, not an instance of this type. Trying to convert this type object to an integer is like calling int(int).\n",
"<type 'int'> is what you'd get if you do i[1] = int, so I'm guessing that somewhere you have i[1] = int instead of i[1] = int(...).\n"
] | [
4,
1
] | [] | [] | [
"compiler_errors",
"python"
] | stackoverflow_0005329510_compiler_errors_python.txt |
Q:
Making PyPy work with any version of Python (>2.5)?
I want to use PyPy with Python 2.6. The default version (PyPy 1.4.1) seems to be 2.5 when downloading binaries. Google doesn't seem to be helping much, advice?
A:
You can download a nightly build if one exists for your platform. They support Python 2.7 and an o... | Making PyPy work with any version of Python (>2.5)? | I want to use PyPy with Python 2.6. The default version (PyPy 1.4.1) seems to be 2.5 when downloading binaries. Google doesn't seem to be helping much, advice?
| [
"You can download a nightly build if one exists for your platform. They support Python 2.7 and an official release with this support is supposed to happen in the next days, as PyPy developers are sprinting at PyCon right now.\nEdit: As of 2012, PyPy stable releases support Python 2.7 and there is ongoing effort to ... | [
3
] | [] | [] | [
"pypy",
"python"
] | stackoverflow_0005328683_pypy_python.txt |
Q:
Python CSV - Need to Group and Calculate values based on one key
I have a simple 3 column csv file that i need to use python to group each row based on one key, then average the values for another key and return them. File is standard csv format, set up as so;
ID, ZIPCODE, RATE
1, 19003, 27.50
2, 19003, 31.33
3, 1... | Python CSV - Need to Group and Calculate values based on one key | I have a simple 3 column csv file that i need to use python to group each row based on one key, then average the values for another key and return them. File is standard csv format, set up as so;
ID, ZIPCODE, RATE
1, 19003, 27.50
2, 19003, 31.33
3, 19083, 41.4
4, 19083, 17.9
5, 19102, 21.40
So basically what I need to... | [
"I've documented some steps to help clarify things:\nimport csv\nfrom collections import defaultdict\n\n# a dictionary whose value defaults to a list.\ndata = defaultdict(list)\n# open the csv file and iterate over its rows. the enumerate()\n# function gives us an incrementing row number\nfor i, row in enumerate(cs... | [
7,
3
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0005328971_csv_python.txt |
Q:
Is there a good way to do version control when developing pylons applications with dependencies?
I'm developing two pylons applications at the same time. Application B uses a lot of the controllers, etc. in application A. Both applications are under active development, but for administrative reasons, they have to ... | Is there a good way to do version control when developing pylons applications with dependencies? | I'm developing two pylons applications at the same time. Application B uses a lot of the controllers, etc. in application A. Both applications are under active development, but for administrative reasons, they have to be kept separate.
Is there a convenient way to do version control so that changes to A are easy to pul... | [
"The only reasonable way to do what you want is to have application B work against formal releases of application A, even if those releases are labled beta or release candidate. IOW, do not treat application A as source code, but as an imported module installed with setup.py or other means.\nDoing it this way will ... | [
0
] | [] | [] | [
"controls",
"python",
"version"
] | stackoverflow_0005328691_controls_python_version.txt |
Q:
What checks should be performed on user data from forms?
I'm writing an app engine app, that has some input fields.
Are there any concerns I need to take into account about something like this?
A:
You should validate that any input from your users meets your requirements. For example, if you need an positive in... | What checks should be performed on user data from forms? | I'm writing an app engine app, that has some input fields.
Are there any concerns I need to take into account about something like this?
| [
"You should validate that any input from your users meets your requirements. For example, if you need an positive integer, then make sure that's what you got.\nAs far as strings, you don't have to worry about SQL (or GQL in this case) injection as long as you don't construct the queries by hand. Instead use the G... | [
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0005304643_google_app_engine_python.txt |
Q:
Create document with python
Is there a library that create a word document with a specific size (width - hight)?
What I want to do is to create a word document that takes photo, date, name as input and put them in a specific positions in the document.
Thanks in advance
A:
Generally speaking you can use OpenOffic... | Create document with python | Is there a library that create a word document with a specific size (width - hight)?
What I want to do is to create a word document that takes photo, date, name as input and put them in a specific positions in the document.
Thanks in advance
| [
"Generally speaking you can use OpenOffice uno (SDK) for generating documents and then save them to word format (If by size your mean A4/A2... format then it work in OOo too). I haven't done this in python I used uno from java and c# but I think it should be even easier in python.\nHere the link for Python-UNO brid... | [
2
] | [] | [] | [
"ms_word",
"python"
] | stackoverflow_0005329864_ms_word_python.txt |
Q:
python-Twitter-api
import twitter
client = twitter.Api()
client = twitter.Api(username='uname', password='password')
update = client.PostUpdate('Tweetin from python!')
This is my code.
When i execute this program i get this error
TypeError: __init__() got an unexpected keyword argument 'username'
Can someone ... | python-Twitter-api | import twitter
client = twitter.Api()
client = twitter.Api(username='uname', password='password')
update = client.PostUpdate('Tweetin from python!')
This is my code.
When i execute this program i get this error
TypeError: __init__() got an unexpected keyword argument 'username'
Can someone help me?
| [
"take a look at this tutorial Twitter From the Command Line in Python Using OAuth \n",
"Per the documentation, you have to use OAuth, and specify keys and access tokens in the API constructor:\nhttp://code.google.com/p/python-twitter/\n>>> api = twitter.Api(consumer_key='consumer_key',\nconsumer_secret='consumer_... | [
2,
1
] | [] | [] | [
"api",
"python",
"twitter"
] | stackoverflow_0005329640_api_python_twitter.txt |
Q:
Comprehension for flattening a sequence of sequences?
If I have sequence of sequences (maybe a list of tuples) I can use itertools.chain() to flatten it. But sometimes I feel like I would rather write it as a comprehension. I just can't figure out how to do it. Here's a very construed case:
Let's say I want to swa... | Comprehension for flattening a sequence of sequences? | If I have sequence of sequences (maybe a list of tuples) I can use itertools.chain() to flatten it. But sometimes I feel like I would rather write it as a comprehension. I just can't figure out how to do it. Here's a very construed case:
Let's say I want to swap the elements of every pair in a sequence. I use a string ... | [
"With a comprehension? Well...\n>>> seq = '012345'\n>>> swapped_pairs = zip(seq[1::2], seq[::2])\n>>> ''.join(item for pair in swapped_pairs for item in pair)\n'103254'\n\n",
"Quickest I've found is to start with an empty array and extend it:\nIn [1]: a = [['abc', 'def'], ['ghi'],['xzy']]\n\nIn [2]: result = []\n... | [
32,
16,
3,
1
] | [] | [] | [
"list_comprehension",
"python",
"sequences"
] | stackoverflow_0000457215_list_comprehension_python_sequences.txt |
Q:
python: join print with previous printed line
In python (2.6) is it possilbe to "join" print output with the previous line of print output? The trailing comma syntax ( print x,) doesn't work because most of the output should have a new line.
for fc in fcs:
count = getCount(fc)
print '%s records in %s' % (... | python: join print with previous printed line | In python (2.6) is it possilbe to "join" print output with the previous line of print output? The trailing comma syntax ( print x,) doesn't work because most of the output should have a new line.
for fc in fcs:
count = getCount(fc)
print '%s records in %s' % ('{0:>9}'.format(count),fc)
if count[0] == '0':
... | [
"import sys\nsys.stdout.write(\"hello world\")\n\nprint writes to the apps standard out and adds a newline.\nHowever you sys.stdout is already a file object pointing to the same location and the write() function of a file object doesn't automatically append a newline to the output string so it should be exactly wha... | [
3,
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0005330249_python.txt |
Q:
Python: how to convert a complex array to a 2D array?
As a C++ programmer, I'm used to access vectors in C++ style:
for (i=0; i<max_x; i++) {
for (j=0; j<max_y; j++) {
vec[i][j] = real(complex_number(j+i*max_x))
}
}
Now I have in Python
x = np.linspace(x1, x2, step)
y = np.linspace(y1, y2, step)
... | Python: how to convert a complex array to a 2D array? | As a C++ programmer, I'm used to access vectors in C++ style:
for (i=0; i<max_x; i++) {
for (j=0; j<max_y; j++) {
vec[i][j] = real(complex_number(j+i*max_x))
}
}
Now I have in Python
x = np.linspace(x1, x2, step)
y = np.linspace(y1, y2, step)
X, Y = np.meshgrid(x, y)
Z = x + 1j*y
for z in ... | [
"Instead of doing Z = x + 1j*y then reshaping, you could do:\nZ = np.zeros((ydim, xdim), dtype=complex)\nZ.real, Z.imag = X, Y\n\nwhich I think might be more efficient (less operations in total). \n",
"Use reshape to turn a 1D array to 2D (or any other shapes).\n>>> x_max = 12\n>>> y_max = 4\n>>> vec1d = np.arang... | [
2,
2,
0
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0005330368_numpy_python_scipy.txt |
Q:
What is the best, efficient approach to do a quick forms based web project?
I am a database guy and its been few years since I did anything with PHP (no MVC experience). I now have to work on a Data Entry project - a form that a user will fill and submit data to the database. I figured this is much more efficient ... | What is the best, efficient approach to do a quick forms based web project? | I am a database guy and its been few years since I did anything with PHP (no MVC experience). I now have to work on a Data Entry project - a form that a user will fill and submit data to the database. I figured this is much more efficient than a spreadsheet approach.
All I need is :
1) Authentication
2) Validation of ... | [
"Use django to two years, and I had an experience of a project using cakephp and hated it. Django was able to show better in all aspects, much of it takes the python and transparent way how the framework works. I strongly recommend Django.\n",
"You should use Symfony with Doctrine : all you'll have to do is defin... | [
3,
2,
2,
0
] | [] | [] | [
"cakephp",
"django",
"model_view_controller",
"python",
"symfony1"
] | stackoverflow_0005328789_cakephp_django_model_view_controller_python_symfony1.txt |
Q:
Way to encapsulate instance fields in Python
Is this use of @property decorator appropriate to obtain a good encapsulation of instance fields? I'm trying to achieve that Foobar class' clients can't assign arbitrary values to the field vel of Foobar instances in any way, de facto bypassing assignment rules defined ... | Way to encapsulate instance fields in Python | Is this use of @property decorator appropriate to obtain a good encapsulation of instance fields? I'm trying to achieve that Foobar class' clients can't assign arbitrary values to the field vel of Foobar instances in any way, de facto bypassing assignment rules defined in the property setter method.
Thanks.
class Fooba... | [
"You can't prevent the user from bypassing anything in python. There's always a way to monkeypatch/reflect/inspect attributes; There's no object sandboxing support.\nIn your example:\n>>> foobar._vel = -1\n\nWould bypass the property entirely and assign directly to the real attribute. You can't prevent it at all. T... | [
4
] | [] | [] | [
"decorator",
"encapsulation",
"properties",
"python"
] | stackoverflow_0005330438_decorator_encapsulation_properties_python.txt |
Q:
Pythonic dictionary traversal
I often find myself in situations where I need to traverse and parse a semi-complex JSON structure. During the traversal, there are certain dictionary keys that are expected, and their values need to be appropriately mapped to some object (foo.__dict__).
Any remaining key/values that... | Pythonic dictionary traversal | I often find myself in situations where I need to traverse and parse a semi-complex JSON structure. During the traversal, there are certain dictionary keys that are expected, and their values need to be appropriately mapped to some object (foo.__dict__).
Any remaining key/values that did not explicitly map to an objec... | [
"You can use the pop method of dictionaries:\nfor key in expected_keys:\n foo.__dict__[key] = d.pop(key)\nfoo.additional_attributes(**d)\n\n"
] | [
4
] | [] | [] | [
"django_models",
"metaprogramming",
"python"
] | stackoverflow_0005330626_django_models_metaprogramming_python.txt |
Q:
Read a JSP servlet page using PHP (libcurl), Python (liburl), or AJAX
So, I'm attempting to curl a page: http://rutgers.bncollege.com/webapp/wcs/stores/servlet/TextBookProcessDropdownsCmd?campusId=35577418 in order to extract some data. The issue is that I keep getting either a 404 error or 302 status on the heade... | Read a JSP servlet page using PHP (libcurl), Python (liburl), or AJAX | So, I'm attempting to curl a page: http://rutgers.bncollege.com/webapp/wcs/stores/servlet/TextBookProcessDropdownsCmd?campusId=35577418 in order to extract some data. The issue is that I keep getting either a 404 error or 302 status on the header. I suspect it has something to do with Barnes and Noble's Tomcat not prop... | [
"This looks kind of fishy. The very first option you set is a URL. Then you set it to POST data. Then at the end of the option block, you append a question mark to it, manually append even more query strings, then yank off the extra ampersand... and then re-reset the URL after changing it to a GET request! This... | [
0
] | [] | [] | [
"ajax",
"curl",
"jsp",
"php",
"python"
] | stackoverflow_0005327091_ajax_curl_jsp_php_python.txt |
Q:
Socket programming in Python -- actual remote port
I've been doing a bit of network programming these days in Python and would like to confirm the flow I think happens between the client and the server:
The servers listens to a given
advertised port (9999)
The client connects to the server by creating a new socke... | Socket programming in Python -- actual remote port | I've been doing a bit of network programming these days in Python and would like to confirm the flow I think happens between the client and the server:
The servers listens to a given
advertised port (9999)
The client connects to the server by creating a new socket (e.g. 1111)
The servers accepts the client request and... | [
"The new socket is on the same port. A TCP connection is identified by 4 pieces of information: the source IP and port, and the destination IP and port. So the fact that your server has two sockets on the same port (i.e. the listening socket and the accepted socket) is not a problem.\n"
] | [
4
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0005330967_python_sockets.txt |
Q:
Turn off a warning in sqlalchemy
I'm using sqlalchemy with reflection, a couple of partial indices in my DB make it dump warnings like this:
SAWarning: Predicate of partial index i_some_index ignored during reflection
into my logs and keep cluttering. It does not hinder my application behavior. I would like to kee... | Turn off a warning in sqlalchemy | I'm using sqlalchemy with reflection, a couple of partial indices in my DB make it dump warnings like this:
SAWarning: Predicate of partial index i_some_index ignored during reflection
into my logs and keep cluttering. It does not hinder my application behavior. I would like to keep these warnings while developing, but... | [
"Python's warning module provides a handy context manager that catches warnings for you.\nHere's how to filter out the SQLAlchemy warning.\nimport warnings\nfrom sqlalchemy import exc as sa_exc\n\nwith warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", category=sa_exc.SAWarning)\n # code here...\n... | [
60,
14
] | [] | [] | [
"postgresql",
"python",
"sqlalchemy"
] | stackoverflow_0005225780_postgresql_python_sqlalchemy.txt |
Q:
Why does Python let me define a variable in one scope, but use it in another?
I see that it's possible to define a variable inside a scope, but then refer to it outside that scope. For instance, the following code works:
if condition:
x = 5
else:
x = 10
print x
However, this strikes me as a bit weird. If ... | Why does Python let me define a variable in one scope, but use it in another? | I see that it's possible to define a variable inside a scope, but then refer to it outside that scope. For instance, the following code works:
if condition:
x = 5
else:
x = 10
print x
However, this strikes me as a bit weird. If you tried to do this in C, the variable X would not be scoped properly:
if(conditio... | [
"Blocks do not create a new scope in Python. Modules, classes, and functions do.\nAlso:\nx = 10\nif condition:\n x = 5\nprint x\n\nor:\nx = 5\nif not condition:\n x = 10\nprint x\n\n",
"My suggestion:\nWrite Python, not C.\nIn Python we use blocks. An if is a block. A block doesn't necessarily mean a differ... | [
17,
5,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005331047_python.txt |
Q:
Populating values in django-admin based on a foreign key selection
I have a model with a foreign key reference that looks something like this
class Plan(models.Model):
template = models.ForeignKey(PlanTemplate)
throttle = models.IntegerField(default=10)
rate_limit = models.BigIntegerField(default=60)
... | Populating values in django-admin based on a foreign key selection | I have a model with a foreign key reference that looks something like this
class Plan(models.Model):
template = models.ForeignKey(PlanTemplate)
throttle = models.IntegerField(default=10)
rate_limit = models.BigIntegerField(default=60)
and the foreign key model:
class PlanTemplate(models.Model):
name = ... | [
"I found a way to do this, but it had to involve javascript, which was actually pretty straight forward. I created a change_form.html in the templates/admin/billing/ directory which looked like this.\n{% extends \"admin/change_form.html\" %}\n\n{% block extrahead %}\n <script src=\"{{MEDIA_URL}}js/jquery.js\" t... | [
5,
0
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0005321186_django_django_admin_python.txt |
Q:
Automatically send and receive data from a HTML page
I am not sure which module I am supposed to use for this.
I have >100 files I need to submit to the following webpage and to retrieve the results.
http://bip.weizmann.ac.il/oca-bin/lpccsu
It would be beneficial if I could automate the process somehow sending th... | Automatically send and receive data from a HTML page | I am not sure which module I am supposed to use for this.
I have >100 files I need to submit to the following webpage and to retrieve the results.
http://bip.weizmann.ac.il/oca-bin/lpccsu
It would be beneficial if I could automate the process somehow sending the file to the
'<'input type="file" name="filename" size='... | [
"There are a few ways to do this:\n1) Perl and LWP\nuse LWP::UserAgent; \nmy $ua = new LWP::UserAgent; \n\nmy $response \n= $ua->post('http://bip.weizmann.ac.il/oca-bin/lpccsu?9955', \n{ param1 => 'value1',\nparam2 => 'value2', \n}); \n\nmy $content = $response->content;\n// your regular expression code\n\n2) Autoh... | [
2,
2
] | [] | [] | [
"html",
"python"
] | stackoverflow_0005329475_html_python.txt |
Q:
Recording keystrokes with pyHook
I've been trying to get this to work for some time now (to get the keyid to print in text, A="A", not A=125.)
Here is my code, it either prints "None" and sometimes it prints the wrong type, or even just the keyid again. (With different IDToName arguments)
import pyHook
from pyHook... | Recording keystrokes with pyHook | I've been trying to get this to work for some time now (to get the keyid to print in text, A="A", not A=125.)
Here is my code, it either prints "None" and sometimes it prints the wrong type, or even just the keyid again. (With different IDToName arguments)
import pyHook
from pyHook import HookManager
from pyHook.HookMa... | [
"why not just use event.Key? xx\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0005101472_python.txt |
Q:
Where is the pypy package in installed pypy-c
I have pypy-c installed with macports (latest version : pypy @1.4.1). I run pypy-c and try to import pypy
$ pypy-c
>>>> import pypy
Traceback (most recent call last):
File "<console>", line 1, in <module>
ImportError: No module named pypy
>>>> from pypy import transl... | Where is the pypy package in installed pypy-c | I have pypy-c installed with macports (latest version : pypy @1.4.1). I run pypy-c and try to import pypy
$ pypy-c
>>>> import pypy
Traceback (most recent call last):
File "<console>", line 1, in <module>
ImportError: No module named pypy
>>>> from pypy import translator
Traceback (most recent call last):
File "<co... | [
"What do you want to import pypy for?\nThere's no pypy module in the binary distribution, but there's one in the source checkout.\n"
] | [
0
] | [] | [] | [
"macports",
"pypy",
"python"
] | stackoverflow_0005331287_macports_pypy_python.txt |
Q:
Combination of numpy and multiprocessing Queues disturbs ordering of the queue
I am using the follwing pattern to do multiprocessing:
for item in data:
inQ.put(item)
for i in xrange(nProcesses):
inQ.put('STOP')
multiprocessing.Process(target=worker, args=(inQ, outQ)).start()
i... | Combination of numpy and multiprocessing Queues disturbs ordering of the queue | I am using the follwing pattern to do multiprocessing:
for item in data:
inQ.put(item)
for i in xrange(nProcesses):
inQ.put('STOP')
multiprocessing.Process(target=worker, args=(inQ, outQ)).start()
inQ.join()
outQ.put('STOP')
for result in iter(outQ.get, 'STOP'):
# ... | [
"numpy arrays use rich comparisons. So a=='STOP' returns a numpy array, not a bool, and that numpy array cannot be coerced to a bool. Under the covers, iter(outQ.get, 'STOP') is doing just that comparison and probably treating the exception when it tries to convert the result to a bool as False. You will have to do... | [
2,
2
] | [] | [] | [
"multiprocessing",
"numpy",
"python",
"queue",
"task_queue"
] | stackoverflow_0005322974_multiprocessing_numpy_python_queue_task_queue.txt |
Q:
Python - Easiest way to scrape text from list of URLs using BeautifulSoup
What's the easiest way to scrape just the text from a handful of webpages (using a list of URLs) using BeautifulSoup? Is it even possible?
Best,
Georgina
A:
import urllib2
import BeautifulSoup
import re
Newlines = re.compile(r'[\r\n]\s+')... | Python - Easiest way to scrape text from list of URLs using BeautifulSoup | What's the easiest way to scrape just the text from a handful of webpages (using a list of URLs) using BeautifulSoup? Is it even possible?
Best,
Georgina
| [
"import urllib2\nimport BeautifulSoup\nimport re\n\nNewlines = re.compile(r'[\\r\\n]\\s+')\n\ndef getPageText(url):\n # given a url, get page content\n data = urllib2.urlopen(url).read()\n # parse as html structured document\n bs = BeautifulSoup.BeautifulSoup(data, convertEntities=BeautifulSoup.Beautifu... | [
6,
1,
1
] | [] | [] | [
"beautifulsoup",
"python",
"screen_scraping",
"web_scraping"
] | stackoverflow_0005331266_beautifulsoup_python_screen_scraping_web_scraping.txt |
Q:
Need Pattern for lookup tables in Google App Engine
I'm using the Python version of Google App Engine and Datastore. What is a good way to load a table that will contain lookup data?
By look up data I mean that after the initial load no rows will need to be inserted, deleted, or updated
Blowing away all rows and ... | Need Pattern for lookup tables in Google App Engine | I'm using the Python version of Google App Engine and Datastore. What is a good way to load a table that will contain lookup data?
By look up data I mean that after the initial load no rows will need to be inserted, deleted, or updated
Blowing away all rows and reloading the table is not acceptable if it destroys refe... | [
"If it's really created once and never changes within the lifetime of a deployment, and it's relatively small (a few megs or less), store it with your app as data files. Have the app load the data into memory initially, and cache it there.\n",
"I think you're referring to some kind of write-behind cache but it is... | [
2,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0005328112_google_app_engine_google_cloud_datastore_python.txt |
Q:
Is it possible to send a URL from javascript running on the browser to the python program running on the client machine?
Can I send the url of the page from the javascript to the python program running on the client machine ??
Also can I redirect the output of the python program to the javascript to be displayed o... | Is it possible to send a URL from javascript running on the browser to the python program running on the client machine? | Can I send the url of the page from the javascript to the python program running on the client machine ??
Also can I redirect the output of the python program to the javascript to be displayed on the browser?
| [
"You can if you're running a server with Python.\nCreate a simple server with python and return json. The only requirement is that the python server must be started in order to except requests.\n",
"In case you want to use XMLHttpRequests you might run into problems that cross-domain requests are not permitted. S... | [
0,
0
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0005329942_javascript_python.txt |
Q:
MySQLdb and Python 3.X
I need the library for work in python 3.1.3 with MySQL, but I can't found it... I have searched for the way of installation but I can´t...
Trying to port the module I obtain this error:
Windows Error [error2] System can´t found the file
A:
You can find MySQL-python at Golhke repository f... | MySQLdb and Python 3.X | I need the library for work in python 3.1.3 with MySQL, but I can't found it... I have searched for the way of installation but I can´t...
Trying to port the module I obtain this error:
Windows Error [error2] System can´t found the file
| [
"You can find MySQL-python at Golhke repository for 3.1-3.2\n",
"You could also try MySQL Connector/Python on Windows and Python v3.1\nIt's pure Python, no MySQL software or compiling required.\n"
] | [
0,
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0005252557_mysql_python.txt |
Q:
How can I determine the bitrate type of mp3 files with Python?
How to determine the type of the bitrate used for an mp3 file, e.g. CBR, VBR or ABR?
A:
mutagen works for me. Here is an excerpt from one of my scripts.
from mutagen.mp3 import MP3
f = MP3(musicfile)
bitrate = f.info.bitrate / 1000
| How can I determine the bitrate type of mp3 files with Python? | How to determine the type of the bitrate used for an mp3 file, e.g. CBR, VBR or ABR?
| [
"mutagen works for me. Here is an excerpt from one of my scripts.\nfrom mutagen.mp3 import MP3\n\nf = MP3(musicfile)\nbitrate = f.info.bitrate / 1000\n\n"
] | [
19
] | [] | [] | [
"bitrate",
"mp3",
"python"
] | stackoverflow_0005332151_bitrate_mp3_python.txt |
Q:
How put html tags into XSL stylesheet?
I have python script that converts data.xml to html using stylesheet.xsl.
And i have a problem with inserting html tags into the stylesheet.
I would like to put all the generated values into table cells. maybe someone experienced could help me?
xsl:choose
xsl:when tes... | How put html tags into XSL stylesheet? | I have python script that converts data.xml to html using stylesheet.xsl.
And i have a problem with inserting html tags into the stylesheet.
I would like to put all the generated values into table cells. maybe someone experienced could help me?
xsl:choose
xsl:when test="$NECoords = 'true'"
xsl:value-of se... | [
"how about using \nstring-join( (concat('<td>',$firsElement),..(elements)..,concat($lastElement,'</td>') ) ,'</td><td>')\n\nI think that this code would generate something like\n<td>$firstElement</td><td>$secEl</td><td>..(n-cells)..</td><td>$lastElement</td>\n\nI don't know if there are problems with the <td> eleme... | [
1
] | [] | [] | [
"python",
"xslt"
] | stackoverflow_0005329463_python_xslt.txt |
Q:
Python - Easy way to scrape Google, download top N hits (entire .html documents) for given search?
Is there an easy way to scrape Google and write the text (just the text) of the top N (say, 1000) .html (or whatever) documents for a given search?
As an example, imagine searching for the phrase "big bad wolf" and d... | Python - Easy way to scrape Google, download top N hits (entire .html documents) for given search? | Is there an easy way to scrape Google and write the text (just the text) of the top N (say, 1000) .html (or whatever) documents for a given search?
As an example, imagine searching for the phrase "big bad wolf" and downloading just the text from the top 1000 hits -- i.e., actually downloading the text from those 1000 w... | [
"Check out BeautifulSoup for scraping the content out of web pages. It is supposed to be very tolerant of broken web pages which will help because not all results are well formed. So you should be able to:\n\nRequest http://www.google.ca/search?q=QUERY_HERE\nExtract and follow result links using BeautifulSoup (It a... | [
4,
3,
3
] | [] | [] | [
"google_search",
"python",
"urllib2",
"web_scraping"
] | stackoverflow_0005321434_google_search_python_urllib2_web_scraping.txt |
Q:
Syntax Error in Django urls.py
I'm having a frustrating time installing a very simple recipes website for myself using Django. Everything has been going fine until I attempt to set up my urls.py, which reads:
from django.conf.urls.defaults import *
from django.contrib import admin
from timsrecipes.recipes import v... | Syntax Error in Django urls.py | I'm having a frustrating time installing a very simple recipes website for myself using Django. Everything has been going fine until I attempt to set up my urls.py, which reads:
from django.conf.urls.defaults import *
from django.contrib import admin
from timsrecipes.recipes import views
admin.autodiscover()
urlpatte... | [
"The exception is not in urls.py, it's in recipes/views.py, line 13.\n"
] | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005332578_django_python.txt |
Q:
How to search & replace in Python?
How can I add a character "-" to a string such as 'ABC-D1234', so it becomes 'ABC-D-1234'?
Also, how can I add a character after the first 2 number, ie from 'ABC-D1234' to 'ABC-D12-34' Many thanks.
A:
It depends on the rule you are using to decide where to insert the extra cha... | How to search & replace in Python? | How can I add a character "-" to a string such as 'ABC-D1234', so it becomes 'ABC-D-1234'?
Also, how can I add a character after the first 2 number, ie from 'ABC-D1234' to 'ABC-D12-34' Many thanks.
| [
"It depends on the rule you are using to decide where to insert the extra character.\nIf you want it between the 5th and 6th characters you could try this:\ns = s[:5] + '-' + s[5:]\n\nIf you want it after the first hyphen and then one more character:\ni = s.index('-') + 2\ns = s[:i] + '-' + s[i:]\n\nIf you want it ... | [
3,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005332701_python.txt |
Q:
C ->Python Import Wrapper Problems
I have defined the name of my wrapper object in my c file blargUtils.c like this (I have defined methods and the lot for it in Blargmethods)...
void initBlarg(){
Py_InitModule("Blarg", Blargmethods);
}
I compiled it like so...
blarglib: blargUtils.c
gcc -I/usr/include/p... | C ->Python Import Wrapper Problems | I have defined the name of my wrapper object in my c file blargUtils.c like this (I have defined methods and the lot for it in Blargmethods)...
void initBlarg(){
Py_InitModule("Blarg", Blargmethods);
}
I compiled it like so...
blarglib: blargUtils.c
gcc -I/usr/include/python2.6 -fPIC -c blargUtils.c -Wall ... | [
"First of all, from looking at the comments, I see that renaming it didn't work. This means (1) python can't find the .so file, (2) the .so file isn't usable (i.e. not compiled correctly or not all required symbols are found), or (3) there is a .py/.pyc/.pyo file in the same directory which already has that name. I... | [
1
] | [] | [] | [
"c",
"import",
"python",
"wrapper"
] | stackoverflow_0005331167_c_import_python_wrapper.txt |
Q:
How to replace pairs of tokens in a string?
New to python, competent in a few languages, but can't see a 'snazzy' way of doing the following. I'm sure it's screaming out for a regex, but any solution I can come up with (using regex groups and what not) becomes insane quite quickly.
So, I have a string with html-li... | How to replace pairs of tokens in a string? | New to python, competent in a few languages, but can't see a 'snazzy' way of doing the following. I'm sure it's screaming out for a regex, but any solution I can come up with (using regex groups and what not) becomes insane quite quickly.
So, I have a string with html-like tags that I want to replace with actual html t... | [
"Maybe something like this can help :\nimport re\n\n\ndef text2html(text):\n \"\"\" Convert a text in a certain format to html.\n\n Examples:\n >>> text2html('Hello, my name is /bJane/b')\n 'Hello, my name is <b>Jane</b>'\n >>> text2html('/iHello/i, my /uname/u is /b/i/uJane/u/i/b')\n '<i>Hello</i... | [
7,
0,
0
] | [] | [] | [
"python",
"regex",
"token"
] | stackoverflow_0005331514_python_regex_token.txt |
Q:
How to rewrite a recursive function to use a loop instead?
This stack overflow thread claims that every recursive function can be written as a loop.
Which recursive functions cannot be rewritten using loops?
It makes complete sense. But I'm not sure how to express the following recursive function as a loop because... | How to rewrite a recursive function to use a loop instead? | This stack overflow thread claims that every recursive function can be written as a loop.
Which recursive functions cannot be rewritten using loops?
It makes complete sense. But I'm not sure how to express the following recursive function as a loop because it has a pre recursive piece of logic and a post recursive piec... | [
"The most pythonic way of doing permutations is to use:\n>>> from itertools import permutations\n>>> permutations([1,2,3])\n>>> list(permutations([1,2,3]))\n[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]\n\n",
"Let's say you want to find all permutations of [1, 2, 3, 4]. There are 24 (=4!) of... | [
3,
1,
0
] | [] | [] | [
"loops",
"permutation",
"python",
"recursion"
] | stackoverflow_0005330248_loops_permutation_python_recursion.txt |
Q:
Python html2text regex performance
i have build a html to plain text regex sequence. I use this in up to 100 threads to clean up html files. I want get all visible text information of an given html file.
self.content = re.sub(r'<!--(.|\n)*?-->', '', self.content)
self.content = re.sub(r'<script (.|\n)*?>(.... | Python html2text regex performance | i have build a html to plain text regex sequence. I use this in up to 100 threads to clean up html files. I want get all visible text information of an given html file.
self.content = re.sub(r'<!--(.|\n)*?-->', '', self.content)
self.content = re.sub(r'<script (.|\n)*?>(.|\n)*?</script>', '', self.content)
... | [
"Use a tool like BeautifulSoup or htmllib and don't try being smarter than the rest of the world. Parsing HTML using regular expressions is the worst thing you can do! There will always be one Html file more where your regexes will fail.\n",
"There is a common credo according which HTML and XML texts must ne-e-ev... | [
4,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0005331473_python_regex.txt |
Q:
Does the enumerate() function count elements in advance?
To support indexing over a collection Python includes enumerate() function. It provides index over collection.
for index, item in enumerate(list):
# do domething
print index
In my case I have a huge list and wonder if it is faster to create index ma... | Does the enumerate() function count elements in advance? | To support indexing over a collection Python includes enumerate() function. It provides index over collection.
for index, item in enumerate(list):
# do domething
print index
In my case I have a huge list and wonder if it is faster to create index manually that use enumerate()? e.g.
index = 0
for item in list:
... | [
"The enumerate function is built in; it does not count the elements a priori. The following is the C-code implementation:\nstatic PyObject *\nenum_next(enumobject *en)\n{\n PyObject *next_index;\n PyObject *next_item;\n PyObject *result = en->en_result;\n PyObject *it = en->en_sit;\n\n next_item = (*... | [
5,
1
] | [] | [] | [
"enumerate",
"list",
"python"
] | stackoverflow_0005333106_enumerate_list_python.txt |
Q:
How to display a jpg file in Python?
def show():
file = raw_input("What is the name of the image file? ")
picture = Image(file)
width, height = picture.size()
pix = picture.getPixels()
I am trying to write a code to display this image but this code does not provide the image.
How to change my ... | How to display a jpg file in Python? | def show():
file = raw_input("What is the name of the image file? ")
picture = Image(file)
width, height = picture.size()
pix = picture.getPixels()
I am trying to write a code to display this image but this code does not provide the image.
How to change my code in order to display this image?
| [
"from PIL import Image\n\nimage = Image.open('File.jpg')\nimage.show()\n\n",
"Don't forget to include\nimport Image\n\nIn order to show it use this :\nImage.open('pathToFile').show()\n\n"
] | [
55,
22
] | [] | [] | [
"python"
] | stackoverflow_0005333244_python.txt |
Q:
Type checking in Python
How can I check the type of function's parameters? For example,
def hello(x):
# check if x is tuple
# check if x is dictionary.
...
EDIT
isinstance(x, type(()))
isinstance(x, type({}))
A:
You don't.
You should never be unsure of the type of a thing in python; it's basically imp... | Type checking in Python | How can I check the type of function's parameters? For example,
def hello(x):
# check if x is tuple
# check if x is dictionary.
...
EDIT
isinstance(x, type(()))
isinstance(x, type({}))
| [
"You don't.\nYou should never be unsure of the type of a thing in python; it's basically impossible to check accurately. While it is possible to do some naïve surface-level checking, the problem is that python is very flexible. Your function shouldn't care if it's passed a dict or something that behaves exactly lik... | [
7,
5,
2
] | [] | [] | [
"python",
"types"
] | stackoverflow_0005333080_python_types.txt |
Q:
Why is this not a fixed width pattern?
I'm trying to split English sentences correctly, and I came up with the unholy regex below:
(?<!\d|([A-Z]\.)|(\.[a-z]\.)|(\.\.\.)|etc\.|[Pp]rof\.|[Dd]r\.|[Mm]rs\.|[Mm]s\.|[Mm]z\.|[Mm]me\.)(?<=([\.!?])|(?<=([\.!?][\'\"])))[\s]+?(?=[\S])'
The problem is, Python keeps raising t... | Why is this not a fixed width pattern? | I'm trying to split English sentences correctly, and I came up with the unholy regex below:
(?<!\d|([A-Z]\.)|(\.[a-z]\.)|(\.\.\.)|etc\.|[Pp]rof\.|[Dd]r\.|[Mm]rs\.|[Mm]s\.|[Mm]z\.|[Mm]me\.)(?<=([\.!?])|(?<=([\.!?][\'\"])))[\s]+?(?=[\S])'
The problem is, Python keeps raising the following error:
Traceback (most recent ... | [
"Consider this subexpression:\n(?<=([\\.!?])|(?<=([\\.!?][\\'\\\"])))\n\nThe left side of the | is one character, while the right size is zero. You have the same issue in your larger negative look-behind too, it could be 1, 2, 3, 4, or 5 characters.\nLogically, a negative look-behind of (?<!A|B|C) should be equival... | [
13,
1
] | [
"It looks like you might be using the repeat chacters near the end:\n[\\s]+?\n\nUnless I'm reading that wrong.\nUPDATE\nOr vertical bar as nightcracker mentioned, and the first answer to this question seems to confirm: determine if regular expression only matches fixed-length strings\n"
] | [
-1
] | [
"python",
"regex"
] | stackoverflow_0005333200_python_regex.txt |
Q:
Python lxml XPath problem
I'm trying to print/save a certain element's HTML from a web-page.
I've retrieved the requested element's XPath from firebug.
All I wish is to save this element to a file.
I don't seem to succeed in doing so.
(tried the XPath with and without a /text() at the end)
I would appreciate any ... | Python lxml XPath problem | I'm trying to print/save a certain element's HTML from a web-page.
I've retrieved the requested element's XPath from firebug.
All I wish is to save this element to a file.
I don't seem to succeed in doing so.
(tried the XPath with and without a /text() at the end)
I would appreciate any help, or past experience.
10x, ... | [
"Your XPath is obviously a bit too long, why don't you try shorter ones and see if they match. One problem might be \"tbody\" which gets automatically created in the DOM by browsers but the HTML markup usually does not contain it.\nHere's an example of how to use XPath results:\n>>> from lxml import etree\n>>> from... | [
11,
0
] | [] | [] | [
"lxml",
"python",
"xpath"
] | stackoverflow_0005333236_lxml_python_xpath.txt |
Q:
Error passing Tuple as 'To' param in Django EmailMessage
I am getting the following error when trying to send an email message where I give the 'To' parameter a tuple of email addresses.
> TypeError: sequence item 0: expected
> string, tuple found
I have looked at the Django documentation for the EmailMessage cla... | Error passing Tuple as 'To' param in Django EmailMessage | I am getting the following error when trying to send an email message where I give the 'To' parameter a tuple of email addresses.
> TypeError: sequence item 0: expected
> string, tuple found
I have looked at the Django documentation for the EmailMessage class and it indicates this should be fine. Anyone have any sugge... | [
"Send HTML email example\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.utils.html import strip_tags\n\nsubject = render_to_string('cart/email/order_subject.txt',c)\nhtml_body = t.render(Context(c))\ntext_body = strip_tags(html_body)\n\nmsg = EmailMultiAlternatives(subject, text_body, None, sc.se... | [
0,
0
] | [] | [] | [
"django",
"email",
"python",
"typeerror"
] | stackoverflow_0004854264_django_email_python_typeerror.txt |
Q:
Django won't eat quicktime objects
Django (1.2.5) won't play *.mov files, however it does take flv and mp4 files.. anything special about quicktime objects?
It says access denied or file not found, file is on the right path other file types work perfectly, the absolute domain does play the movie (its embedded in J... | Django won't eat quicktime objects | Django (1.2.5) won't play *.mov files, however it does take flv and mp4 files.. anything special about quicktime objects?
It says access denied or file not found, file is on the right path other file types work perfectly, the absolute domain does play the movie (its embedded in JW player on the site, who state they sup... | [
"If you're doing things the right way, Django doesn't serve movie files, the web server (apache, nginx, cherokee, etc.) serve them. So the problem is probably on the side of your web server's configuration.\n",
"Are you sure the static files serving has been correctly configured? From the djangoproject file:\n`(r... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005330167_django_python.txt |
Q:
How to sub with matched groups and variables in Python
new to python. This is probably simple but I haven't found an answer.
rndStr = "20101215"
rndStr2 = "20101216"
str = "Looking at dates between 20110316 and 20110317"
outstr = re.sub("(.+)([0-9]{8})(.+)([0-9]{8})",r'\1'+rndStr+r'\2'+rndStr2,str)
The output I'... | How to sub with matched groups and variables in Python | new to python. This is probably simple but I haven't found an answer.
rndStr = "20101215"
rndStr2 = "20101216"
str = "Looking at dates between 20110316 and 20110317"
outstr = re.sub("(.+)([0-9]{8})(.+)([0-9]{8})",r'\1'+rndStr+r'\2'+rndStr2,str)
The output I'm looking for is:
Looking at dates between 20101215 and 20... | [
"Your backreferences are ambiguous. Your replacement string becomes\n\\120101215\\220101216\n\nwhich is two rather large numbers to be backreferencing :)\nTo solve it, use this syntax:\nr'\\g<1>'+rndStr+r'\\g<2>'+rndStr2 \n\nYou also have too many sets of parentheses (or \"brackets\" if you speak British English l... | [
27,
3
] | [
"rndStr = \"20101215\"\nrndStr2 = \"20101216\"\nmys = \"Looking at dates between {0} and {1}\".format(rndStr, rndStr2)\n\nPlease do not use str as a variable name; it overwrites the built-in str type.\n",
"rndStr = \"20101215\"\nrndStr2 = \"20101216\"\n\nprint \"Looking at dates between %s and %s\" %(rndStr,rndSt... | [
-1,
-1
] | [
"python",
"regex"
] | stackoverflow_0005331985_python_regex.txt |
Q:
Python: recursive way to subtract from class attributes?
I have a class with many attributes, and when I give a number, I would like it to subtract that from one attribute, but if the amount is greater than the attribute subtracted from, move to the next attribute with what is left over. Example:
def subt(self, am... | Python: recursive way to subtract from class attributes? | I have a class with many attributes, and when I give a number, I would like it to subtract that from one attribute, but if the amount is greater than the attribute subtracted from, move to the next attribute with what is left over. Example:
def subt(self, amount):
self.attr1 += amount
if self.attr1 < 0:
... | [
"You can access the attributes using .__dict__ You need a list for the order you want to subtract. Something like this works.\nclass A():\n def __init__(self):\n self.foo = 100\n self.bar = 200\n self.baz = 300\n self.sub_stack = ['foo', 'baz', 'bar']\n\n def subt(self, amount):\n ... | [
4,
0,
0
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0005333515_python_recursion.txt |
Q:
best way to create a dict like {0:0,1:1,2:2} using python
this is my code :
print dict(range(3),range(3))
but it show error :
Traceback (most recent call last):
File "c.py", line 7, in <module>
print dict(range(3),range(3))
TypeError: dict expected at most 1 arguments, got 2
what can i do ,
thanks
A:
You... | best way to create a dict like {0:0,1:1,2:2} using python | this is my code :
print dict(range(3),range(3))
but it show error :
Traceback (most recent call last):
File "c.py", line 7, in <module>
print dict(range(3),range(3))
TypeError: dict expected at most 1 arguments, got 2
what can i do ,
thanks
| [
"You could use a dictionary comprehension which works in Python 2.7 or newer:\n{ i: i for i in range(3) }\n\nOr for older versions of Python you can do this:\ndict((i, i) for i in range(3))\n\n",
"This should work\n dict(zip(range(3),range(3)))\n\n",
"A longer but easy to understand way: \nd={}\nfor x in ran... | [
5,
3,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0005333870_dictionary_python.txt |
Q:
Column Name as Variable in PostgreSql Query
i was trying to update a table row by row in postgresql using python.
the code used was
cursor.execute("UPDATE im_entry.pr_table
SET selected_entry = im_entry.usr_table.",entryn,"
FROM im_entry.usr_table
WHERE im_... | Column Name as Variable in PostgreSql Query | i was trying to update a table row by row in postgresql using python.
the code used was
cursor.execute("UPDATE im_entry.pr_table
SET selected_entry = im_entry.usr_table.",entryn,"
FROM im_entry.usr_table
WHERE im_entry.pr_table.image_1d = ",idn,"")
...where ent... | [
"You can't bind table or column names, only the values associated with them.\n",
"Try:\ncursor.execute(\n '''UPDATE im_entry.pr_table \n SET selected_entry = im_entry.usr_table.{0}\n FROM im_entry.usr_table \n WHERE im_entry.pr_table.image_1d = ?'''.format(entryn),[idn])\n\nNormally, you wou... | [
0,
0
] | [] | [] | [
"postgresql",
"python",
"sql"
] | stackoverflow_0005334212_postgresql_python_sql.txt |
Q:
Convert 64bit hex to Windows datetime
I need to convert a windows hex 64 bit (big endian) date time to something readable in python?
example 'abaaaaaaccd3e340'
converts to "Tue, 29 June 2010 09:47:42 UTC"
Any help would be appreciated.
A:
http://code.activestate.com/recipes/303344-converting-windows-64-bit-time-... | Convert 64bit hex to Windows datetime | I need to convert a windows hex 64 bit (big endian) date time to something readable in python?
example 'abaaaaaaccd3e340'
converts to "Tue, 29 June 2010 09:47:42 UTC"
Any help would be appreciated.
| [
"http://code.activestate.com/recipes/303344-converting-windows-64-bit-time-to-python-useable-f/\nThis might help...\n",
"Looks word-for-word like this question, but your example number is different, although the date/time is exactly the same.\n"
] | [
1,
0
] | [] | [] | [
"c#",
"hex",
"python"
] | stackoverflow_0005333376_c#_hex_python.txt |
Q:
Sound properties manipulation in python
I am searching for a lib that helps me to use many sound properties.
I mean, I need something to get each frequency of sounds, get the sound waves length and width, get the peak and trough (in a measurement way) of the sounds.
I need something that leads me as close as poss... | Sound properties manipulation in python | I am searching for a lib that helps me to use many sound properties.
I mean, I need something to get each frequency of sounds, get the sound waves length and width, get the peak and trough (in a measurement way) of the sounds.
I need something that leads me as close as possible to manipulate and measure sounds waves i... | [
"The Python wiki page PythonInMusic has a lot of links, some of which will probably be useful to you. It includes a whole range of projects to input and output sound in different formats. A quick glance shows a couple of more specialised projects that might also be helpful:\n\naudiolab - bridges the gap between num... | [
1
] | [] | [] | [
"audio",
"python",
"scientific_computing"
] | stackoverflow_0005334247_audio_python_scientific_computing.txt |
Q:
Python - How to detect when user closes a console application via "X" button
I currently have a Console based python program running under windows. The program maintains most of its data in memory and periodically saves the data to disk, or when the user shuts the application down via a Keyboard interrupt (Ctrl + ... | Python - How to detect when user closes a console application via "X" button | I currently have a Console based python program running under windows. The program maintains most of its data in memory and periodically saves the data to disk, or when the user shuts the application down via a Keyboard interrupt (Ctrl + C) event.
The problem i have is that when a user hits the "X" button at the top ri... | [
"In windows\nif you are using pywin32, you can perform an event before the console is closed, I'm not sure this will tell you who or what is closing it, but maybe this gets you half way.\nYou might also want to check out: Prevent a console app from closing ...\ndef on_exit(signal_type):\n print('caught signal:', ... | [
7
] | [] | [] | [
"application_shutdown",
"console",
"python",
"signals"
] | stackoverflow_0005334614_application_shutdown_console_python_signals.txt |
Q:
python list/dict property best practice
I have a class object that stores some properties that are lists of other objects. Each of the items in the list has an identifier that can be accessed with the id property. I'd like to be able to read and write from these lists but also be able to access a dictionary keyed ... | python list/dict property best practice | I have a class object that stores some properties that are lists of other objects. Each of the items in the list has an identifier that can be accessed with the id property. I'd like to be able to read and write from these lists but also be able to access a dictionary keyed by their identifier. Let me illustrate with a... | [
"An indexed list class:\nclass IndexedList(list):\n def __init__(self, items, attrs):\n super(IndexedList,self).__init__(items)\n # do indexing\n self._attrs = tuple(attrs)\n self._index = {}\n _add = self._addindex\n for obj in self:\n _add(obj)\n\n def _a... | [
3,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005332841_python.txt |
Q:
Python loop problems
I have a script that counts the number of files in a folder, and if it's less than a max number, it creates new files until there is the correct number. Ideally, as old files are deleted, the new ones should be generated. The problem is, my code sometimes wont create a new file if only one fil... | Python loop problems | I have a script that counts the number of files in a folder, and if it's less than a max number, it creates new files until there is the correct number. Ideally, as old files are deleted, the new ones should be generated. The problem is, my code sometimes wont create a new file if only one file is deleted at a time. So... | [
"Seems like a race condition between the file being created and the file showing up in os.listdir() output. The print statement probably takes just enough time to \"fix\" this on your system, most of the time.\nWhy not change your logic so that it only calls getCount() once, then creates the appropriate amount of f... | [
2
] | [] | [] | [
"function",
"loops",
"python"
] | stackoverflow_0005334915_function_loops_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.