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:
Use python to connect to a php page and upload image
I would like to know if its possible to use python to connect to a certain site
(EX: http://www.example.com/python )
and upload an image from the computer.
Basically I have a python script that takes images from the webcam. Now after it takes the image how can ... | Use python to connect to a php page and upload image | I would like to know if its possible to use python to connect to a certain site
(EX: http://www.example.com/python )
and upload an image from the computer.
Basically I have a python script that takes images from the webcam. Now after it takes the image how can i send that image to a webpage. If you tell me how to get ... | [
"Use urllib2 for this. Basically build up a urllib2.Request with the URL to the PHP script, and then add_data to add the image data that you want to submit.\nedit: you can follow the examples here, and specifically this example to help understand the full process\n",
"I advice you to learn \"mechanize\" library ... | [
2,
1,
0
] | [] | [] | [
"ftp",
"php",
"python"
] | stackoverflow_0004866890_ftp_php_python.txt |
Q:
Is there a widely used STOMP adapter for Twisted?
I checked out stomper and it didn't look complete. (I'm very new to Python) Is anybody out there using stomper in a production environment?
If not, I guess I'll have to roll out my own Twisted Stomp adapter.
Thanks in advance!
A:
There is a python library called ... | Is there a widely used STOMP adapter for Twisted? | I checked out stomper and it didn't look complete. (I'm very new to Python) Is anybody out there using stomper in a production environment?
If not, I guess I'll have to roll out my own Twisted Stomp adapter.
Thanks in advance!
| [
"There is a python library called stomper which I've used in the past with twisted (it comes with twisted example code). Disclaimer, I've worked on the code for stomper so I like it :)\nThese days I've moved away from stomp/ActiveMQ towards AMQP + RabbitMQ, using the txAMQP and py-amqplib libraries. I've found rabb... | [
7,
1,
1
] | [] | [] | [
"activemq",
"python",
"stomp",
"twisted"
] | stackoverflow_0000506594_activemq_python_stomp_twisted.txt |
Q:
Python won't eval() code
I have the following eval() thing:
c = Customer()
eval("c.name = row.value('customer', '{c}')".format(c=column_name), { 'c': c, 'row': row})
When I try to run that, I get this:
Traceback (most recent call last):
File "./import.py", line 19, in <module>
c = Customer.save_from_row(row... | Python won't eval() code | I have the following eval() thing:
c = Customer()
eval("c.name = row.value('customer', '{c}')".format(c=column_name), { 'c': c, 'row': row})
When I try to run that, I get this:
Traceback (most recent call last):
File "./import.py", line 19, in <module>
c = Customer.save_from_row(row)
File "/home/jason/projects... | [
"eval evaluates expressions. Assignment is a statement, not an expression.\nAnd don't even get me started on how easily misused and - in 99.99% of all cases - utterly unnecesary eval is. Just refer to the numerous other eval questions, I bet each has at least one such rant in an answer or comment - so I'll save my ... | [
11,
2
] | [] | [] | [
"python"
] | stackoverflow_0004867101_python.txt |
Q:
Counting collisions in a Python dictionary
my first time posting here, so hope I've asked my question in the right sort of way,
After adding an element to a Python dictionary, is it possible to get Python to tell you if adding that element caused a collision? (And how many locations the collision resolution strate... | Counting collisions in a Python dictionary | my first time posting here, so hope I've asked my question in the right sort of way,
After adding an element to a Python dictionary, is it possible to get Python to tell you if adding that element caused a collision? (And how many locations the collision resolution strategy probed before finding a place to put the elem... | [
"Short answer:\nYou can't simulate using object ids as dict keys by using random integers as dict keys. They have different hash functions.\nCollisions do happen. \"Having unique thingies means no collisions\" is wrong for several values of \"thingy\".\nYou shouldn't be worrying about collisions.\nLong answer:\nSom... | [
10,
5
] | [] | [] | [
"dictionary",
"optimization",
"python"
] | stackoverflow_0004865325_dictionary_optimization_python.txt |
Q:
Does the 'in' clause used on python dictionaries call the keys() function every time?
Let's say I have a
dict = {...} #lots of words in dictionary
I have to do a
for word in ...: #long list of words
if word in dict:
#do something
My question is, does the 'if word in dict' call the dict.keys() f... | Does the 'in' clause used on python dictionaries call the keys() function every time? | Let's say I have a
dict = {...} #lots of words in dictionary
I have to do a
for word in ...: #long list of words
if word in dict:
#do something
My question is, does the 'if word in dict' call the dict.keys() function every time and hence a lot slower than if I added another variable at the top that ... | [
"no. foo in mydict is in fact a lot faster than foo in keys_list, since dicts are hash tables, so finding the element inside it is O(1). While foo in keys_list would be O(n) (slower as the number of keys grows bigger)\nBut you could always test yourself:\n$ python -m timeit -s \"x = range(1000)\" \"15 in x\"\n10000... | [
11,
5,
2,
2,
1
] | [] | [] | [
"dictionary",
"optimization",
"python"
] | stackoverflow_0004867341_dictionary_optimization_python.txt |
Q:
Make all Django models inherit from certain class
I wrote a certain function that I'd like all my Django models to have. What's the best way to make all my models inherit from a certain class?
What I tried didn't work. I made a new class like this:
from django.db import models
class McifModel(models.Model):
p... | Make all Django models inherit from certain class | I wrote a certain function that I'd like all my Django models to have. What's the best way to make all my models inherit from a certain class?
What I tried didn't work. I made a new class like this:
from django.db import models
class McifModel(models.Model):
pass
And then I did this in another model:
from django.... | [
"Because you didn't import mcif -- you imported McifModel. Try this:\nfrom mcif.models.mcif_model import McifModel\n\nclass Customer(McifModel):\n ...\n\n"
] | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004867675_django_python.txt |
Q:
See class methods in Python console
If I'm dealing with an object in the Python console, is there a way to see what methods are available for that class?
A:
If by class, you actually meant the instance you have, you can simply use dir:
a = list()
print dir(a)
If you really meant to see the methods of the class ... | See class methods in Python console | If I'm dealing with an object in the Python console, is there a way to see what methods are available for that class?
| [
"If by class, you actually meant the instance you have, you can simply use dir:\na = list()\nprint dir(a)\n\nIf you really meant to see the methods of the class of your object:\na = list()\nprint dir(a.__class__)\n\nNote that in that case, both would print the same results, but python being quite dynamic, you can i... | [
9,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004863281_python.txt |
Q:
where in class hierarchy should instance methods be written?
Here's a part of a class "hierarchy" that I use for a simulation model (my code is in Python, but I think my question isn't language dependent):
class World:
# highest-level class, which "knows" everything about the model
# most likely will have just one... | where in class hierarchy should instance methods be written? | Here's a part of a class "hierarchy" that I use for a simulation model (my code is in Python, but I think my question isn't language dependent):
class World:
# highest-level class, which "knows" everything about the model
# most likely will have just one instance
# contains (e.g., in a dictionary) references to all the... | [
"The thing that you need to take into account is the Single Responsibility Principle. Basically, each class should be responsible for one \"thing\", and should completely encapsulate that one responsibility. And you should only inherit where the responsibility is extended. You should always be able to say that t... | [
3,
1,
1,
0,
0
] | [] | [] | [
"language_agnostic",
"oop",
"python",
"software_design"
] | stackoverflow_0004860686_language_agnostic_oop_python_software_design.txt |
Q:
How to manage dependency when cloning repository?
I am using mercurial and I am wondering how to do the following.
Here is my repository architecture :
./repo/utils/workers/[...]
./repo/utils/tools/[...]
./repo/proj1/file.py
Let's say that in proj1/file.py I need to import some code located in workers and tools.... | How to manage dependency when cloning repository? | I am using mercurial and I am wondering how to do the following.
Here is my repository architecture :
./repo/utils/workers/[...]
./repo/utils/tools/[...]
./repo/proj1/file.py
Let's say that in proj1/file.py I need to import some code located in workers and tools. eg
from utils.workers import foo
from utils.tools impo... | [
"You should look at subrepositories (which also called nested)\n",
"The best solution I've found to to this, is by using buildout.\nhttp://www.buildout.org\nIt is a really helpful solution to manage dependencies.\n"
] | [
0,
0
] | [] | [] | [
"distutils",
"mercurial",
"python",
"repository",
"repository_pattern"
] | stackoverflow_0004765629_distutils_mercurial_python_repository_repository_pattern.txt |
Q:
How can you obtain the OS's argv[0] (not sys.argv[0]) in Python?
I want to obtain the true value of the operating system's argv[0] in a Python program. Python's sys.argv[0] is not this value: it is the name of the Python script being executed (with some exceptions). What I want is a foo.py that will print "somestr... | How can you obtain the OS's argv[0] (not sys.argv[0]) in Python? | I want to obtain the true value of the operating system's argv[0] in a Python program. Python's sys.argv[0] is not this value: it is the name of the Python script being executed (with some exceptions). What I want is a foo.py that will print "somestring" when executed as
exec -a "somestring" python foo.py
The trivial ... | [
"On Linux you can read the contents of /proc/self/cmdline:\n#!/usr/bin/env python\nimport sys\nprint sys.argv[0]\n\nf = open('/proc/self/cmdline', 'rb')\ncmdline = f.read()\nf.close()\n\nprint repr(cmdline.split('\\x00'))\n\nAnd the output is:\n$ bash\n$ exec -a \"somestring\" python foo.py \nfoo.py\n['somestring',... | [
7
] | [] | [] | [
"python"
] | stackoverflow_0004867761_python.txt |
Q:
QPoint for context menu position
I generate these i buttons:
self.connect(self.ui.pushButton_i, QtCore.SIGNAL('customContextMenuRequested(const QPoint)'), self.on_context_menu)
The buttons are paced in a gridLayout. The position of the contextMenu horizontal is OK but the vertical position is always on the lowest... | QPoint for context menu position | I generate these i buttons:
self.connect(self.ui.pushButton_i, QtCore.SIGNAL('customContextMenuRequested(const QPoint)'), self.on_context_menu)
The buttons are paced in a gridLayout. The position of the contextMenu horizontal is OK but the vertical position is always on the lowest of the buttons.
How can I make sure t... | [
"What I did is to ask the object that creates the contextMenu to map the mouse coordinate to a global coordinate:\n self.editorContextMenu.exec_(self.confEditorTree.mapToGlobal(point))\n\nHere editorContextMenu being the the contextMenu itself and self.confEditorTree being the thing that was clicked on. So in ... | [
1
] | [] | [] | [
"contextmenu",
"pyqt",
"python"
] | stackoverflow_0004867694_contextmenu_pyqt_python.txt |
Q:
Python socket.send() is not sent until socket is closed
I'm building an IRC bot in Python for fun. It is supposed to accept commands prefixed with '!' and act on them. The function below is used to parse commands received in an IRC message.
def parse_cmd(self, sender):
#Admin Commands
if sender == self.own... | Python socket.send() is not sent until socket is closed | I'm building an IRC bot in Python for fun. It is supposed to accept commands prefixed with '!' and act on them. The function below is used to parse commands received in an IRC message.
def parse_cmd(self, sender):
#Admin Commands
if sender == self.owner:
if self.command == 'quit':
send_bufr ... | [
"In his comment on my question, Winston Ewert was correct. The socket.send should have read:\nsend_bufr = \"PRIVMSG %s :Hello %s\\r\\n\" %(self.channel, sender)\nprint(send_bufr)\nself.sock.send(bytearray(send_bufr, \"utf-8\"))\n\nA dumb mistake on my part to leave out the terminator. Thanks to everyone who helped.... | [
1,
0
] | [] | [] | [
"irc",
"python",
"sockets"
] | stackoverflow_0004867833_irc_python_sockets.txt |
Q:
Python: Appending dimensions to a bidimensional array
Suppose you have an array (m, m) and want to make it (n, n). For example, transforming a 2x2 matrix to a 6x6. So:
[[ 1. 2.]
[ 3. 4.]]
To:
[[ 1. 2. 0. 0. 0. 0.]
[ 3. 4. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0.]
[ 0. 0. ... | Python: Appending dimensions to a bidimensional array | Suppose you have an array (m, m) and want to make it (n, n). For example, transforming a 2x2 matrix to a 6x6. So:
[[ 1. 2.]
[ 3. 4.]]
To:
[[ 1. 2. 0. 0. 0. 0.]
[ 3. 4. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0.]]
This is what I... | [
"Why not use array = numpy.zeros((6,6)), see the numpy docs...\nEDIT, woops, question has been edited... I guess you are trying to put ones in a section of an array filled with zeros? Then:\narray = numpy.zeros((6,6))\narray[0:2,0:2] = 1\n\nIf the small matrix does not all have the value of 1:\narray[ystart:yend,xs... | [
3,
1
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0004867918_arrays_numpy_python.txt |
Q:
Is there something equivalent to django's managers in SQLAlchemy?
I have some SQLAlchemy models (Declarative) and some queries to write like:
Mymodel.query.filter(Mymodel.myfield=='lambda')
Since I have to use the above query several times in my code I would like to do better than repeating it over and over. I ... | Is there something equivalent to django's managers in SQLAlchemy? | I have some SQLAlchemy models (Declarative) and some queries to write like:
Mymodel.query.filter(Mymodel.myfield=='lambda')
Since I have to use the above query several times in my code I would like to do better than repeating it over and over. I know that in django you can do it by putting managers in your models.
I... | [
"For common queries I add a class method to a mapped (ORM) class. \nFor example:\nclass User(object):\n\n @classmethod\n def get_by_username(cls, dbsession, username):\n return dbsession.query(cls).filter(cls.username==username).one()\n\nThe mapped class is essentially the manager. \n",
"What I end u... | [
11,
1
] | [] | [] | [
"django_models",
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0004866489_django_models_orm_python_sqlalchemy.txt |
Q:
how do I get email_re from django to work within a python webapp project in google app engine?
When I import it inside a handler with this:
from django.core.validators import email_re
I get the following error when I run the app:
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine... | how do I get email_re from django to work within a python webapp project in google app engine? | When I import it inside a handler with this:
from django.core.validators import email_re
I get the following error when I run the app:
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django/django/conf/__init__.py", line 53, in... | [
"Try using following lines of code after your imports:\nfrom django.conf import settings \nsettings.configure()\n\nRead here for more info: http://groups.google.com/group/tipfy/browse_thread/thread/78c17b4f82c894a6\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"python",
"web_applications"
] | stackoverflow_0004868139_google_app_engine_python_web_applications.txt |
Q:
Django Forms: How to edit fields that aren't on the model itself
I have two models, Foo and Bar. Bar has a foreign key to Foo. From the Django Admin interface, I'd like to let the user edit the list of Bar instances that are linked to Foo.
My idea for how to do this would be to include javascript in the form, whic... | Django Forms: How to edit fields that aren't on the model itself | I have two models, Foo and Bar. Bar has a foreign key to Foo. From the Django Admin interface, I'd like to let the user edit the list of Bar instances that are linked to Foo.
My idea for how to do this would be to include javascript in the form, which would make a list populated by query calls back to the server. When ... | [
"This feature is already catered for in the Django admin application.\nYou just need to create an InlineModelAdmin for your class.\nhttp://docs.djangoproject.com/en/1.2/ref/contrib/admin/#inlinemodeladmin-objects\n"
] | [
3
] | [] | [] | [
"django",
"django_admin",
"javascript",
"python"
] | stackoverflow_0004868299_django_django_admin_javascript_python.txt |
Q:
how to bold csv data in excel?
I work on a python(django) project. I write csv code as follows,
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=DueDateWiseSearch.csv'
writer = csv.writer(response)
writer.writerow(['Infant Name','Mother Name','Mother... | how to bold csv data in excel? | I work on a python(django) project. I write csv code as follows,
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=DueDateWiseSearch.csv'
writer = csv.writer(response)
writer.writerow(['Infant Name','Mother Name','Mother Address',
'Next Vaccine Dose',... | [
"There's no way to do that in CSV. You could all caps the output, or you could use another format that supports text styles. \n",
"CSV only contains data, it doesn't contain any formatting information. If you need to format your data, I'd suggest actually creating an XLS file instead of a CSV file. Try using so... | [
24,
6,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003749020_python.txt |
Q:
Retrieve multiple xml items in a loop with elementtree
I'm trying to loop over an xml file with elementtree. The file looks a bit like this:
<items>
<item>
<name>Blah</name>
<price>1234</price>
</item>
<item>
<name>Something</name>
<price>2345</price>
</item>
</items>
After reading this wi... | Retrieve multiple xml items in a loop with elementtree | I'm trying to loop over an xml file with elementtree. The file looks a bit like this:
<items>
<item>
<name>Blah</name>
<price>1234</price>
</item>
<item>
<name>Something</name>
<price>2345</price>
</item>
</items>
After reading this with elementtree, I can do this:
for element in doc.findall('/... | [
"Please read the documentation(http://docs.python.org/library/xml.etree.elementtree.html). Here is a working example:\nfor elem in doc.findall('item'):\n for i in elem.getchildren():\n print i.text\n\noutputs:\n\nBlah \n 1234 \n Something\n 2345\n\nIn my code I iterate over all the items in the xml and r... | [
4,
2
] | [] | [] | [
"elementtree",
"python"
] | stackoverflow_0004868656_elementtree_python.txt |
Q:
How do I store multiple copies of the same field in Django?
I'm storing OLAC metadata which describes linguistic resources. Many of the elements of the metadata are repeatable -- for example, a resource can have two languages, three authors and four dates associated with it.
Is there any way of storing this in one... | How do I store multiple copies of the same field in Django? | I'm storing OLAC metadata which describes linguistic resources. Many of the elements of the metadata are repeatable -- for example, a resource can have two languages, three authors and four dates associated with it.
Is there any way of storing this in one model? It seems like overkill to define a model for each repeata... | [
"It sounds like the best way would be via many to many relationships, like this:\nclass author(models.Model):\n # fields?\n\nclass language(models.Model):\n iso_lang_code = models.CharField() # probably need some constraints here\n\nclass resource(models.Model):\n name = models.CharField()\n authors = m... | [
4,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004868900_django_django_models_python.txt |
Q:
How to make python autocompletion display matches?
I have kind of a completer class with an autocompletion function. Simple version:
class Completer:
def __init__(self):
self.words = ["mkdir","mktbl", "help"]
self.prefix = None
def complete(self, prefix, index):
if prefix != self.p... | How to make python autocompletion display matches? | I have kind of a completer class with an autocompletion function. Simple version:
class Completer:
def __init__(self):
self.words = ["mkdir","mktbl", "help"]
self.prefix = None
def complete(self, prefix, index):
if prefix != self.prefix:
self.matching_words = [w for w in sel... | [
"Set the readline option\nset show-all-if-ambiguous on\n\nif you want completions after the first <tab>. Otherwise just hit <tab> twice. \nReference: http://caliban.org/bash/, Section readline Tips and Tricks\nPS. Tested your code on OS X and Linux, it works well (on my machines ;)\n",
"I was suggested a solution... | [
7,
2
] | [] | [] | [
"autocomplete",
"python",
"readline"
] | stackoverflow_0004869121_autocomplete_python_readline.txt |
Q:
Passing Command line argument to Python program using IDLE?
I have downloaded a python file xxxxxx.py that is supposed to run on the command line by
typing: python xxxxxx.py filename1 filename2
and that should take these two files as arguments.
I was wondering if there is a way I can use IDLE to pass in these argu... | Passing Command line argument to Python program using IDLE? | I have downloaded a python file xxxxxx.py that is supposed to run on the command line by
typing: python xxxxxx.py filename1 filename2
and that should take these two files as arguments.
I was wondering if there is a way I can use IDLE to pass in these arguments. Is there a way other than setting sys.argv ?
Thanks
| [
"It depends on the content of your Python file. If it is well-written, like:\n#! /usr/bin/env python\n\ndef process(files):\n for file in files:\n # ...\n\nif __name__ == '__main__'\n # some error checking on sys.argv\n process(sys.argv[1:])\n sys.exit(0)\n\nThen you could simply import the python ... | [
6,
4
] | [] | [] | [
"command_line",
"command_line_arguments",
"python",
"python_idle"
] | stackoverflow_0004869490_command_line_command_line_arguments_python_python_idle.txt |
Q:
Find a strings location in a list - Python
If I have a series of lists in a dictionary (for example):
{'Name': ['Thomas', 'Steven', 'Pauly D'], 'Age': [30, 50, 29]}
and I want to find the strings position so I can then get the same position from the other list.
So e.g.
if x = 'Thomas' #is in position 2:
y = d... | Find a strings location in a list - Python | If I have a series of lists in a dictionary (for example):
{'Name': ['Thomas', 'Steven', 'Pauly D'], 'Age': [30, 50, 29]}
and I want to find the strings position so I can then get the same position from the other list.
So e.g.
if x = 'Thomas' #is in position 2:
y = dictionary['Age'][2]
| [
"Store it in the proper structure in the first place.\nD = dict(zip(dictionary['Name'], dictionary['Age']))\nprint D['Thomas']\n\n",
"i = dictionary['Name'].index('Thomas')\ny = dictionary['Age'][i]\n\nHowever, index performs a linear search, which could be slow for a large list. In other cases similar to this, ... | [
5,
2,
1,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0004869779_dictionary_list_python.txt |
Q:
E-Mail Site Admins in Django without using mail_admins()
I know this sounds kind of stupid, but as a beginner in Django (and even Python), I just want to know how I can access the email address from the ADMINS tuple, or maybe even access the admin name.
I read that tuples are semantic, kind of like lightweight str... | E-Mail Site Admins in Django without using mail_admins() | I know this sounds kind of stupid, but as a beginner in Django (and even Python), I just want to know how I can access the email address from the ADMINS tuple, or maybe even access the admin name.
I read that tuples are semantic, kind of like lightweight structs. So if that's the case, I may be able to access those sem... | [
"ADMINS is a setting. You can access it as follows:\nfrom django.conf import settings\nsettings.ADMINS\n\nFor example, to get all the email addresses as a list:\nfrom django.conf import settings\nadmin_emails = [v for k,v in settings.ADMINS]\n\nThe settings docs:\nhttp://docs.djangoproject.com/en/1.2/topics/settin... | [
8
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004869832_django_python.txt |
Q:
Python bluetooth transfer speed?
In Python, am using the LightBlue module for Bluetooth connectivity. How do I get the speed at which I am sending file to my phone from my laptop (Ubuntu)?
A:
It is not correct to say "python bluetooth speed", because Python is just a language and an execution runtime and has not... | Python bluetooth transfer speed? | In Python, am using the LightBlue module for Bluetooth connectivity. How do I get the speed at which I am sending file to my phone from my laptop (Ubuntu)?
| [
"It is not correct to say \"python bluetooth speed\", because Python is just a language and an execution runtime and has nothing to do with Bluetooth. You should tell us what Python extension are you using to work with Bluetooth? What bluetooth stack are you using? and eventually the operating system?\nWith lightbl... | [
0,
0
] | [
"You need a binding for the Bluetooth driver/OS service that handles the Bluetooth device.\nMost drivers are written in C, some in C++. If you can get the source code/API or if it's provided you might be able to access it from python. You might need to code some custom binding to your OS service to do so.\n"
] | [
-1
] | [
"bluetooth",
"python"
] | stackoverflow_0004863727_bluetooth_python.txt |
Q:
Is there anything like Lisp's SLIME for Python/Django?
I know about the Django console and it's useful to an extent but it would be really nice to be able to edit your code with the console open, lime SLIME in Emacs. Is there anything that facilitates this for Django or, failing that, at least Python?
A:
I do no... | Is there anything like Lisp's SLIME for Python/Django? | I know about the Django console and it's useful to an extent but it would be really nice to be able to edit your code with the console open, lime SLIME in Emacs. Is there anything that facilitates this for Django or, failing that, at least Python?
| [
"I do not know if this is exactly what you are looking for, but Workzeug provides a interactive debugging tool, which can be used like that. Just do a assert False and you can use the CLI as demonstrated in this screencast: http://ericholscher.com/blog/2008/sep/12/screencast-django-command-extensions/\n",
"IDLE\n... | [
2,
2,
1
] | [] | [] | [
"django",
"lisp",
"python",
"slime"
] | stackoverflow_0004868375_django_lisp_python_slime.txt |
Q:
Python Help with "from distutils.core import setup"
I keep seeing this kind of code a lot in python setup.py files.
from distutils.core import setup
setup(
name = 'SOMETHINGHERE',
version = 'SOMETHINGHERE',
py_modules = ['SOMETHINGHERE'],
author = 'S... | Python Help with "from distutils.core import setup" | I keep seeing this kind of code a lot in python setup.py files.
from distutils.core import setup
setup(
name = 'SOMETHINGHERE',
version = 'SOMETHINGHERE',
py_modules = ['SOMETHINGHERE'],
author = 'SOMETHINGHERE',
author_email = 'SOMETHINGHERE',... | [
"This is described in detail in the Distutils documentation.\nBasically setup is a function that checks which command distutils was invoked with and performs the appropriate action on the package (e.g. installing it, downloading it, building a binary distribution, etc.). The arguments provide any package-specific i... | [
3
] | [] | [] | [
"coding_style",
"distutils",
"python",
"setup.py"
] | stackoverflow_0004870121_coding_style_distutils_python_setup.py.txt |
Q:
Python: what's the gdata method for uploading an image with enabled OCR?
as demonstrated on this PHP code, (http://code.google.com/p/gdata-samples/source/browse/trunk/doclist/OCRDemo/ocr.php?r=194 )
where an image can be uploaded to google docs that is automatically converted to text. i'm wondering how to do this ... | Python: what's the gdata method for uploading an image with enabled OCR? | as demonstrated on this PHP code, (http://code.google.com/p/gdata-samples/source/browse/trunk/doclist/OCRDemo/ocr.php?r=194 )
where an image can be uploaded to google docs that is automatically converted to text. i'm wondering how to do this in python. there is an "upload" method, but i'm just puzzled how to enable the... | [
"assuming you've started here:\nhttp://code.google.com/apis/documents/docs/3.0/developers_guide_python.html\nyou have an authenticated client object already created.\nf = open('/path/to/your/test.pdf')\nms = gdata.data.MediaSource(file_handle=f, content_type='application/pdf', content_length=os.path.getsize(f.name)... | [
2
] | [] | [] | [
"gdata_python_client",
"ocr",
"python"
] | stackoverflow_0003176274_gdata_python_client_ocr_python.txt |
Q:
convert 64 bit windows date time in python
I need to convert a windows hex 64 bit (big endian) date time to something readable in python?
example '01cb17701e9c885a'
converts to "Tue, 29 June 2010 09:47:42 UTC"
Any help would be appreciated.
A:
Looks like a Win32 FILETIME value, which:
Contains a 64-bit value re... | convert 64 bit windows date time in python | I need to convert a windows hex 64 bit (big endian) date time to something readable in python?
example '01cb17701e9c885a'
converts to "Tue, 29 June 2010 09:47:42 UTC"
Any help would be appreciated.
| [
"Looks like a Win32 FILETIME value, which:\n\nContains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC).\n\nTo convert:\nfrom datetime import datetime,timedelta\ndt = '01cb17701e9c885a'\nus = int(dt,16) / 10\nprint(datetime(1601,1,1) + timedelta(microseconds=us))\n\nOut... | [
12,
1
] | [] | [] | [
"python"
] | stackoverflow_0004869769_python.txt |
Q:
Distributing list items to variables in python
I'm fairly new to Python and I'm looking for a way to distribute items in a list into individual variables. The point of this is to display individual items as text objects in Blender. Here's what I have so far, but I know there's gotta be a more efficient way to go a... | Distributing list items to variables in python | I'm fairly new to Python and I'm looking for a way to distribute items in a list into individual variables. The point of this is to display individual items as text objects in Blender. Here's what I have so far, but I know there's gotta be a more efficient way to go about doing this.
file = open('lyrics.conf')
data = f... | [
"if you really want individual variables, at some point you have at least to do an unpacking like v1,v2,v3,v4,v5,v6,v7,v8,v9,v10 = some_list\nbut why would you want to do this? if something is a collection/list of things, it is best represented as such.\n",
"With b you already have an easily accessible list of th... | [
6,
5,
3,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004869391_python.txt |
Q:
Python 2.7.1 can't see Twisted
I have a new MacBook Pro running OS X 10.6.6 / Snow Leopard -- which ships with Python 2.6, although I have installed 2.7.1
Unfortunately, this doesn't seem to see the Twisted install in the 2.6/Extras/lib/python/twisted directory, as I find I'm unable to import modules that I can se... | Python 2.7.1 can't see Twisted | I have a new MacBook Pro running OS X 10.6.6 / Snow Leopard -- which ships with Python 2.6, although I have installed 2.7.1
Unfortunately, this doesn't seem to see the Twisted install in the 2.6/Extras/lib/python/twisted directory, as I find I'm unable to import modules that I can see are present in that directory.
"wh... | [
"You'll have to install twisted using python 2.7.\nAlso, python doesn't look up what's in the PATH variable for imports, it looks in PYTHONPATH. But just putting your python 2.6 folder in your pythonpath isn't a very good solution.\n",
"You'll need to install Twisted into your Python 2.7 installation somehow. Th... | [
3,
3,
2,
1
] | [] | [] | [
"bash",
"osx_snow_leopard",
"python",
"twisted"
] | stackoverflow_0004869315_bash_osx_snow_leopard_python_twisted.txt |
Q:
Running a Twisted Application in PyDev
I would like to debug a Twisted Application (10.0.0) using the Eclipse (3.5.2) PyDev Module (1.6.4) and Python (2.6.5). To run the application from the command line I would specify the following:
c:\python26\python c:\python26\scripts\twistd.py -ny mytwistedapp.py
To accomp... | Running a Twisted Application in PyDev | I would like to debug a Twisted Application (10.0.0) using the Eclipse (3.5.2) PyDev Module (1.6.4) and Python (2.6.5). To run the application from the command line I would specify the following:
c:\python26\python c:\python26\scripts\twistd.py -ny mytwistedapp.py
To accomplish this using PyDev I created a new PyDev ... | [
"First off, thank you all so much for your kind and gracious support in this matter!\nThe key to running a twisted application via the PyDev module of Eclipse is to define twistd.py as the Main Module in the Run Configuration. The following steps can be used:\nThese instructions assume you can already run twisted a... | [
3
] | [] | [] | [
"eclipse",
"pydev",
"python",
"twisted.application"
] | stackoverflow_0004794707_eclipse_pydev_python_twisted.application.txt |
Q:
Drag and Drop in PyQt
I'm new to PyQt and I have a problem, search de google, PyQt docs, Mr.
Summerfield's book, but
was unable to find a way of sort it.
I have a QListWidget and a QTableWidget all have the drag and drop enable,
I use this example:
http://zetcode.com/tutorials/pyqt4/dragdrop/
it works fine becau... | Drag and Drop in PyQt | I'm new to PyQt and I have a problem, search de google, PyQt docs, Mr.
Summerfield's book, but
was unable to find a way of sort it.
I have a QListWidget and a QTableWidget all have the drag and drop enable,
I use this example:
http://zetcode.com/tutorials/pyqt4/dragdrop/
it works fine because the text in the ListWidg... | [
"I don't quite understand your question, but I'm assuming you want to select, or highlight the item after it's been dropped? Anyhow, this will get you the QTableWidgetItem thats been dropped so you can set focus, select it, etc\nIf this is the case, you'll want to do it in your drop event.\ndef dropEvent(self, e)\n... | [
2
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0004830368_pyqt_python.txt |
Q:
Django - enforcing ManyToManyField unique items
I'm trying to do something simple like this:
members = models.ManyToManyField(User, blank=True, null=True, unique=True)
but unique isn't allowed. When looking at the table created, it makes foreign keys so uniqueness is implied I imagine.
I want to be able to associ... | Django - enforcing ManyToManyField unique items | I'm trying to do something simple like this:
members = models.ManyToManyField(User, blank=True, null=True, unique=True)
but unique isn't allowed. When looking at the table created, it makes foreign keys so uniqueness is implied I imagine.
I want to be able to associate members with this model representing a group. Th... | [
"For one, I wouldn't use num_members. Instead, you can check how many members there are with mygroup.members.count(). Secondly, adding members more than once doesn't really add them more than once, so you're fine.\nA ManyToManyField on Group for member pointing to User is implemented with a separate table (somethin... | [
41,
16
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004870935_django_django_models_python.txt |
Q:
In Django's "login" built in app, how do I make it redirect to the home page when the user is already logged in?
(r'^login/?$',login,{'template_name':'login.html', 'authentication_form':CustomAuthenticationForm}),
Right now, I do this. I utilize Django's login system.
But, when I'm logged in, it still redirects m... | In Django's "login" built in app, how do I make it redirect to the home page when the user is already logged in? | (r'^login/?$',login,{'template_name':'login.html', 'authentication_form':CustomAuthenticationForm}),
Right now, I do this. I utilize Django's login system.
But, when I'm logged in, it still redirects me to the login page.
| [
"Usually, you don't ever go to the login page. Ever.\nYou use the @login_required decorator on each relevant view function.\nThe decorator redirects to the login page, then redirects back to the originally requested page. \nThere's no reason to ever bookmark, link to or visit the login page. \n",
"There are tw... | [
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004870403_django_python.txt |
Q:
MySQL-python Cannot connect to server
This is driving me crazy.
I have Python 2.5 and MySQL-python-1.2.3 from the .exe available here installed on Vista.
I have been making .php pages over the past few weeks and connected fine in order to test them in my browser.
$dbcnx=@mysql_connect("localhost", "root", "mypa... | MySQL-python Cannot connect to server | This is driving me crazy.
I have Python 2.5 and MySQL-python-1.2.3 from the .exe available here installed on Vista.
I have been making .php pages over the past few weeks and connected fine in order to test them in my browser.
$dbcnx=@mysql_connect("localhost", "root", "mypassword")
I have also been using mysql comm... | [
"Don't use the windows version (all my relevant experience is on Linux), but I'd be willing to bet it will work if you use 127.0.0.1 in place of localhost.\nEdit: -- a bit of explanation.\nFirstly, check the entries in mysql.user table, for the host field (although by default, you probably have three entries for ro... | [
15,
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0004871147_mysql_python.txt |
Q:
Python 3.1- Grid Simulation Conceptual issue
The goal is to treat a 1D array as a 2D grid. A second 1D array gives a list of values that need to be changed in the grid, and a third array indicates by how much.
The catch is that the values surrounding a modified value is changed also.
The example below stays as a ... | Python 3.1- Grid Simulation Conceptual issue | The goal is to treat a 1D array as a 2D grid. A second 1D array gives a list of values that need to be changed in the grid, and a third array indicates by how much.
The catch is that the values surrounding a modified value is changed also.
The example below stays as a 1D array, but makes calculations on it as if it wa... | [
"You didn't specify that you had to do it any specific way so I'm assuming you're open to suggestions.\nA completely different(and IMHO simpler) way would be to make an array of arrays:\ngrid = [[0,0,0,0,0],\n [0,0,0,2,0],\n [1,0,0,0,0],\n [0,0,0,0,0],\n [0,0,3,0,0]]\n\nTo access a locat... | [
2,
2
] | [] | [] | [
"python",
"python_3.x",
"simulation"
] | stackoverflow_0004870771_python_python_3.x_simulation.txt |
Q:
Writing files into chroot environment
I'm trying to write data to files in a chroot environment. Since I'm non-root user, they only way I can communicate with chroot is using schroot command.
Currently I'm using the following trick to write the data.
$ schroot -c chroot_session -r -d /tmp -- bash -c "echo \"$text... | Writing files into chroot environment | I'm trying to write data to files in a chroot environment. Since I'm non-root user, they only way I can communicate with chroot is using schroot command.
Currently I'm using the following trick to write the data.
$ schroot -c chroot_session -r -d /tmp -- bash -c "echo \"$text\" > file.txt"
But I'm sure this will give... | [
"Kinda hackish, but…\nc = ConfigParser.RawConfigParser()\nc.readfp(open(os.path.join('/var/lib/schroot/session', chroot_session), 'r'))\nchroot_basedir = c.get(chroot_session, 'mount-location')\nwith open(os.path.join(chroot_basedir, '/tmp/file.txt'), 'w') as fp:\n fp.write(text)\n\n\nOkay, so privileges don't l... | [
1,
0
] | [] | [] | [
"chroot",
"linux",
"python",
"shell"
] | stackoverflow_0004871401_chroot_linux_python_shell.txt |
Q:
how to control a figure/model to move in real time
good day sirs. i have a small program that reads and processes data via serial port. these data represent an airplane/vehicle's attitude/tilt. can you suggest any python libraries that will enable me to create graphics that will take the said input and move/tilt a... | how to control a figure/model to move in real time | good day sirs. i have a small program that reads and processes data via serial port. these data represent an airplane/vehicle's attitude/tilt. can you suggest any python libraries that will enable me to create graphics that will take the said input and move/tilt accordingly? the simpler the library, the better. forgive... | [
"VPython is the perfect tool for this. It's super quick and easy to make small 3D interactive moving scenes. For example, you could easily plot an arrow or two, and update them continuously with your data.\n(Of course, use PySerial, for reading from the serial port...)\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0004871526_python.txt |
Q:
How can I detect when objects of a Django model are added/deleted?
When adding or removing objects of Foo type I need to do the same calculation. How can I detect the adding/deleting of objects for Foo model? For example:
from django.db import models
class Foo(models.Model):
...
def save(self):
#d... | How can I detect when objects of a Django model are added/deleted? | When adding or removing objects of Foo type I need to do the same calculation. How can I detect the adding/deleting of objects for Foo model? For example:
from django.db import models
class Foo(models.Model):
...
def save(self):
#do some processing
def delete(self):
#do some processing
Ca... | [
"You should use Django's signals to call a particular function before or after a model is saved or deleted (and also at other times, if need be). Check out the relevant documentation here: http://docs.djangoproject.com/en/dev/topics/signals/\nIf you override the model methods, your delete() will not be invoked when... | [
5
] | [] | [] | [
"django",
"django_models",
"django_signals",
"python"
] | stackoverflow_0004871625_django_django_models_django_signals_python.txt |
Q:
PyGTK: Embed a window into another window
I want to embed a window into another window, kind of like this:
EDIT: Screenshots deleted, sorry!
That is a wingdows program and was not made with GTK tough.
I tried using plugs and sockets, but apparently I can't put a gtk.Window (a toplevel window) on a plug.
Is it po... | PyGTK: Embed a window into another window | I want to embed a window into another window, kind of like this:
EDIT: Screenshots deleted, sorry!
That is a wingdows program and was not made with GTK tough.
I tried using plugs and sockets, but apparently I can't put a gtk.Window (a toplevel window) on a plug.
Is it possible? If so, how? If not, what do you think I... | [
"gtk.Window is derived from gtk.Bin, so it can only contain one single child. This again can be used in the following way:\n\nLoad both windows (e.g. from Glade files)\nRemove the child from the second window, but save a reference to the child\nAdd the child somewhere in the first window\n\nThe second step would lo... | [
2
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0004870819_gtk_pygtk_python.txt |
Q:
What's the recommended 'design pattern' for exposing data via class variables?
I've seen quite a few modules allow people to access data using:
print blah.name
As opposed to:
print blah.get_name()
Given the name is a a static variable, it seems like a better choice to use the variable method rather than calling ... | What's the recommended 'design pattern' for exposing data via class variables? | I've seen quite a few modules allow people to access data using:
print blah.name
As opposed to:
print blah.get_name()
Given the name is a a static variable, it seems like a better choice to use the variable method rather than calling a function.
I'm wondering what the best 'design' is for implementing this myself. Fo... | [
"Python properties are designed to resolve this issue.\nProperties allow the phases blah.name, blah.name = x, and del blah.name to automatically invoke getter, setter, and deleter methods, if such methods have been defined. \n",
"I may be misunderstanding your question, but I think you're overthinking it. Unless... | [
5,
1,
1
] | [] | [] | [
"design_patterns",
"oop",
"python"
] | stackoverflow_0004871360_design_patterns_oop_python.txt |
Q:
Python error when using Asian characters through IIS
I made this very simple script to test in on browser. setdefaultlanguage was already utf-8
import sys
sys.getdefaultencoding()
f = 'ฟ'
print "Content-Type: text/plain;charset=utf-8"
print f`
The moment I added f = 'some asian text' I always get an error page wi... | Python error when using Asian characters through IIS | I made this very simple script to test in on browser. setdefaultlanguage was already utf-8
import sys
sys.getdefaultencoding()
f = 'ฟ'
print "Content-Type: text/plain;charset=utf-8"
print f`
The moment I added f = 'some asian text' I always get an error page with IIS - 502 web server received an invalid response. Howe... | [
"I believe the problem is in your output of HTTP headers. The headers are terminated by a double linefeed (usually \"\\r\\n\\r\\n\"), while you only have a single one. The web server will treat the asian character as part of the HTTP headers (where it is illegal), and thus throw an error.\n"
] | [
1
] | [] | [] | [
"iis",
"python"
] | stackoverflow_0004870772_iis_python.txt |
Q:
Understanding Python Classes, In an attempt to make Custom widgets
I'm trying to create a class called Menu, which would create a right-click menu for whichever widget is given to it. In this case self.Label.
However, when I run my program I get the following error:
Traceback (most recent call last):
File "<str... | Understanding Python Classes, In an attempt to make Custom widgets | I'm trying to create a class called Menu, which would create a right-click menu for whichever widget is given to it. In this case self.Label.
However, when I run my program I get the following error:
Traceback (most recent call last):
File "<string>", line 245, in run_nodebug
File "<module1>", line 57, in <module>... | [
"Maybe you should try inheriting from some base widget class?\n"
] | [
2
] | [] | [] | [
"class",
"python",
"tkinter",
"widget"
] | stackoverflow_0004872205_class_python_tkinter_widget.txt |
Q:
List directory file contents in a Django template
I'm just learning Python & Django. (Thanks to everyone who contributes here -- it's been an invaluable resource!)
One seemingly basic thing that I'm having trouble with is rendering a simple list of static files (say the contents of a single repository directory o... | List directory file contents in a Django template | I'm just learning Python & Django. (Thanks to everyone who contributes here -- it's been an invaluable resource!)
One seemingly basic thing that I'm having trouble with is rendering a simple list of static files (say the contents of a single repository directory on my server) as a list of downloadable links. Whether ... | [
"Something very much not like that, I reckon.\nYou'll probably need to create a function of your own inside views.py - see tutorial.\nThat function will get the file list from os.listdir into a list.\nPass that list in the context to a template and do render_to_response with a template you've written - see tutorial... | [
15
] | [] | [] | [
"django",
"django_templates",
"filesystems",
"python",
"repository"
] | stackoverflow_0004872183_django_django_templates_filesystems_python_repository.txt |
Q:
cleaning up python on ubuntu
My use case is probably not unusual. I want to use Ubuntu and the Google App Engine. The latest Ubuntu has a version of Python which is not GAE compatible so it was necessary to go back to Python 2.5.5.
After doing so, "whereis python" reveals this mess:
python: /usr/bin/python /usr/... | cleaning up python on ubuntu | My use case is probably not unusual. I want to use Ubuntu and the Google App Engine. The latest Ubuntu has a version of Python which is not GAE compatible so it was necessary to go back to Python 2.5.5.
After doing so, "whereis python" reveals this mess:
python: /usr/bin/python /usr/bin/python2.6 /etc/python /etc/pyt... | [
"Python is a very important utility used by apt and other packages on your system. I would try to undo whatever installation you did. When you reinstall python 2.5, install using the \"altinstall\" mechanism to keep python2.5 pointing to the old version:\nE.g.:\n# apt-get build-dep python\n# wget my-python-2.5.tar.... | [
3,
1,
0
] | [] | [] | [
"python",
"ubuntu"
] | stackoverflow_0004870616_python_ubuntu.txt |
Q:
Specify priority in buildout.cfg to fetch eggs
I was wondering if there was a way to specify where eggs should be fetch from first before looking at pypi.python.org/
For example :
[buildout]
find-links:
/home/eggs/
eggs =
foo
bar
If there is foo or a bar package on pypi with a version number higher t... | Specify priority in buildout.cfg to fetch eggs | I was wondering if there was a way to specify where eggs should be fetch from first before looking at pypi.python.org/
For example :
[buildout]
find-links:
/home/eggs/
eggs =
foo
bar
If there is foo or a bar package on pypi with a version number higher than my package called foo located in /home/eggs/, bu... | [
"You should pin your eggs to specific versions, that way you can control what eggs are used every single time you run the buildout:\n[buildout]\nversions = versions\n\n[versions]\nfoo = 1.0\nbar = 1.1\nspam = 1.0b2\n\nThe versions option in the [buildout] section lets you name a section that contains version pins f... | [
4
] | [] | [] | [
"buildout",
"python"
] | stackoverflow_0004868704_buildout_python.txt |
Q:
PyQt4: Stop Window from taking Focus
What I am trying to do is make an on screen keyboard.
To do this I need to stop the Program from taking focus away from other windows.
Here is the code I have that keeps the window on top.
import sys
from PyQt4 import QtGui, QtCore, Qt
class mymainwindow(QtGui.QMainWindow):
... | PyQt4: Stop Window from taking Focus | What I am trying to do is make an on screen keyboard.
To do this I need to stop the Program from taking focus away from other windows.
Here is the code I have that keeps the window on top.
import sys
from PyQt4 import QtGui, QtCore, Qt
class mymainwindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWi... | [
"Change focus policy of window and all of its contents QWidget::setFocusPolicy\n"
] | [
2
] | [] | [] | [
"pyqt4",
"python",
"qt4"
] | stackoverflow_0004871414_pyqt4_python_qt4.txt |
Q:
Python Subprocess.Popen from a thread
I'm trying to launch an 'rsync' using subprocess module and Popen inside of a thread. After I call the rsync I need to read the output as well. I'm using the communicate method to read the output. The code runs fine when I do not use a thread. It appears that when I use a thre... | Python Subprocess.Popen from a thread | I'm trying to launch an 'rsync' using subprocess module and Popen inside of a thread. After I call the rsync I need to read the output as well. I'm using the communicate method to read the output. The code runs fine when I do not use a thread. It appears that when I use a thread it hangs on the communicate call. Anothe... | [
"You didn't supply any code for us to look at, but here's a sample that does something similar to what you describe:\nimport threading\nimport subprocess\n\nclass MyClass(threading.Thread):\n def __init__(self):\n self.stdout = None\n self.stderr = None\n threading.Thread.__init__(self)\n\n ... | [
46,
17
] | [] | [] | [
"multithreading",
"python",
"rsync",
"subprocess"
] | stackoverflow_0000984941_multithreading_python_rsync_subprocess.txt |
Q:
python: validating function parameters
I need to make sure all the named parameters were passed to a method (I don't want any defaults). Is the following the best way to enforce it?
class X:
def func(self, **kwargs):
if set(kwargs.keys() != ('arg1', 'arg2', 'arg3'):
raise ArgException(kwargs)
A:
For ... | python: validating function parameters | I need to make sure all the named parameters were passed to a method (I don't want any defaults). Is the following the best way to enforce it?
class X:
def func(self, **kwargs):
if set(kwargs.keys() != ('arg1', 'arg2', 'arg3'):
raise ArgException(kwargs)
| [
"For Python 2.x, Hugh's answer (i.e. just use named positional arguments) is your best bet.\nFor Python 3.x, you also have the option of requiring the use of keyword arguments (rather than merely allowing it) as follows:\nclass X(object):\n def func(self, *, arg1, arg2, arg3):\n pass\n\n",
"class X(obje... | [
5,
3,
0
] | [] | [] | [
"coding_style",
"python",
"python_3.x"
] | stackoverflow_0004870534_coding_style_python_python_3.x.txt |
Q:
what's wrong with this python line?
The following line in my source code:
a = testSourceDir.find("\\", testSourceDir.find("\\drv")+1)
is in the shell displayed as:
a = testSourceDir.find("\", testSourceDir.find("\\drv")+1)
but gives the following error:
SyntaxError: unexpected character after line continuation c... | what's wrong with this python line? | The following line in my source code:
a = testSourceDir.find("\\", testSourceDir.find("\\drv")+1)
is in the shell displayed as:
a = testSourceDir.find("\", testSourceDir.find("\\drv")+1)
but gives the following error:
SyntaxError: unexpected character after line continuation character
What am I doing wrong?
| [
"You need to escape the \\:\na= testSourceDir.find(\"\\\\\", testSourceDir.find(\"\\\\drv\")+1)\n\nMore about escape sequences here.\n",
"\"is in the shell displayed as:\"\nWhat do you mean with that?\nThe first line is correct. The second line is not. What's wrong with it is that you have only one backslash, so ... | [
4,
3
] | [] | [] | [
"python"
] | stackoverflow_0004872500_python.txt |
Q:
How to add a new column to the beginning of the rows of a CSV file?
I have one csv file in which I have 6 to 8 column.
Ex:
ID Test Description file-name module view path1 path2
I want to add new column (Node) to the beginning.
Ex:
Node ID Test Description file-name module view path1 path2
A:
It would be fairl... | How to add a new column to the beginning of the rows of a CSV file? | I have one csv file in which I have 6 to 8 column.
Ex:
ID Test Description file-name module view path1 path2
I want to add new column (Node) to the beginning.
Ex:
Node ID Test Description file-name module view path1 path2
| [
"It would be fairly easy to do using the csv module's DictReader and DictWriter classes. Here's an example that reads the old file and writes the new one in single pass.\nA DictReader instance returns each logical line or row of the file as a dictionary whose keys are the field names. You can explicitly specify the... | [
19,
3
] | [] | [] | [
"csv",
"python",
"updates"
] | stackoverflow_0004872077_csv_python_updates.txt |
Q:
How to develop a django->pylons file upload tool?
I have a Pylons application that provides web services to a Django-based front end. I need to be able to provide file upload and download to the users of the application.
Basically, they upload a file in the front end (which might be literally anything, and often q... | How to develop a django->pylons file upload tool? | I have a Pylons application that provides web services to a Django-based front end. I need to be able to provide file upload and download to the users of the application.
Basically, they upload a file in the front end (which might be literally anything, and often quite large). The file is transmitted from client => dja... | [
"You're not neccessarily stuck with scp'ing the uploaded file all at once. scp can take data from standard input, and in python you have fine control over input, output and error pipes of subprocesses.\nFor the Pylons part, I guess, the question could read, \"How to do streaming HTTP uploads/downloads with Pylons\"... | [
1
] | [] | [] | [
"django",
"pylons",
"python",
"web_applications",
"web_services"
] | stackoverflow_0004715750_django_pylons_python_web_applications_web_services.txt |
Q:
Python multiprocessing with unrelated processes
I have many processes that are spawned separately, not from parent to child. The processes need to send a message to specific processes. The receiving processes address (pid) can be stored in a database, but the processes cannot share any common variables in memory.
... | Python multiprocessing with unrelated processes | I have many processes that are spawned separately, not from parent to child. The processes need to send a message to specific processes. The receiving processes address (pid) can be stored in a database, but the processes cannot share any common variables in memory.
I could not find any way to accomplish this with pyth... | [
"\nThe processes need to send a message to specific processes. The receiving processes address (pid) can be stored in a database, but the processes cannot share any common variables in memory.\n\nDatabase? Why? Everyone uses a file for this, since a file is cheap, available, and you're only storing one integer va... | [
2
] | [] | [] | [
"multiprocessing",
"python",
"sockets"
] | stackoverflow_0004873229_multiprocessing_python_sockets.txt |
Q:
Unsupported characters in input
I want to assign a string of characters to a variable but it says
: there isn't a "code to show.
I have a string that i want to assign to a variable
d="stunning:/ËstÊnɪÅ/"
Unsupported characters in input
or
word="stuning:/ˈstraɪkɪŋ/"
Unsupported characters in input
so basically ... | Unsupported characters in input | I want to assign a string of characters to a variable but it says
: there isn't a "code to show.
I have a string that i want to assign to a variable
d="stunning:/ËstÊnɪÅ/"
Unsupported characters in input
or
word="stuning:/ˈstraɪkɪŋ/"
Unsupported characters in input
so basically the interpreter doesn't allow me to a... | [
"Set the source file encoding accordingly to the actual encoding of the file, so that the interpreter knows how to parse it.\nFor instance, if you use UTF-8, just add this string to the header of the file:\n # -*- coding: utf8 -*-\n\nIt must be the first or the second line of the file. See PEP 0263: Defining Pyt... | [
8,
2
] | [] | [] | [
"python",
"python_2.x",
"unicode"
] | stackoverflow_0004873543_python_python_2.x_unicode.txt |
Q:
cURL script in PHP or Python, perl
I have in PHP a script that use multi curl to connect to sites doing the following actions:
login to the site
get a page
verify the page content
if the content is what I need I do 5.
post some data to the site.
log out.
My script can login to <20 sites in parallel, but is not t... | cURL script in PHP or Python, perl | I have in PHP a script that use multi curl to connect to sites doing the following actions:
login to the site
get a page
verify the page content
if the content is what I need I do 5.
post some data to the site.
log out.
My script can login to <20 sites in parallel, but is not too fast and is use a lot of server res... | [
"I'd imagine it has less to do with the language, and more to do with waiting for HTTP requests. It doesn't sound like you are doing anything that would cause PHP to be the bottleneck.\nI'd start by testing the time it takes for the HTTP requests. I'll bet that's where your bottleneck is.\n",
"For python, try to ... | [
2,
1
] | [] | [] | [
"curl",
"performance",
"php",
"python"
] | stackoverflow_0004873871_curl_performance_php_python.txt |
Q:
Joining two 2D numpy arrays into a single 2D array of 2-tuples
I have two 2D numpy arrays like this, representing the x/y distances between three points. I need the x/y distances as tuples in a single array.
So from:
x_dists = array([[ 0, -1, -2],
[ 1, 0, -1],
[ 2, 1, 0]])
y_d... | Joining two 2D numpy arrays into a single 2D array of 2-tuples | I have two 2D numpy arrays like this, representing the x/y distances between three points. I need the x/y distances as tuples in a single array.
So from:
x_dists = array([[ 0, -1, -2],
[ 1, 0, -1],
[ 2, 1, 0]])
y_dists = array([[ 0, -1, -2],
[ 1, 0, -1],
... | [
"import numpy as np\ndists = np.vstack(([x_dists.T], [y_dists.T])).T\n\nreturns dists like you wanted them. Afterwards it is not \"a single 2D array of 2-tuples\", but a normal 3D array where the third axis is the concatenation of the two original arrays.\nYou see:\ndists.shape # (3, 3, 2)\n\n",
"numpy.rec.fromar... | [
12,
8
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0004873665_arrays_numpy_python.txt |
Q:
return tuple from a method
I am writing a method which returns a tuple on success but None on failure. I have not yet finalized on None (as a failure case return) but it is one of the choices. Can we return -1,-1 for failure case? I am looking for best pythonic way to achieve this so that unpacking is easy.
Please... | return tuple from a method | I am writing a method which returns a tuple on success but None on failure. I have not yet finalized on None (as a failure case return) but it is one of the choices. Can we return -1,-1 for failure case? I am looking for best pythonic way to achieve this so that unpacking is easy.
Please let me know how we can improve ... | [
"If there is a failure, why don't you raise an exception?\nYou can of course return (-1, -1) as failure, but it would not be a good solution in my opinion.\nRemember that in Python EAFP (Easier to Ask Forgiveness than Permission) is favoured over LBYL (Look Before You Leap).\nThis means that it is considered better... | [
14,
3
] | [] | [] | [
"python"
] | stackoverflow_0004873613_python.txt |
Q:
how to use sqlalchemy for sql?
select category_id, (select category.name from category where category.id = category_id ) as category_name from ( select distinct category_id as category_id from model join category on ( category.id = model.category_id) ) as R
...
self.current_session.query(Model.category_id).join(C... | how to use sqlalchemy for sql? | select category_id, (select category.name from category where category.id = category_id ) as category_name from ( select distinct category_id as category_id from model join category on ( category.id = model.category_id) ) as R
...
self.current_session.query(Model.category_id).join(Category).distinct()
But how to know ... | [
"for model, category in self.current_session.query(Model, Category).join(Category).distinct():\n print model.category_id, category.name\n\n"
] | [
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0004874043_python_sqlalchemy.txt |
Q:
Django checkbox want to check only a subset of the list of items
another checkbox question. I have items in a list. Each item has a checkbox. What I want to do is What I want to do is to tick all the items that are a subset of items. The subset of items = client.storageitem_set.all() is items = models.StorageItem... | Django checkbox want to check only a subset of the list of items | another checkbox question. I have items in a list. Each item has a checkbox. What I want to do is What I want to do is to tick all the items that are a subset of items. The subset of items = client.storageitem_set.all() is items = models.StorageItem.objects.filter(orderstoragelist__order__pk = order.pk) This is define... | [
"This may help though I've never done this before, assuming you have some model M you just need to render it's form with the data/options you need and apply onto subset.\n\n\n# Model\nclass M(models.Model):\n status = models.BooleanField() # this will be our checkbox\n # your stuffs\n\n# Model's form\nclass M... | [
0
] | [] | [] | [
"checkbox",
"django",
"html",
"python",
"subset"
] | stackoverflow_0004873679_checkbox_django_html_python_subset.txt |
Q:
How can I find the mimetype of a file without extension that is sent to me inside a zip file?
I have a simple problem: in a system I'm developing the user can send us zipfiles and I need to filter the content of it. (block applications and malicious scripts)
To block the inner files by extension is easy, but files... | How can I find the mimetype of a file without extension that is sent to me inside a zip file? | I have a simple problem: in a system I'm developing the user can send us zipfiles and I need to filter the content of it. (block applications and malicious scripts)
To block the inner files by extension is easy, but files without extension are very common and the extension isn't the most reliable source about the conte... | [
"Not a direct answer, but the format of /etc/magic is not that complicated, so if its only a few filetypes you need to detect, perhaps its easiest to write your own detection routine.\n# Java\n\n0 beshort 0xcafe\n>2 beshort 0xbabe application/x-java-applet\n\nwe get:\ndata = open... | [
2
] | [] | [] | [
"mime_types",
"python",
"python_magic"
] | stackoverflow_0004874333_mime_types_python_python_magic.txt |
Q:
Joining elements of a list
I have a list of tuples like:
data = [('a1', 'a2'), ('b1', 'b2')]
And I want to generate a string like this: "('a1', 'a2'), ('b1'. 'b2')"
If i do something like: ','.join(data), I get an error:
TypeError: sequence item 0: expected string, tuple found
If I want to do something in a sin... | Joining elements of a list | I have a list of tuples like:
data = [('a1', 'a2'), ('b1', 'b2')]
And I want to generate a string like this: "('a1', 'a2'), ('b1'. 'b2')"
If i do something like: ','.join(data), I get an error:
TypeError: sequence item 0: expected string, tuple found
If I want to do something in a single line without doing something... | [
"Use a generator to cast the tuples to strings and then use join().\n>>> ', '.join(str(d) for d in data)\n\"('a1', 'a2'), ('b1', 'b2')\"\n\n",
"Discard the opening and closing brackets from str() output:\n>>> data = [('a1', 'a2'), ('b1', 'b2')]\n>>> str(data)\n\"[('a1', 'a2'), ('b1', 'b2')]\"\n>>> str(data)[1:-1]... | [
14,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004874514_python.txt |
Q:
What are `globals` and `locals` parameters in Python __import__ function for?
There's a part of __import__ in Python documentation, which I don't understand:
__import__(name[, globals[, locals[, fromlist[, level]]]])
The function imports the module name, potentially using the given globals and locals to determine... | What are `globals` and `locals` parameters in Python __import__ function for? | There's a part of __import__ in Python documentation, which I don't understand:
__import__(name[, globals[, locals[, fromlist[, level]]]])
The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context. The standard implementation does n... | [
"\nThe standard implementation does not use its locals argument at all, and uses its globals only to determine the package context of the import statement.\n\n(from docs.python.org)\nI still have no idea how globals are used; what global variable can ever affect the way import statement works?\nEDIT: After looking ... | [
6,
2
] | [
"\nWhat is there to \"interpret\" about the module name? What is package context?\n\nWhen you enter\n>>> a\n\nPython must \"interpret\" that name. Is it a global? Is it a local?\n>>> def f(x):\n... return x * a\n\nNow, x is clearly local. a has to be \"interpreted\". Global? Local?\n\nWhy does the example p... | [
-2
] | [
"import",
"python"
] | stackoverflow_0004874342_import_python.txt |
Q:
Why doesn't the function work with my input?
I have a default example dictionary which looks like this:
critics = {'Lisa Rose': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5,
'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5,
'The Night Listener': 3.0},
'Gene Seymour': {'Lady... | Why doesn't the function work with my input? | I have a default example dictionary which looks like this:
critics = {'Lisa Rose': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5,
'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5,
'The Night Listener': 3.0},
'Gene Seymour': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5,
'Ju... | [
"You are probably fooled by the long keys that hide to the eyes which strings are different.\nTry setting all the values to 0 in test 'seljak' and run a correlation with it. You'll see a 0 correlation:\nprint sim_pearson(tests, 'test@example.com', 'seljak')\n\nChange the last value of test 'seljak' to 1 and you wil... | [
1
] | [] | [] | [
"algorithm",
"dictionary",
"python"
] | stackoverflow_0004874446_algorithm_dictionary_python.txt |
Q:
Python PIL create thumbnail image with copyright text
I would like to create a thumbnail image from a larger image then add copyright information to the bottom of the image in a white box with black text. I guess the process I need to follow is
open original image
scale image down to new size (width: 300px, heig... | Python PIL create thumbnail image with copyright text | I would like to create a thumbnail image from a larger image then add copyright information to the bottom of the image in a white box with black text. I guess the process I need to follow is
open original image
scale image down to new size (width: 300px, height: relative)
extend image canvas size to original size + 5... | [
"import Image\nimport ImageDraw\n\nim = Image.open(\"image.jpg\")\nim.thumbnail((300,300))\nbox = im.getbbox()\nim2=im.crop((box[0], box[1], box[2], box[3]+50))\ndraw=ImageDraw.Draw(im2)\ndraw.text((box[2]-100,box[3]+10), \"Copyright\")\nim2.show()\n\nSetting the font and exact sizing left as an exercise to the rea... | [
3
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0004872912_python_python_imaging_library.txt |
Q:
fast folder size calculation in Python on Windows
I am looking for a fast way to calculate the size of a folder in Python on Windows. This is what I have so far:
def get_dir_size(path):
total_size = 0
if platform.system() == 'Windows':
try:
items = win32file.FindFilesW(path + '\\*')
except Except... | fast folder size calculation in Python on Windows | I am looking for a fast way to calculate the size of a folder in Python on Windows. This is what I have so far:
def get_dir_size(path):
total_size = 0
if platform.system() == 'Windows':
try:
items = win32file.FindFilesW(path + '\\*')
except Exception, err:
return 0
# Add the size or perform... | [
"A quick profiling of your code suggests that over 90% of the time is consumed in the FindFilesW() call alone. This means any improvements by tweaking the Python code would be minor.\nTiny tweaks (if you were to stick with FindFilesW) could include ensuring DIR_EXCLUDES is a set instead of a list, avoiding the rep... | [
6,
2,
1,
1,
1,
0
] | [] | [] | [
"directory",
"python",
"size",
"windows"
] | stackoverflow_0001987119_directory_python_size_windows.txt |
Q:
Learning Python: Is there a better way to write words + vars to file?
For example, the following code:
#!/usr/bin/env python
cliente = 'TESTE'
servidor_virtual = '10.2.192.115'
porta = '22'
conf = "# pool " + cliente + '\n' "virtual_server" + servidor_virtual + porta + '\n'
f = open('cliente.conf', 'w')
f.wri... | Learning Python: Is there a better way to write words + vars to file? | For example, the following code:
#!/usr/bin/env python
cliente = 'TESTE'
servidor_virtual = '10.2.192.115'
porta = '22'
conf = "# pool " + cliente + '\n' "virtual_server" + servidor_virtual + porta + '\n'
f = open('cliente.conf', 'w')
f.write(conf)
f.close()
I'm beginning at Python and creating a model to write s... | [
"To process configuration files you should use the ConfigParser module. See the ConfigParser docs.\n",
"Another possible way to do this is to use lists and the string join function.\nconf = [\"# pool \", cliente, '\\n', \"virtual_server\", servidor_virtual, porta, '\\n']\nf.write(''.join(conf))\n\n",
"Do this.\... | [
3,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004874125_python.txt |
Q:
URLs in mod_python Not Working as Expected
I'm building a web server with apache and mod_python. I've created index.py as I've seen others do, but unlike others I can't access web pages without adding a .py to the url.
For example, http://127.0.1.1/commentsubmit produces a 404, but http://127.0.1.1/commentsubmit.p... | URLs in mod_python Not Working as Expected | I'm building a web server with apache and mod_python. I've created index.py as I've seen others do, but unlike others I can't access web pages without adding a .py to the url.
For example, http://127.0.1.1/commentsubmit produces a 404, but http://127.0.1.1/commentsubmit.py brings up the page as expected.
Everything is ... | [
"Your apache server would have been configured to pass requests to filenames that end in .py to mod_python (if the file exist in the dir.) \nThere are a number of different solutions to make request to /commentsubmit get passed to your commentsubmit.py handler. The easiest would probably be to to use mod_rewrite. ... | [
1
] | [] | [] | [
"apache",
"mod_python",
"python",
"url"
] | stackoverflow_0004870386_apache_mod_python_python_url.txt |
Q:
Displaying reference property's variable through form
models.py
class User(db.Model):
user_id = db.StringProperty(required=True)
nickname = db.StringProperty(required=False)
email = db.StringProperty(required=False)
pic_url = db.StringProperty(required=False)
type_admin = db.BooleanPr... | Displaying reference property's variable through form | models.py
class User(db.Model):
user_id = db.StringProperty(required=True)
nickname = db.StringProperty(required=False)
email = db.StringProperty(required=False)
pic_url = db.StringProperty(required=False)
type_admin = db.BooleanProperty(default=False)
school = db.ReferenceProperty(... | [
"override the __unicode__ method on your School model\nclass School(db.Model): \n school_id = db.StringProperty(required=True) \n school_name= db.StringProperty(required=True) \n school_domain = db.StringProperty(required=False) \n\n def __unicode__(self):\n return self.school_name\n\n"
] | [
2
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0004874907_django_google_app_engine_python.txt |
Q:
Find speed of vehicle from images
I am doing a project to find the speed of a vehicle from images. We are taking these images from within the vehicle. We will be marking some object from the 1st image as a reference. Using the properties of the same object in the next image, we must calculate the speed of the movi... | Find speed of vehicle from images | I am doing a project to find the speed of a vehicle from images. We are taking these images from within the vehicle. We will be marking some object from the 1st image as a reference. Using the properties of the same object in the next image, we must calculate the speed of the moving vehicle. Can anyone help me here??? ... | [
"Knowing the acquisition frequency, you must now find the distance between the successive positions of the marker.\nTo find this distance, I suggest you estimate the pose of the marker for each image. Loosely speaking, the \"pose\" is the transformation matrix expressing the coordinates of an object relative to a c... | [
11
] | [] | [] | [
"image_processing",
"opencv",
"opticalflow",
"performance",
"python"
] | stackoverflow_0004872570_image_processing_opencv_opticalflow_performance_python.txt |
Q:
Retrieving key/ID values from app engine datastore?
I've got a page on my Python app which has a drop-down box of locations associated with the current user, with the names of the locations as the visible values of the drop-down box. What I want to do is allow the user to select one of these locations to associate... | Retrieving key/ID values from app engine datastore? | I've got a page on my Python app which has a drop-down box of locations associated with the current user, with the names of the locations as the visible values of the drop-down box. What I want to do is allow the user to select one of these locations to associate with their current location. When a user adds a new Loca... | [
"Keys in the datastore are represented by objects, not simple values (see here)\nFor any entity in the datastore, call its .key() method to get its key object, and then you can get the printable representation by casting it to a string. \nYou can either set this up in your view code that gets data ready for the tem... | [
2
] | [] | [] | [
"database",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004874954_database_google_app_engine_google_cloud_datastore_python.txt |
Q:
How to create a nested dictionary from a datastore model?
I am working on this problem a couple of days, my idea is from this model:
class oceni(db.Model):
user = db.UserProperty()
weight = db.FloatProperty()
item = db.StringProperty()
..to create a dictionary in this format:
collection = dict()
col... | How to create a nested dictionary from a datastore model? | I am working on this problem a couple of days, my idea is from this model:
class oceni(db.Model):
user = db.UserProperty()
weight = db.FloatProperty()
item = db.StringProperty()
..to create a dictionary in this format:
collection = dict()
collection = {
'user1':{'item1':weight1,'item2':weight2..},
... | [
"I've used your variable names your notation in this snippet.\nkontenier = db.GqlQuery('SELECT * FROM oceni')\nkolekcija = {}\nfor it in kontenier:\n if it.user not in kolekcija:\n kolekcija[it.user] = {}\n kolekcija[it.user][it.item] = it.weight\n\n"
] | [
3
] | [] | [] | [
"datastore",
"dictionary",
"google_app_engine",
"python"
] | stackoverflow_0004875285_datastore_dictionary_google_app_engine_python.txt |
Q:
Is it possible to define a semi-annual frequency for a python scikits.timeseries time_series object?
According to the scikits.timeseries module the following frequencies are available when defining a time_series object:
Annual Frequencies, Quarterly frequencies, Monthly, Weekly, Daily etc. A full list is shown on... | Is it possible to define a semi-annual frequency for a python scikits.timeseries time_series object? | According to the scikits.timeseries module the following frequencies are available when defining a time_series object:
Annual Frequencies, Quarterly frequencies, Monthly, Weekly, Daily etc. A full list is shown on the documentation link: http://pytseries.sourceforge.net/core.constants.html#scikits.timeseries.const.fre... | [
"Define quaterly frequency and fill it to 50%:\nimport scikits.timeseries as ts\n\ndates = ts.date_array(start_date=ts.Date('Q', '2009-01'),\n end_date=ts.Date('Q', '2011-01'))\ndata = ts.TimeSeries(np.arange(9), dates=dates, mask=1-dates.quarter%2)\n\n# returns:\ntimeseries([0 -- 2 -- 4 -- 6 -... | [
1
] | [] | [] | [
"python",
"scikits",
"scipy"
] | stackoverflow_0004875228_python_scikits_scipy.txt |
Q:
Problem with format datetime in python
I have problem with formatting date. This is my code:
myDate=datetime.datetime.now()
print myDate #2011-02-02 13:54:26.162000
stime = time.mktime(time.strptime(myDate, '%Y-%m-%d %I:%M%S.%f'))
At my last line I get exception:
File "c:\Python27\Lib\_strptime.py", line 322, in ... | Problem with format datetime in python | I have problem with formatting date. This is my code:
myDate=datetime.datetime.now()
print myDate #2011-02-02 13:54:26.162000
stime = time.mktime(time.strptime(myDate, '%Y-%m-%d %I:%M%S.%f'))
At my last line I get exception:
File "c:\Python27\Lib\_strptime.py", line 322, in _strptime
found = format_regex.match(data_... | [
"I'm trying to get random date of birth for adult.\nOK, so if you say than an adult can be between 18 and 75 years old (6571 - 27375 days), then let's find a date that is so many days ago from today:\nfrom datetime import datetime, timedelta\nimport random\n\nbirthday = datetime.today() - timedelta(days = random.ra... | [
4,
3,
0
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0004874764_datetime_python.txt |
Q:
how to read a file using ajax and django?
My Ajax code:
var upfile = $("#file-id").val().split(/[\/\\]/).pop();
$.ajax({
type: 'POST',
url: '/upload/',
data:{"upfile":upfile},
success: function(data) {
if (data['success'] === "true") {
}
},
dataType: 'json'
});
return false;... | how to read a file using ajax and django? | My Ajax code:
var upfile = $("#file-id").val().split(/[\/\\]/).pop();
$.ajax({
type: 'POST',
url: '/upload/',
data:{"upfile":upfile},
success: function(data) {
if (data['success'] === "true") {
}
},
dataType: 'json'
});
return false;
Django code:
In simple form submit action ... | [
"It's normal, by default a form submitted with Ajax will not upload files. You need o have a look to some file upload jquery plugins (there's a few of them, I can not suggest one as I did not try any of these yet)\n"
] | [
2
] | [] | [] | [
"ajax",
"django",
"python"
] | stackoverflow_0004875426_ajax_django_python.txt |
Q:
Python script to check if a zip file is corrupt
How do I check if a zip file is corrupt or not? I have a zip file with 10 jpg images. I am able to extract say 8 of the images. Two of the images in the zip are corrupt and I am not able to extract those. Is there a way to check for this in a Python script?
A:
This... | Python script to check if a zip file is corrupt | How do I check if a zip file is corrupt or not? I have a zip file with 10 jpg images. I am able to extract say 8 of the images. Two of the images in the zip are corrupt and I am not able to extract those. Is there a way to check for this in a Python script?
| [
"This code will either throw an exception (if the zip file is really bad or if it's not a zip file), or show the first bad file in the zip file.\nimport os\nimport sys\nimport zipfile\n\nif __name__ == \"__main__\":\n args = sys.argv[1:]\n\n\n print \"Testing zip file: %s\" % args[0]\n\n the_zip_file = zip... | [
25,
10
] | [] | [] | [
"python",
"zip"
] | stackoverflow_0004875747_python_zip.txt |
Q:
Porting ctypes-based code snippet from linux to windows
I have the following code that works under linux. I want to port it to Windows but i have no idea where to look for.
import os
import sys
import ctypes
import ctypes.util
MAX_CHARS = 1000 # maximum number of characters to read
if __name__ == "__main__":
... | Porting ctypes-based code snippet from linux to windows | I have the following code that works under linux. I want to port it to Windows but i have no idea where to look for.
import os
import sys
import ctypes
import ctypes.util
MAX_CHARS = 1000 # maximum number of characters to read
if __name__ == "__main__":
libc = ctypes.CDLL("libc.so.6") # LINUX
fd = libc.ope... | [
"These slides indicate that this will work:\n>>> from ctypes import *\n>>> libc = cdll.msvcrt\n\nI can then access libc.printf, and libc.fopen, but not open or read, though libc._open and libc._read are available. Perhaps an issue with calling conventions?\n"
] | [
4
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0004875776_ctypes_python.txt |
Q:
This bash script is not working - Linux/Python
I can't seem to figure out how to get his bash script working.
#!/bin/bash
export WORKON_HOME=~/.envs
source /usr/local/bin/virtualenvwrapper.sh
workon staging_env
It is using viretualenv and virualenvwrapper in order to use a Python virtual environment.
Typing thes... | This bash script is not working - Linux/Python | I can't seem to figure out how to get his bash script working.
#!/bin/bash
export WORKON_HOME=~/.envs
source /usr/local/bin/virtualenvwrapper.sh
workon staging_env
It is using viretualenv and virualenvwrapper in order to use a Python virtual environment.
Typing these commands in the shell work perfectly fine, running... | [
"When you run a script, it creates its own instance of the shell (bash, in this case). Because of this, the changes are lost when the script ends and the script's shell is closed.\nTo make the changes stick, you'll have to source the script instead of running it.\n"
] | [
4
] | [] | [] | [
"bash",
"python",
"ubuntu",
"virtualenv",
"virtualenvwrapper"
] | stackoverflow_0004876176_bash_python_ubuntu_virtualenv_virtualenvwrapper.txt |
Q:
Django paging object has issues with Postgresql QuerySets
I have some django code that runs fine on a SQLite database or on a MySQL database, but it runs into problems with Postgres, and it's making me crazy that no one has has this issue before. I think it may also be related to the way querysets are evaluated by... | Django paging object has issues with Postgresql QuerySets | I have some django code that runs fine on a SQLite database or on a MySQL database, but it runs into problems with Postgres, and it's making me crazy that no one has has this issue before. I think it may also be related to the way querysets are evaluated by the pager.
In a view I have:
def index(request, page=1):
l... | [
"This was a terrible mistake on my part, no blame goes to Postgresql - the issue was popping up with the way one of my custom template tags was handling certain posts in the postgresql database that weren't present in the SQLite one. I'm still figuring out the issue, but this question is invalid.\n"
] | [
0
] | [] | [] | [
"django",
"django_queryset",
"postgresql",
"python"
] | stackoverflow_0004869574_django_django_queryset_postgresql_python.txt |
Q:
Tkinter progress bar/window not responding when moved
I have borrowed a progress bar from here that I would like to adapt work in my program with global variables. Here is the code for reference:
import Tkinter
class Meter(Tkinter.Frame):
def __init__(self, master, width=300, height=20, bg='white', fillcolor... | Tkinter progress bar/window not responding when moved | I have borrowed a progress bar from here that I would like to adapt work in my program with global variables. Here is the code for reference:
import Tkinter
class Meter(Tkinter.Frame):
def __init__(self, master, width=300, height=20, bg='white', fillcolor='orchid1',\
value=0.0, text=None, font=No... | [
"some_fct and other_fct both sleep for 10 seconds each, so the app will be unresponsive for at least 20 seconds when it starts up since those sleeps all happen before mainloop is called. Are you saying that even after those 20 seconds the app is unresponsive, or are you asking why it's unresponsive for the first 20... | [
2,
2
] | [] | [] | [
"move",
"progress_bar",
"python",
"tkinter"
] | stackoverflow_0004868003_move_progress_bar_python_tkinter.txt |
Q:
pyserial connection works, but how to handle output with ser.readline()?
I can connect to an energy-meter (Baudrate 300!) and the logfile with 228 lines comes slowly in.
line = ser.readline(eol='!')
print line
If I use the above code, the complete logfiles is shown.
And if I parse separatly saved logfiles with m... | pyserial connection works, but how to handle output with ser.readline()? | I can connect to an energy-meter (Baudrate 300!) and the logfile with 228 lines comes slowly in.
line = ser.readline(eol='!')
print line
If I use the above code, the complete logfiles is shown.
And if I parse separatly saved logfiles with match, it sorts out the right values into sqlite.
So both "parts" work separatl... | [
"I would suggest you use a WHILE loop instead of a FOR loop.\nThe readline function is not an iterable, so you cannot loop over its values. This line does not do what you intended:\nfor line in ser.readline(eol='!')\n\nInstead, try this:\nss = r'(0\\.0\\.0|0\\.9\\.1|0\\.9\\.2|1\\.6\\.1|1\\.8\\.1)\\(([0-9\\.]+)'\n\n... | [
1
] | [] | [] | [
"pyserial",
"python",
"regex",
"sqlite"
] | stackoverflow_0004876116_pyserial_python_regex_sqlite.txt |
Q:
Python regular expression not giving expected result
Trying to do a regular expression search on a list in python 2.5.4 - example code:
import re
list_in = ['heti_abcd_xyz_1234', 'heti_abcd_xyz', 'heti_abcd']
en = re.compile('abcd_xyz_1234$')
for item in list_in:
if en.search(item) is None:
list_in.... | Python regular expression not giving expected result | Trying to do a regular expression search on a list in python 2.5.4 - example code:
import re
list_in = ['heti_abcd_xyz_1234', 'heti_abcd_xyz', 'heti_abcd']
en = re.compile('abcd_xyz_1234$')
for item in list_in:
if en.search(item) is None:
list_in.remove(item)
print list_in
For the result however I get:
... | [
"You're modifying the list as you iterate over it. You can't do that.\n",
"It can be a lot simpler:\n>>> list_in = ['heti_abcd_xyz_1234', 'heti_abcd_xyz', 'heti_abcd']\n>>> [x for x in list_in if x.endswith(\"abcd_xyz_1234\")]\n['heti_abcd_xyz_1234']\n\nIf you want a solution that works for arbitrary regex, you c... | [
7,
3,
2
] | [] | [] | [
"for_loop",
"list",
"python"
] | stackoverflow_0004876804_for_loop_list_python.txt |
Q:
Environment Variable for Process
I need to start process within python script, so I use for this subprocess.Popen() and give environment variables through parameter env of Popen function, but my process doesn't see needed environment variables.
How can I do it?
Any help will be appreciated.
I'm running OS X 10.5... | Environment Variable for Process | I need to start process within python script, so I use for this subprocess.Popen() and give environment variables through parameter env of Popen function, but my process doesn't see needed environment variables.
How can I do it?
Any help will be appreciated.
I'm running OS X 10.5.
Example:
env = os.environ
env["Foo"]... | [
"By default, sudo resets the environment of the program it runs for security reasons. If you want to avoid that, you need to pass in the -E flag to sudo, and either the command you're running has to have the SETENV tag or the setenv option has to be set in the sudoers file. See the sudo man page and the sudoers m... | [
4,
0
] | [] | [] | [
"environment_variables",
"python",
"subprocess"
] | stackoverflow_0004876237_environment_variables_python_subprocess.txt |
Q:
Django Form inheritance on Google App Engine
I need inherit one form based on another as described in Django documentation. I have created next code:
'''models'''
class Blog(db.Model):
slug = db.StringProperty('blog url', required=True)
name = db.StringProperty('blog name', required=True)
author = db.... | Django Form inheritance on Google App Engine | I need inherit one form based on another as described in Django documentation. I have created next code:
'''models'''
class Blog(db.Model):
slug = db.StringProperty('blog url', required=True)
name = db.StringProperty('blog name', required=True)
author = db.UserProperty(auto_current_user_add=True, required=... | [
"It would probably make more sense to split out the clean_slug method out of the BlogCreateForm class, since that's the only thing that's really being reused. Doing something such as the following should get what you want.\nclass CleanForm(forms.ModelForm):\n def clean_slug(self):\n return \"something\"\n... | [
0
] | [] | [] | [
"django",
"django_forms",
"google_app_engine",
"python"
] | stackoverflow_0004259039_django_django_forms_google_app_engine_python.txt |
Q:
How to test whether x is a member of a universal set?
I have a list L, and x in L evaluates to True if x is a member of L. What can I use instead of L in order x in smth will evaluate to True independently on the value of x?
So, I need something, what contains all objects, including itself, because x can also be ... | How to test whether x is a member of a universal set? | I have a list L, and x in L evaluates to True if x is a member of L. What can I use instead of L in order x in smth will evaluate to True independently on the value of x?
So, I need something, what contains all objects, including itself, because x can also be this "smth".
| [
"class Universe:\n def __contains__(_,x): return True\n\n",
"You can inherit from the built-in list class and redefine the __contains__ method that is called when you do tests like item in list:\n>>> class my_list(list):\n def __contains__(self, item):\n return True\n\n\n>>> L = my_list()\n>>> L\n[]\... | [
8,
2,
0
] | [] | [] | [
"math",
"python"
] | stackoverflow_0004876399_math_python.txt |
Q:
Making an enumeration of a lookup table in a database with SQLAlchemy?
So I've got this lookup table in a database that looks something like this:
-----------------
| Code | Id |
-----------------
| Good | 1 |
| Bad | 2 |
-----------------
And I want to make a Python object that looks something lik... | Making an enumeration of a lookup table in a database with SQLAlchemy? | So I've got this lookup table in a database that looks something like this:
-----------------
| Code | Id |
-----------------
| Good | 1 |
| Bad | 2 |
-----------------
And I want to make a Python object that looks something like this:
>>> Codes.Good
1
>>> Codes.Bad
2
I've been doing using a hack of pa... | [
"The creator of SqlAlchemy just recently put up a post on doing just this:\nhttp://techspot.zzzeek.org/2011/01/14/the-enum-recipe/\n"
] | [
3
] | [] | [] | [
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0004877285_python_sql_sqlalchemy.txt |
Q:
ImportError : No module named _sqlite3 on GAE
While trying to start local Google App Engine (v1.3.8) Server on my Fedora 14 with Python 2.5 (installed from source) I get the importerror
ImportError: No module named _sqlite3
I have the following package installed - sqlite, sqlite-devel, python2.5, python2.7. I did... | ImportError : No module named _sqlite3 on GAE | While trying to start local Google App Engine (v1.3.8) Server on my Fedora 14 with Python 2.5 (installed from source) I get the importerror
ImportError: No module named _sqlite3
I have the following package installed - sqlite, sqlite-devel, python2.5, python2.7. I did some Google and it looks like this error comes whe... | [
"Install sqlite-devel and rebuild Python.\n",
"This works equally on Ubuntu 10.10 using \n\n$ sudo aptitude install sqlite3 libsqlite3-dev\n\nand rebuilding Python.\n"
] | [
8,
3
] | [] | [] | [
"google_app_engine",
"python",
"sqlite"
] | stackoverflow_0004185991_google_app_engine_python_sqlite.txt |
Q:
How do you force wx.ListCtrl scroll bars to auto-lock to the bottom so that the most recent data is shown in the window?
As new data comes into my wx.ListCtrl the window fills up and scroll bars appear. What I want to do is to have the most current data (at the bottom of the list) displayed on the windows. My fi... | How do you force wx.ListCtrl scroll bars to auto-lock to the bottom so that the most recent data is shown in the window? | As new data comes into my wx.ListCtrl the window fills up and scroll bars appear. What I want to do is to have the most current data (at the bottom of the list) displayed on the windows. My first idea was a way to force the wx.ListCtrl scroll bars to default to the bottom of the window. If there is another/better wa... | [
"After you add the new items, you should be able to use\nself.EnsureVisible(self.GetItemCount() - 1)\n\nto pin the scrollbar to the bottom.\n"
] | [
10
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004877263_python_wxpython.txt |
Q:
How to monkey patch __init__ module in Python?
I know, I know, it's dirty and all. I want to know if it's possible to hijack the __init__ module of a Python module to replace it by your own.
I'm asking that because I need to prevent a django lib to start some part of it's init process that make it crashes with our... | How to monkey patch __init__ module in Python? | I know, I know, it's dirty and all. I want to know if it's possible to hijack the __init__ module of a Python module to replace it by your own.
I'm asking that because I need to prevent a django lib to start some part of it's init process that make it crashes with our configuration.
And yes, it's better to fix the djan... | [
"One way to hijack the import procedure is to simulate the import sometime before it takes place, in another module that is imported before the one you want to monkey-patch. Insert whatever you want into sys.modules with the name of the module as the key, and when the time comes to import the original module, Pytho... | [
4,
0
] | [] | [] | [
"django",
"init",
"monkeypatching",
"python"
] | stackoverflow_0004877457_django_init_monkeypatching_python.txt |
Q:
Twisted: Creating a ThreadPool and then daemonizing leads to uninformative hangs
I am developing a networked application in Twisted, part of which consists of a web interface written in Django.
I wish to use Twisted's WSGI server to host the web interface, and I've written a working "tap" plugin to allow me to use... | Twisted: Creating a ThreadPool and then daemonizing leads to uninformative hangs | I am developing a networked application in Twisted, part of which consists of a web interface written in Django.
I wish to use Twisted's WSGI server to host the web interface, and I've written a working "tap" plugin to allow me to use twistd.
When running the server with the -n flag (don't daemonize) everything works f... | [
"Return a MultiService from your ServiceMaker; one that includes your ThreadPoolService as well as your main application service. The API for assembling such a thing is pretty straightforward:\nmulti = MultiService()\nmine = TCPServer(...) # your existing application service\nthreads = ThreadPoolService()\nmine.se... | [
7
] | [] | [] | [
"django",
"python",
"threadpool",
"twisted",
"wsgi"
] | stackoverflow_0004875326_django_python_threadpool_twisted_wsgi.txt |
Q:
Convert a binary number in a list back to its decimal form in python?
How would I convert a binary string to a decimal number? I am taking the binary out of a list of values, and need to then convert it to decimal format.
ex. x=["0b000101"] needs to become x= [5]
Is this Possible?
A:
In [66]: x
Out[66]: ['0b0001... | Convert a binary number in a list back to its decimal form in python? | How would I convert a binary string to a decimal number? I am taking the binary out of a list of values, and need to then convert it to decimal format.
ex. x=["0b000101"] needs to become x= [5]
Is this Possible?
| [
"In [66]: x\nOut[66]: ['0b000101']\n\nIn [67]: [int(elt,base=2) for elt in x]\nOut[67]: [5]\n\n"
] | [
6
] | [] | [] | [
"python"
] | stackoverflow_0004877745_python.txt |
Q:
What Python Module extracts certain chars from raw input?
What Python module can I use to extract certain chars from raw input?
Example: user types in "1J1J"... I want Python to extract both the "J"s.
A:
#!/usr/bin/python
result = raw_input("Enter some string: ")
print result.replace("J","")
Running this and g... | What Python Module extracts certain chars from raw input? | What Python module can I use to extract certain chars from raw input?
Example: user types in "1J1J"... I want Python to extract both the "J"s.
| [
"#!/usr/bin/python\n\nresult = raw_input(\"Enter some string: \")\nprint result.replace(\"J\",\"\")\n\nRunning this and giving input: 1J1J prints out:\n11\n\nWhich is 1J1J but with the \"J\"s extracted\n"
] | [
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0004877924_python_string.txt |
Q:
How would I check a string for a certain letter in Python?
How would I tell Python to check the below for the letter x and then print "Yes"? The below is what I have so far...
dog = "xdasds"
if "x" is in dog:
print "Yes!"
A:
Use the in keyword without is.
if "x" in dog:
print "Yes!"
If you'd like to ... | How would I check a string for a certain letter in Python? | How would I tell Python to check the below for the letter x and then print "Yes"? The below is what I have so far...
dog = "xdasds"
if "x" is in dog:
print "Yes!"
| [
"Use the in keyword without is.\nif \"x\" in dog:\n print \"Yes!\"\n\nIf you'd like to check for the non-existence of a character, use not in:\nif \"x\" not in dog:\n print \"No!\"\n\n",
"in keyword allows you to loop over a collection and check if there is a member in the collection that is equal to the el... | [
56,
7,
3
] | [] | [] | [
"python"
] | stackoverflow_0004877844_python.txt |
Q:
direct standard error to same file and standard output?
I have something like
f=open('out.txt','w')
print >>f, 'action=%r'%action
in one of my Python programs. Is it possible to direct standard error to the same file as standard output?
Thanks!
A:
You could do this...
import sys
f = open("error.log", "w")
sys... | direct standard error to same file and standard output? | I have something like
f=open('out.txt','w')
print >>f, 'action=%r'%action
in one of my Python programs. Is it possible to direct standard error to the same file as standard output?
Thanks!
| [
"You could do this...\nimport sys\n\nf = open(\"error.log\", \"w\")\nsys.stderr = f \nprint \"raising exception\"\nraise Exception, \"find this in error.log\"\n\nOr to answer your question more directly, \nimport sys\nf = open(\"logall.txt\", \"w\")\nsys.stderr = f\nsys.stdout = f\nprint \"find this in l... | [
2,
1
] | [] | [] | [
"file",
"file_io",
"python"
] | stackoverflow_0004877796_file_file_io_python.txt |
Q:
Shortcut for method parameter
I was wondering if there was a way to do something like this in Python:
some_method(param1="param1", param2 = somevar or None)
I want to pass the param2 if somevar is set, or None if it isn't. Basically I am looking for a shorter way of doing this:
if somevar is None:
some_method(par... | Shortcut for method parameter | I was wondering if there was a way to do something like this in Python:
some_method(param1="param1", param2 = somevar or None)
I want to pass the param2 if somevar is set, or None if it isn't. Basically I am looking for a shorter way of doing this:
if somevar is None:
some_method(param1="param1")
else:
some_method(par... | [
"Keyword arguments default to what you provide them in your function definition.\ndef some_method(param1=\"param1\", param2=None):\n # param1 is \"param1\" unless some other value is passed in.\n # param2 is None if some value is not passed for it.\n\nConsider:\ndef print_values(first_value=\"Hello\", second_... | [
3,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0004877727_python.txt |
Q:
How to find values in string, manipulate and replace them
How to find values in string, add specific value to each of them and replace output with fixed string.
import re
def _replace(content):
#x = float(content.group(4))+20
#y = float(content.group(6))+20
return content.group(6)
print re.sub('<g(\s)t... | How to find values in string, manipulate and replace them | How to find values in string, add specific value to each of them and replace output with fixed string.
import re
def _replace(content):
#x = float(content.group(4))+20
#y = float(content.group(6))+20
return content.group(6)
print re.sub('<g(\s)transform="matrix\((.*)(\s)(.*)(\s)(.*)\)\"', _replace, '<g tran... | [
"First off, I should repeat the usual warning about not parsing XML with regexes. It's a bad idea, and it will never work for all cases. If you're actually trying to parse the full xml document, use an XML parser.\nThat having been said, I'm guilty of doing quick and dirty stuff like this all the time. If you re... | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004877787_python_regex.txt |
Q:
How come the second call to the Python app doesn't have keyboard focus
If I call this class twice, the first time the keyboard focus goes to the window. The second time it doesn't. The escape key is used to close the window and it works the first time. The second time the window must be clicked in with the mouse b... | How come the second call to the Python app doesn't have keyboard focus | If I call this class twice, the first time the keyboard focus goes to the window. The second time it doesn't. The escape key is used to close the window and it works the first time. The second time the window must be clicked in with the mouse before the escape key will work. Is there something going on with the focus n... | [
"I just ran the code, and in Windows 7, it doesn't take focus either time.\nWhat OS are you running it in? \nAlso, you can force focus to the root window by throwing in this line.\nroot.focus_force()\n",
"On a Mac using X11 as the window server and using either an X terminal or a regular terminal, the focus alway... | [
0,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0004813326_python_tkinter.txt |
Q:
numpy array of objects
I'm trying to implement a simulation for a lattice model (lattice boltzmann) in Python. Each site of the lattice has a number of properties, and interact with neighboring sites according to certain rules. I figured that it might be clever to make a class with all the properties and make a gr... | numpy array of objects | I'm trying to implement a simulation for a lattice model (lattice boltzmann) in Python. Each site of the lattice has a number of properties, and interact with neighboring sites according to certain rules. I figured that it might be clever to make a class with all the properties and make a grid of instances of that clas... | [
"You can vectorize the class's __init__ function:\nimport numpy as np\n\nclass Site:\n def __init__(self, a):\n self.a = a\n def set_a(self, new_a):\n self.a = new_a\n\nvSite = np.vectorize(Site)\n\ninit_arry = np.arange(9).reshape((3,3))\n\nlattice = np.empty((3,3), dtype=object)\nlattice[:,:] ... | [
29,
9,
8
] | [] | [] | [
"numpy",
"python",
"simulation"
] | stackoverflow_0004877624_numpy_python_simulation.txt |
Q:
Python indentation error:
I have tried notepad++ and eclipse but even then , it is showing me an indentation error at line 18. I don't know, why it is throwing me an error like that...? please help me.
from brisa.core.reactors.qtreactor import QtReactor
reactor = QtReactor()
from brisa.core import config
from bris... | Python indentation error: | I have tried notepad++ and eclipse but even then , it is showing me an indentation error at line 18. I don't know, why it is throwing me an error like that...? please help me.
from brisa.core.reactors.qtreactor import QtReactor
reactor = QtReactor()
from brisa.core import config
from brisa.upnp.device import Device
fro... | [
"In such cases it is usually a good idea to run python with the -t flag:\n\n-t : issue warnings about inconsistent tab usage (-tt: issue errors)\n\nThis will help to find indentation problems caused by accidentally used tabs.\n",
"The row\n self.verticalLayout.addWidget(self.lineEdit)\n\nshould be on the ... | [
13,
7,
5,
3
] | [] | [] | [
"python"
] | stackoverflow_0004878369_python.txt |
Q:
Django - filter ManyToManyField?
I'm not sure the best way to describe what it is that I'm trying to do so forgive my title.
I have two models, User and Group. Group contains field, members, which is a ManyToManyField referring to User.
Given a User, I want to find all of the Groups to which that user belongs.
My... | Django - filter ManyToManyField? | I'm not sure the best way to describe what it is that I'm trying to do so forgive my title.
I have two models, User and Group. Group contains field, members, which is a ManyToManyField referring to User.
Given a User, I want to find all of the Groups to which that user belongs.
My idea would be to do something like th... | [
"If you have the user and you want to have his groups then start querying from it, not the way around ;)\nHere's an example:\njames = User.objects.get(pk= 123)\njames_groups = james.group_set.all()\n\n",
"The most concise way is probably\ngroups = user1.group_set.all()\n\nwhich gives you a queryset that is itera... | [
2,
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004878030_django_django_models_python.txt |
Q:
pyqt4 on Linux environment
I am trying to use PyQt4. I have downloaded its LINUX version and trying to install it with Cygwin(because I have windows on my PC and I want to use linux, therefore I am using Cygwin). I don't know how to install it ? please guide me . There is no such file like setup.py, install....wha... | pyqt4 on Linux environment | I am trying to use PyQt4. I have downloaded its LINUX version and trying to install it with Cygwin(because I have windows on my PC and I want to use linux, therefore I am using Cygwin). I don't know how to install it ? please guide me . There is no such file like setup.py, install....what should I do??
| [
"PyQt4 and Qt are cross-platform. If you write cross-platform code, you don't need to develop on any specific OS. Testing on different platforms from time to time is a good idea, but good cross-platform code will usually just work.\nDon't use any Windows-specific features, Windows-specific code. In particular, don'... | [
2
] | [] | [] | [
"linux",
"pyqt4",
"python"
] | stackoverflow_0004877959_linux_pyqt4_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.