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:
What's the difference between quantize() and str.format()?
I don't mean what's the technical difference, but rather, what's the faster/more logical or Pythonic, etc. way to do this:
def __quantized_price(self):
TWOPLACES = Decimal(10) ** -2
return self.price.quantize(TWOPLACES)
or
def __fo... | What's the difference between quantize() and str.format()? | I don't mean what's the technical difference, but rather, what's the faster/more logical or Pythonic, etc. way to do this:
def __quantized_price(self):
TWOPLACES = Decimal(10) ** -2
return self.price.quantize(TWOPLACES)
or
def __formatted_price(self):
TWOPLACES = Decimal(10) ** -2
... | [
"Decimal.quantize returns a new Decimal that has a different value.\n''.format() formats a string. \nIn this particular case printing the result yields the same output. Other than that they are totally different operations returning totally different types. \n"
] | [
8
] | [] | [] | [
"django",
"python",
"quantization",
"string"
] | stackoverflow_0002015359_django_python_quantization_string.txt |
Q:
Trying to get a solid Python install working on my Mac?
I have Mac OSX 10.5.8 with Xcode installed. I want to avoid MacPorts and want to just get a solid Python install foundation so I can then move on to mess with Django and other things. I want to use Buildout with my Python applications.
I have installed binary... | Trying to get a solid Python install working on my Mac? | I have Mac OSX 10.5.8 with Xcode installed. I want to avoid MacPorts and want to just get a solid Python install foundation so I can then move on to mess with Django and other things. I want to use Buildout with my Python applications.
I have installed binary Python 2.6.4 from the official site and installed this. Foll... | [
"Firstly, there's absolutely no need to install a new version of Python to work on Django in Leopard. The stock Python 2.5 works absolutely fine, and Django is 100% compatible with that version.\nSecondly, if you do want to use virtualenv with a different version of Python other than the system default, you simply ... | [
2,
1,
0,
0,
0
] | [] | [] | [
"buildout",
"installation",
"macos",
"python",
"unix"
] | stackoverflow_0002012959_buildout_installation_macos_python_unix.txt |
Q:
SQLAlchemy filter query by related object
Using SQLAlchemy, I have a one to many relation with two tables - users and scores. I am trying to query the top 10 users sorted by their aggregate score over the past X amount of days.
users:
id
user_name
score
scores:
user
score_amount
created... | SQLAlchemy filter query by related object | Using SQLAlchemy, I have a one to many relation with two tables - users and scores. I am trying to query the top 10 users sorted by their aggregate score over the past X amount of days.
users:
id
user_name
score
scores:
user
score_amount
created
My current query is:
top_users = DBSession... | [
"The single-joined-row way, with a group_by added in for all user columns although MySQL will let you group on just the \"id\" column if you choose:\n sess.query(User, func.sum(Score.amount).label('score_increase')).\\\n join(User.scores).\\\n filter(Score.created_at > someday).\\\n ... | [
22,
1,
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0002010454_python_sqlalchemy.txt |
Q:
Custom Django template tag to look up a string username and return it as a user object
I use some third-party template tags in my Django Application (maintained elsewhere) that return a username as a string I can access in my templates like this.
{% for user in gr.user.foll.list %}
{{user}}
Trouble is because {... | Custom Django template tag to look up a string username and return it as a user object | I use some third-party template tags in my Django Application (maintained elsewhere) that return a username as a string I can access in my templates like this.
{% for user in gr.user.foll.list %}
{{user}}
Trouble is because {{user}} is returned as a string - I need to convert into a Django User Object, if it exists ... | [
"use a template filter like so:\n{{username|get_user}}\n\nin your user_template_tags.py:\nfrom django import template\nfrom django.contrib.auth.models import User\n\nregister = template.Library()\n\n########################\n\ndef get_user(username):\n try:\n user = User.objects.get(username__iexact=usern... | [
4
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0002015740_django_django_templates_python.txt |
Q:
Deploying Pylons with Nginx reverse proxy?
Is there a tutorial on how to deploy Pylons with Nginx?
I've been able to start nginx and then serve pylons to :8080 with paster serve development.ini
However, I can't seem to do other stuff as pylons locks me into that serve mode. If I try to CTRL+Z out of pylons servin... | Deploying Pylons with Nginx reverse proxy? | Is there a tutorial on how to deploy Pylons with Nginx?
I've been able to start nginx and then serve pylons to :8080 with paster serve development.ini
However, I can't seem to do other stuff as pylons locks me into that serve mode. If I try to CTRL+Z out of pylons serving to do other stuff on my server, pylons goes do... | [
"Run Pylons in daemon mode.\npaster serve development.ini --daemon\n\n",
"Running Pylons with nginx tutorial found here:\nwiki.pylonshq.com/display/pylonscookbook/Running+Pylons+with+NGINX\nPylons on Nginx with Memcached and SSI:\nhttp://www.reshetseret.com/app/blog/?p=3\nUPDATE: link is broken, here is google ca... | [
5,
2
] | [] | [] | [
"nginx",
"paster",
"pylons",
"python"
] | stackoverflow_0001071088_nginx_paster_pylons_python.txt |
Q:
Search a file for strings from a second file
I have two files. The first file contains a list of 6 character keys (SA0001, SA1001, etc.). The second file contains a list of dates and amounts where the first six positions will match the key in the first file. I want to verify that every key in the first file has at... | Search a file for strings from a second file | I have two files. The first file contains a list of 6 character keys (SA0001, SA1001, etc.). The second file contains a list of dates and amounts where the first six positions will match the key in the first file. I want to verify that every key in the first file has at least one match in the second file. There may be ... | [
"Use sets instead:\nset1=set(line[:6] for line in open('file1.txt'))\nset2=set(line[:6] for line in open('file2.txt'))\nnot_found = set1 - set2\nif not_found:\n print \"Some keys not found: \" + ', '.join(not_found)\n\n",
"first_file=open(\"file1.txt\",\"r\")\n#save all items from first file into a set\nfirst_... | [
3,
2,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002016006_python.txt |
Q:
Entity groups in Google App Engine Datastore
So I have an app that if I'm honest doesn't really need transactional integrity (lots of updates, none of them critical). So I was planning on simply leaving entity groups by the wayside for now. But I'd still like to understand it (coming from a relational background... | Entity groups in Google App Engine Datastore | So I have an app that if I'm honest doesn't really need transactional integrity (lots of updates, none of them critical). So I was planning on simply leaving entity groups by the wayside for now. But I'd still like to understand it (coming from a relational background).
The way I see it, all queries for my app will b... | [
"\nThe way I see it, if I want transactions (on a per-user basis), I will need some kind of root user entity as the parent of all entities that are part of the hierarchy of her data, no matter how thin this entity would actually be i.e. basically no properties.\n\nI wouldn't just create a root user entity and throw... | [
12,
3
] | [] | [] | [
"google_app_engine",
"python",
"schemaless"
] | stackoverflow_0001515135_google_app_engine_python_schemaless.txt |
Q:
Python/Django: If 5 and 5.00 are different values (when expressed in Decimal), then
If 5 and 5.00 and 5.000 are all different, then why does Django's decimal field save without the .00 even when I have decimal_places=2
?
More importantly, how can I save a value 5.00 as 5.00 in Django without using String.
A:
I t... | Python/Django: If 5 and 5.00 are different values (when expressed in Decimal), then | If 5 and 5.00 and 5.000 are all different, then why does Django's decimal field save without the .00 even when I have decimal_places=2
?
More importantly, how can I save a value 5.00 as 5.00 in Django without using String.
| [
"I think it would be more correct to say those are different representations of the same value '5'. \nInternally, the value saved (unless you're actually storing a string) is 5.\nWhen the value is displayed, ie converted to a string representation for the screen, it might be shown as 5, 5.00 or 5.000 but internally... | [
3,
2
] | [] | [] | [
"decimal",
"django",
"python"
] | stackoverflow_0002016292_decimal_django_python.txt |
Q:
Creating several profile classes in django
I'm getting started with django and I'd like to extend the basic django.contrib.auth.models.User class to create my own site profile(s). Here is described how to do it, got that.
As far as I've understood it, you can only specify a single class as AUTH_PROFILE_MODULE in y... | Creating several profile classes in django | I'm getting started with django and I'd like to extend the basic django.contrib.auth.models.User class to create my own site profile(s). Here is described how to do it, got that.
As far as I've understood it, you can only specify a single class as AUTH_PROFILE_MODULE in your settings.py.
Now, if I create an extension c... | [
"There can be only one profile class. I guess I don't understand the scenario where you would want to split them up. In any case,\nAUTH_PROFILE_MODULE = \"UserProfileExtended\"\n\nshould handle the inheritance correctly for the simple example you give.\n"
] | [
1
] | [] | [] | [
"django",
"profile",
"python"
] | stackoverflow_0002016452_django_profile_python.txt |
Q:
Simple non-web based bug tracker
There's a ton and and a half of questions and even more answers here concerning people looking for bug trackers. However all of them (that I found) seem to be about web based solutions. Since I'm working on a local project where I don't want to set up a web / DB server, and I don't... | Simple non-web based bug tracker | There's a ton and and a half of questions and even more answers here concerning people looking for bug trackers. However all of them (that I found) seem to be about web based solutions. Since I'm working on a local project where I don't want to set up a web / DB server, and I don't want to use a hosted tracker either, ... | [
"I'm surprised nobody has mentioned Roundup.\nIt meets all your criteria, including not requiring a web-based interface (as per your specification, and unlike the accepted answer which suggested Trac).\nRoundup is:\n\nOpen source\nPure Python\nSupports SQLite\nNot fancy, focuses on solid bug tracking\n\nAnd as a si... | [
9,
8,
6,
2,
0
] | [
"Do yourself a favor. Get over this \"must not be web based\" obsession, Install a local WAMP stack on your PC or on a LAN server. Now, you can install your own wiki. And something like Trac. I'd like to find an implementation of google code's bugtracker and integrated wiki thats runnable locally - Trac seems to be... | [
-13
] | [
"bug_tracking",
"non_web",
"python",
"windows"
] | stackoverflow_0001211463_bug_tracking_non_web_python_windows.txt |
Q:
What programs are used to build standalone desktop widgets that interact with online php and mysql?
I have seen mention of Java and Python. I need something that can be installed on a users desktop without them having to also install Java or anything else. User simplicity is a must.
This widget will log into an... | What programs are used to build standalone desktop widgets that interact with online php and mysql? | I have seen mention of Java and Python. I need something that can be installed on a users desktop without them having to also install Java or anything else. User simplicity is a must.
This widget will log into an online php based calendar that accesses mySQL. Any pointers on what I should be reading up on? Python?... | [
"Sounds like something like Adobe Air, Microsoft's Silverlight, or Appcelerators Titanium is what you want.\n",
"Adobe Air is the popular solution to this problem these days\n",
"The others here are basically right. You don't specify what the platform you want to put this on. You have a couple of options:\n\nNa... | [
3,
2,
1,
0,
0,
0
] | [] | [] | [
"mysql",
"php",
"python",
"widget"
] | stackoverflow_0002016609_mysql_php_python_widget.txt |
Q:
How can I auto-fill a paragraph in Eclipse?
I would like to auto-fill a paragraph to 80 characters (or some other fixed width) in Eclipse. Is this possible via a keyboard command like in Emacs? Or is there maybe a plugin (I did not find anything on google)?
Edit: I am not sure if this is relevant, but I need this ... | How can I auto-fill a paragraph in Eclipse? | I would like to auto-fill a paragraph to 80 characters (or some other fixed width) in Eclipse. Is this possible via a keyboard command like in Emacs? Or is there maybe a plugin (I did not find anything on google)?
Edit: I am not sure if this is relevant, but I need this for docstrings in Python code (using the PyDev pl... | [
"You can wrap the paragraph in Pydev with Ctrl+2+w (see Pydev keybindings at: http://pydev.org/manual_adv_keybindings.html)\n",
"Highlight the text, then press Ctrl-Shift-F, or open the context menu and select Source / Format.\n"
] | [
6,
2
] | [] | [] | [
"eclipse",
"formatting",
"python",
"word_wrap"
] | stackoverflow_0000643422_eclipse_formatting_python_word_wrap.txt |
Q:
Have writen a program to extract text from a PDF in python, and now need to make it run for every PDF in the folder and save as a text file
So far here is the code I have (it is working and extracting text as it should.)
import pyPdf
def getPDFContent(path):
content = ""
# Load PDF into pyPDF
pdf = py... | Have writen a program to extract text from a PDF in python, and now need to make it run for every PDF in the folder and save as a text file | So far here is the code I have (it is working and extracting text as it should.)
import pyPdf
def getPDFContent(path):
content = ""
# Load PDF into pyPDF
pdf = pyPdf.PdfFileReader(file(path, "rb"))
# Iterate pages
for i in range(0, pdf.getNumPages()):
# Extract text from page and add to con... | [
"Take a look at os.walk()\n",
"The glob module can help you find all files in a single directory that match a wildcard pattern.\n",
"for loop to get it to run on all PDF's in a directory: look at the glob module\nsave the text as a CSV: look at the csv module\ncount the pictures: look at the pyPDF module :-)\nT... | [
4,
0,
0
] | [] | [] | [
"csv",
"pdf",
"python"
] | stackoverflow_0002016777_csv_pdf_python.txt |
Q:
Conditional statements in Eclipse templates
Eclipse templates can automatically insert text and variables as you are coding. When variables are used with the ${variable} form, the value is inserted automatically.
My question is whether you can add sections to these templates conditionally. Can you have a method de... | Conditional statements in Eclipse templates | Eclipse templates can automatically insert text and variables as you are coding. When variables are used with the ${variable} form, the value is inserted automatically.
My question is whether you can add sections to these templates conditionally. Can you have a method definition template that will fill in multiple vari... | [
"It can be done through Jython scripting in Pydev in the latest nightly build (which will be 1.5.4).\nSee http://pydev.org/download.html for details on getting it.\nShortly, you can define a variable in scripting and program it in Jython to be how you want it to be (and you can update the templates cache on the fly... | [
2,
1
] | [] | [] | [
"eclipse",
"pydev",
"python",
"templates"
] | stackoverflow_0001890330_eclipse_pydev_python_templates.txt |
Q:
How do you reload your Python source into the console window in Eclipse/Pydev?
In other Python IDEs (PythonWin and Idle) it's possible to hit a key and have your current source file window reloaded into the console. I find this useful when experimenting with a piece of code; you can call functions from the consol... | How do you reload your Python source into the console window in Eclipse/Pydev? | In other Python IDEs (PythonWin and Idle) it's possible to hit a key and have your current source file window reloaded into the console. I find this useful when experimenting with a piece of code; you can call functions from the console interactively and inspect data structures there.
Is there a way to do this with Ec... | [
"You can do it with Ctrl+Alt+Enter on the latest Pydev for details on what Ctrl+Alt+Enter provides as it can do a number of things related to the interactive console.\n",
"Use the revert option on the File menu.\nYou can bind a key to it in Windows > Preferences > General > Keys.\nEdit:\nThe reload(module) functi... | [
7,
1
] | [] | [] | [
"pydev",
"python"
] | stackoverflow_0001191018_pydev_python.txt |
Q:
Newbie needs help with Python Tutorial
I am a newbie going through a byte of python (3.0). This is the first programming language I have ever used. I am stuck at the point where you make a simple program that creates a backup zip file (p.75). I'm running Windows 7 (64 bit) with python 3.1. Prior to this I installe... | Newbie needs help with Python Tutorial | I am a newbie going through a byte of python (3.0). This is the first programming language I have ever used. I am stuck at the point where you make a simple program that creates a backup zip file (p.75). I'm running Windows 7 (64 bit) with python 3.1. Prior to this I installed GNUWin32 + sources, and added C:\Program F... | [
">>> zip -qr C:\\Backup\\20100106143030.zip C:\\AB\\a C:\\AB\\b \n\nsounds like a command you should type in your operating system's shell, not in python's shell. Maybe you can try \nos.system('zip -qr C:\\Backup\\20100106143030.zip C:\\AB\\a C:\\AB\\b') \n\nin the python shell...\n",
"That's not giving you the h... | [
2,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0002017320_python.txt |
Q:
Python Thread Pause and Wait
I have an array of threads. Each of them call the run method continuously. At the end of each run method I want them to pause and wait.
How can I get the threads to execute one at a time, and then continue the loop when all are finished? I need them to ALWAYS execute in order (ie: 1, 2... | Python Thread Pause and Wait | I have an array of threads. Each of them call the run method continuously. At the end of each run method I want them to pause and wait.
How can I get the threads to execute one at a time, and then continue the loop when all are finished? I need them to ALWAYS execute in order (ie: 1, 2, 3, 4 - 1, 2, 3, 4...)
I'm curren... | [
"Your description seems to imply you don't want the threads to execute concurrently, which would bring into question why you're using threading in the first place. \nI sense two possible answers as to why you'd want to do this.\nThe first possibility is that you are trying to prevent your threads from working on so... | [
3,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0002017261_multithreading_python.txt |
Q:
a(*{'q':'qqq'}),why only print key
def a(*x):
print x
a({'q':'qqq'})
a(*{'q':'qqq'})#why only print key.
traceback:
({'q': 'qqq'},)
('q',)
A:
That's how dictionaries get converted to sequences.
tuple(dictionary) = tuple(dictionary.keys())
for a similar reason
for x in dictionary:
assigns keys, not pairs, ... | a(*{'q':'qqq'}),why only print key | def a(*x):
print x
a({'q':'qqq'})
a(*{'q':'qqq'})#why only print key.
traceback:
({'q': 'qqq'},)
('q',)
| [
"That's how dictionaries get converted to sequences.\ntuple(dictionary) = tuple(dictionary.keys())\nfor a similar reason\nfor x in dictionary:\n\nassigns keys, not pairs, to x\n",
"When you're calling a function, using an asterisk before a list or dict will pass it in as positional parameters.\nFor example:\n>>> ... | [
5,
2,
2,
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002017548_python.txt |
Q:
Get memory usage of computer in Windows with Python
How can I tell what the computer's overall memory usage is from Python, running on Windows XP?
A:
You can also just call GlobalMemoryStatusEx() (or any other kernel32 or user32 export) directly from python:
import ctypes
class MEMORYSTATUSEX(ctypes.Structure)... | Get memory usage of computer in Windows with Python | How can I tell what the computer's overall memory usage is from Python, running on Windows XP?
| [
"You can also just call GlobalMemoryStatusEx() (or any other kernel32 or user32 export) directly from python: \nimport ctypes\n\nclass MEMORYSTATUSEX(ctypes.Structure):\n _fields_ = [\n (\"dwLength\", ctypes.c_ulong),\n (\"dwMemoryLoad\", ctypes.c_ulong),\n (\"ullTotalPhys\", ctypes.c_ulongl... | [
23,
13,
0
] | [] | [] | [
"memory",
"memory_management",
"python",
"pywin32",
"winapi"
] | stackoverflow_0002017545_memory_memory_management_python_pywin32_winapi.txt |
Q:
Why does tarfile.extractall ignore errors by default?
Python's tarfile module ignores errors during extraction by default, unless errorlevel is set to either 1 or 2 (or debug to 1 if only error messages need to be printed).
Try doing a mkdir /tmp/foo && sudo chown root /tmp/foo && chmod a-w /tmp/foo and using tar... | Why does tarfile.extractall ignore errors by default? | Python's tarfile module ignores errors during extraction by default, unless errorlevel is set to either 1 or 2 (or debug to 1 if only error messages need to be printed).
Try doing a mkdir /tmp/foo && sudo chown root /tmp/foo && chmod a-w /tmp/foo and using tarfile to extract a .tar.gz file over /tmp/foo -- you will se... | [
"FWIW, this nasty behavior is will be changed in Python 2.7 and 3.2. http://svn.python.org/view?view=rev&revision=76780 Apparently the reason for ignoring the errors before was to be more like GNU tar, which ignores errors.\n"
] | [
2
] | [] | [] | [
"permissions",
"python",
"tarfile"
] | stackoverflow_0002017725_permissions_python_tarfile.txt |
Q:
Data Carving loop improvements
I currently have a Python app I am developing which will data carve a block device for jpeg files. Let's just say that it sometimes works and sometimes doesn't. I have created it so that I read the block device till I find a ffd8, then I keep the stream open and search via looping ... | Data Carving loop improvements | I currently have a Python app I am developing which will data carve a block device for jpeg files. Let's just say that it sometimes works and sometimes doesn't. I have created it so that I read the block device till I find a ffd8, then I keep the stream open and search via looping for the ffd9 closure. Though I alwa... | [
"The trouble with reading the block device directly is that there is no guarantee that the blocks of any given file are contiguous. That means that even if you find your magic marker bytes 0xFFD8 in block 13, say, there is no guarantee that block 14 belongs to the same file, whether or not it contains the 0xFFD9 e... | [
2
] | [] | [] | [
"io",
"python"
] | stackoverflow_0002018210_io_python.txt |
Q:
How to create a class from function
I am still struggling with understanding classes, I am not certain but I have an idea that this function I have created is probably a good candidate for a class. The function takes a list of dictionaries, identifies the keys and writes out a csv file.
First Q, is this function... | How to create a class from function | I am still struggling with understanding classes, I am not certain but I have an idea that this function I have created is probably a good candidate for a class. The function takes a list of dictionaries, identifies the keys and writes out a csv file.
First Q, is this function a good candidate for a class (I write ou... | [
"The main idea behind objects is that an object is data plus methods.\nWhenever you are thinking about making something an object, you must ask yourself what will be the object's data, and what operations (methods) will you want to perform on that data.\nFunctions, more readily translate to methods than classes.\nS... | [
2,
2,
1,
1,
0,
0
] | [] | [] | [
"class",
"python"
] | stackoverflow_0002018282_class_python.txt |
Q:
Examples of using Doctests in Django in an Agile / BDD way
I'm interested in learning how to Doctests and Unit tests in a more Agile / BDD way.
I've found a few tutorials that seem reasonable, but they are just thumbnails.
What I would really like to see is the source code of some Django projects that were develop... | Examples of using Doctests in Django in an Agile / BDD way | I'm interested in learning how to Doctests and Unit tests in a more Agile / BDD way.
I've found a few tutorials that seem reasonable, but they are just thumbnails.
What I would really like to see is the source code of some Django projects that were developed BDD style.
The things I'm unclear about are how do you handle... | [
"I've asked myself the same question before. I've found doctests to be of limited utility for things like views, model methods and managers because\n\nYou need to be able to setup and teardown a test data set to actually use for testing\nViews need to take a request object. In a doctest, where does that come from?\... | [
3,
1,
1,
0
] | [] | [] | [
"agile",
"django",
"doctest",
"python"
] | stackoverflow_0001907610_agile_django_doctest_python.txt |
Q:
What is the difference between these two classes?
class SortedDict(dict):
def __init__(self, data=None):
if data is None:
data = {}
super(SortedDict, self).__init__(data)
and
class SortedDict(dict):
def __init__(self, data={}):
dict(data)
I think they are same.
A:
d... | What is the difference between these two classes? | class SortedDict(dict):
def __init__(self, data=None):
if data is None:
data = {}
super(SortedDict, self).__init__(data)
and
class SortedDict(dict):
def __init__(self, data={}):
dict(data)
I think they are same.
| [
"dict(data) just creates a dictionary from data without saving the result anywhere. super(SortedDict, self).__init__(data) on the other hand calls the parent class constructor.\nAlso, in the case of multiple inheritance, using super ensures that all the right constructors are called in the right order. Using None a... | [
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0002018543_python.txt |
Q:
Real-world examples of nested functions
I asked previously how the nested functions work, but unfortunately I still don't quite get it. To understand it better, can someone please show some real-wold, practical usage examples of nested functions?
Many thanks
A:
Your question made me curious, so I looked in some ... | Real-world examples of nested functions | I asked previously how the nested functions work, but unfortunately I still don't quite get it. To understand it better, can someone please show some real-wold, practical usage examples of nested functions?
Many thanks
| [
"Your question made me curious, so I looked in some real-world code: the Python standard library. I found 67 examples of nested functions. Here are a few, with explanations.\nOne very simple reason to use a nested function is simply that the function you're defining doesn't need to be global, because only the enclo... | [
10,
8,
4,
3,
2,
2,
1,
1
] | [] | [] | [
"function",
"nested",
"python"
] | stackoverflow_0002017101_function_nested_python.txt |
Q:
3d Histogram in Python
I am trying to generate a 3D histogram using python. I tried the following code but I am getting an error too many values to unpack.
from matplotlib import pyplot
import pylab
from mpl_toolkits.mplot3d import Axes3D
import numpy
fig = pylab.figure()
ax = Axes3D(fig)
data_filename = 'C... | 3d Histogram in Python | I am trying to generate a 3D histogram using python. I tried the following code but I am getting an error too many values to unpack.
from matplotlib import pyplot
import pylab
from mpl_toolkits.mplot3d import Axes3D
import numpy
fig = pylab.figure()
ax = Axes3D(fig)
data_filename = 'C:\csvfiles\luxury.txt'
data... | [
"\"Too many values to unpack\" happens when you do something like this: \n(a, b) = (1, 2, 3)\n\nThat is, not enough variables on the left to accept all of the values on the right of the =. \nUpdate:\nTry: ax.hist( (X, Y, Z) )\nThe hist function wants a tuple as the first argument. \n"
] | [
3
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0002018572_matplotlib_python.txt |
Q:
What is the relationship between '@1' and '@2'
class SortedDict(dict):
def __new__(cls, *args, **kwargs):
instance = super(SortedDict, cls).__new__(cls, *args, **kwargs)
instance.keyOrder = []
return instance
def __setitem__(self, key, value):
super(SortedDic... | What is the relationship between '@1' and '@2' | class SortedDict(dict):
def __new__(cls, *args, **kwargs):
instance = super(SortedDict, cls).__new__(cls, *args, **kwargs)
instance.keyOrder = []
return instance
def __setitem__(self, key, value):
super(SortedDict, self).__setitem__(key, value)#@1
if k... | [
"The SortedDict is \"A dictionary that keeps its keys in the order in which they're inserted.\" (See: documentation). \nYour @1 line is storing the key-value pair in the dictionary. The @2 stores the key in an internal list to maintain order. \n",
"Because this is a Sorted dict. Dictionaries normally are unsorted... | [
3,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002018900_django_python.txt |
Q:
Problems with Trac post commit script (SyntaxError: invalid syntax)
I've setup a post commit script found at http://trac.edgewall.org/browser/trunk/contrib/trac-post-commit-hook to associate changesets with tickets
When I try to commit, I get the following error
'post-commit' hook failed with error output:
Fil... | Problems with Trac post commit script (SyntaxError: invalid syntax) | I've setup a post commit script found at http://trac.edgewall.org/browser/trunk/contrib/trac-post-commit-hook to associate changesets with tickets
When I try to commit, I get the following error
'post-commit' hook failed with error output:
File "/var/www/svn/repo/hooks/trac-post-commit-hook", line 101
(options,... | [
"May be you have space or tab before (options,args)? may be like this.\n>>> (options, args) = parser.parse_args(sys.argv[1:])\n>>> # this is fine\n>>>\n>>> (options, args) = parser.parse_args(sys.argv[1:])\n File \"<stdin>\", line 1\n (options, args) = parser.parse_args(sys.argv[1:])\n ^\nSyntaxError: inval... | [
3,
2
] | [] | [] | [
"post_commit",
"python",
"svn",
"trac"
] | stackoverflow_0002018888_post_commit_python_svn_trac.txt |
Q:
Dynamically Naming Groups in Python Regular Expressions
Is there a way to dynamically update the name of regex groups in Python?
For example, if the text is:
person 1: name1
person 2: name2
person 3: name3
...
person N: nameN
How would you name groups 'person1', 'person2', 'person3', ..., and 'personN' without kn... | Dynamically Naming Groups in Python Regular Expressions | Is there a way to dynamically update the name of regex groups in Python?
For example, if the text is:
person 1: name1
person 2: name2
person 3: name3
...
person N: nameN
How would you name groups 'person1', 'person2', 'person3', ..., and 'personN' without knowing beforehand how many people there are?
| [
"No, but you can do something like this:\n>>> import re\n>>> p = re.compile('(?m)^(.*?)\\\\s*:\\\\s*(.*)$')\n>>> text = '''person 1: name1\nperson 2: name2\nperson 3: name3\n...\nperson N: nameN'''\n>>> p.findall(text)\n\noutput:\n[('person 1', 'name1'), ('person 2', 'name2'), ('person 3', 'name3'), ('person N', 'n... | [
2,
1,
1,
0
] | [] | [] | [
"python",
"regex",
"regex_group"
] | stackoverflow_0002019005_python_regex_regex_group.txt |
Q:
using python expect to run openvpn
i need a python script to run open vpn automaticaly
but i use sudo for run the open vpn
sudo openvpn --cd /etc/openvpn --config openvpn.conf &
thats my terminal command. i have to give the password for sudo, can i use pexpect to run that command?
and i have to get the exit code... | using python expect to run openvpn | i need a python script to run open vpn automaticaly
but i use sudo for run the open vpn
sudo openvpn --cd /etc/openvpn --config openvpn.conf &
thats my terminal command. i have to give the password for sudo, can i use pexpect to run that command?
and i have to get the exit code because i want to know that the openvpn... | [
"You can change /etc/sudoers so that openvpn command can be run without giving the password. \nyourusername ALL=(all) NOPASSWD: /path/to/openvpn\n\nand in python, do something like:\nimport subprocess\nexitcode = subprocess.call([\"sudo\",\"openvpn\",\"--cd /etc/openvpn --config openvpn.conf\"])\n\n"
] | [
4
] | [] | [] | [
"expect",
"openvpn",
"python"
] | stackoverflow_0002018606_expect_openvpn_python.txt |
Q:
How to wait for messages on multiple queues using py-amqplib
I'm using py-amqplib to access RabbitMQ in Python. The application receives requests to listen on certain MQ topics from time to time.
The first time it receives such a request it creates an AMQP connection and a channel and starts a new thread to listen... | How to wait for messages on multiple queues using py-amqplib | I'm using py-amqplib to access RabbitMQ in Python. The application receives requests to listen on certain MQ topics from time to time.
The first time it receives such a request it creates an AMQP connection and a channel and starts a new thread to listen for messages:
connection = amqp.Connection(host = host, useri... | [
"If you want more than one comsumer per channel just attach another one using basic_consume() and use channel.wait() after. It will listen to all queues attached via basic_consume(). Make sure you define different consumer tags for each basic_consume().\nUse channel.basic_cancel(consumer_tag) if you want to cancel ... | [
1
] | [] | [] | [
"amqp",
"message_queue",
"py_amqplib",
"python",
"rabbitmq"
] | stackoverflow_0001807113_amqp_message_queue_py_amqplib_python_rabbitmq.txt |
Q:
Python Instantiating SubClasses
I wrote the following code trying to figure out how to instantiate the subclasses within the main class.. I came up with something that doesn't feel right.. at least for me.
Is there something wrong with this type of instancing? Is there a better way to call subclasses?
class Fami... | Python Instantiating SubClasses | I wrote the following code trying to figure out how to instantiate the subclasses within the main class.. I came up with something that doesn't feel right.. at least for me.
Is there something wrong with this type of instancing? Is there a better way to call subclasses?
class Family():
def __init__(self):
self.... | [
"What you've defined there are not (in Python terminology at least) subclasses - they're inner classes, or nested classes. I'm guessing that this isn't actually what you were trying to achieve, but I'm not sure what you did actually want - but here are my four best guesses:\n\nA subclass is where the class inheriti... | [
6,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0002019415_python.txt |
Q:
how to use 'pickle'
my code(i was unable to use 'pickle'):
class A(object):
def __getstate__(self):
print 'www'
return 'sss'
def __setstate__(self,d):
print 'aaaa'
import pickle
a = A()
s = pickle.dumps(a)
e = pickle.loads(s)
print s,e
print :
www
aaaa
ccopy_reg
_reconstructor
p0
... | how to use 'pickle' | my code(i was unable to use 'pickle'):
class A(object):
def __getstate__(self):
print 'www'
return 'sss'
def __setstate__(self,d):
print 'aaaa'
import pickle
a = A()
s = pickle.dumps(a)
e = pickle.loads(s)
print s,e
print :
www
aaaa
ccopy_reg
_reconstructor
p0
(c__main__
A
p1
c__builti... | [
"What are you trying to do? It works for me:\nclass A(object):\n def __init__(self):\n self.val = 100\n\n def __str__(self):\n \"\"\"What a looks like if your print it\"\"\"\n return 'A:'+str(self.val)\n\nimport pickle\na = A()\na_pickled = pickle.dumps(a)\na.val = 200\na2 = pickle.loads(... | [
4,
3,
0
] | [] | [] | [
"pickle",
"python"
] | stackoverflow_0002019489_pickle_python.txt |
Q:
Integer division compared to floored quotient: why this surprising result?
The // "integer division" operator of Python surprised me, today:
>>> math.floor(11/1.1)
10.0
>>> 11//1.1
9.0
The documentation reads "(floored) quotient of x and y". So, why is math.floor(11/1.1) equal to 10, but 11//1.1 equal to 9?
A:
... | Integer division compared to floored quotient: why this surprising result? | The // "integer division" operator of Python surprised me, today:
>>> math.floor(11/1.1)
10.0
>>> 11//1.1
9.0
The documentation reads "(floored) quotient of x and y". So, why is math.floor(11/1.1) equal to 10, but 11//1.1 equal to 9?
| [
"Because 1.1 can't be represented in binary form exactly; the approximation is a littler higher than 1.1 - therefore the division result is a bit too small. \nTry the following:\nUnder Python 2, type at the console:\n>>> 1.1\n1.1000000000000001\n\nIn Python 3.1, the console will display 1.1, but internally, it's st... | [
6
] | [] | [] | [
"floor",
"integer_division",
"python",
"python_2.x",
"python_3.x"
] | stackoverflow_0002019588_floor_integer_division_python_python_2.x_python_3.x.txt |
Q:
How to import a variable from different file types
I am trying to obtain a variable from a different file type and import it into a Python script. The file is version.mk, it has a variable called VARIABLE_ID. The import module does not work as normally, is there any way to call variables from other file types?
Tha... | How to import a variable from different file types | I am trying to obtain a variable from a different file type and import it into a Python script. The file is version.mk, it has a variable called VARIABLE_ID. The import module does not work as normally, is there any way to call variables from other file types?
Thanks for any help
import os
from version import VERSION_... | [
"If you are sure about version.mk is valid python file, and does not have any harm codes, you can execute it.\n>>> exec(open(\"version.mk\"))\n>>> print VERSION_ID\n1\n\n\nUPDATE: because OP Added VERSION_ID is not a valid python number\nversion.mk \n#version no is here\nVERSION_ID=0.0.2\n\n#some more info here\n..... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0002019552_python.txt |
Q:
SFTP using ftplib
I need to download a file from a host using SFTP.
Do you know if is it possible to do that using Python ftplib?
I saw an example here, but when I try to connect I receive EOFError.
I tried this code:
import ftplib
ftp = ftplib.FTP()
ftp.connect( "1.2.3.4", "22" )
This method returns with an erro... | SFTP using ftplib | I need to download a file from a host using SFTP.
Do you know if is it possible to do that using Python ftplib?
I saw an example here, but when I try to connect I receive EOFError.
I tried this code:
import ftplib
ftp = ftplib.FTP()
ftp.connect( "1.2.3.4", "22" )
This method returns with an error after long time so I ... | [
"As the question you linked to states, ftplib doesn't support SFTP (which is a transfer protocol over SSH and has nothing to do with FTPS, FTP over SSL). Use the recommended Paramiko instead.\n"
] | [
21
] | [] | [] | [
"ftplib",
"python",
"sftp"
] | stackoverflow_0002019780_ftplib_python_sftp.txt |
Q:
Error when install python mysql module on windows?
When i try to install mysql on windows i get this error
MySQL-python-0.9.2>python setup.py build
running build
running build_py
running build_ext
building '_mysql' extension
error: Unable to find vcvarsall.bat
A:
I guess, you don't have visual c++ compiler insta... | Error when install python mysql module on windows? | When i try to install mysql on windows i get this error
MySQL-python-0.9.2>python setup.py build
running build
running build_py
running build_ext
building '_mysql' extension
error: Unable to find vcvarsall.bat
| [
"I guess, you don't have visual c++ compiler installed or compiler not in the PATH.\nIf you have mingw32, you can pass paramter -c mingw32\nAnd mysql-python is available as binary in windows, you may not need to compile yourself.\nUPDATE: OP is using python 2.6, no binaries for 1.2.3 in mysql-python page for window... | [
5
] | [] | [] | [
"mysql",
"python",
"windows"
] | stackoverflow_0002019827_mysql_python_windows.txt |
Q:
https username and pwd + saving file with webbrowser
I would like to use python webbrowser to access a secure https page and save it into a file.
Am I right if I say that with webbrowser control is not possible to save an entire web page but only opening a URL? I didn't see any 'save' method.
Other than this, the ... | https username and pwd + saving file with webbrowser | I would like to use python webbrowser to access a secure https page and save it into a file.
Am I right if I say that with webbrowser control is not possible to save an entire web page but only opening a URL? I didn't see any 'save' method.
Other than this, the page I want to use is a secure http page and I don't know ... | [
"\nSave means \"Write a file to the disk\". Of course there's no \"save\" method. The library opens the URL so your program can read it. Period. If your program wants to write it to disk, that's not part of reading a URL, so it's not part of browsing.\nUse urllib2 for this. Not the webbrowser. It's much, much... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0002019482_python.txt |
Q:
python vs java on web service development?
i am currently using php as backend language in webdevelopment. but im wondering what you need to install to get running with python and java.
with php i need apache and mysql.
can i use those for java and python too?
i cant find good guides equivalent to LAMP/MAMP/WAMP s... | python vs java on web service development? | i am currently using php as backend language in webdevelopment. but im wondering what you need to install to get running with python and java.
with php i need apache and mysql.
can i use those for java and python too?
i cant find good guides equivalent to LAMP/MAMP/WAMP so i understand the parts when using either java ... | [
"You need to look into the Web Application Framework subject. Some SO pointers:\n\nsimple-webserver-or-web-testing-framework\nweb-application-frameworks-c-vs-python\ndjango-vs-other-python-web-frameworks\nwhat-web-application-framework-for-java-is-recommended\ncan-anyone-recommend-a-simple-java-web-app-framework\n.... | [
4,
4,
2
] | [] | [] | [
"java",
"python"
] | stackoverflow_0002019621_java_python.txt |
Q:
Python basic maths
My friend wrote up this script for me to calculate the quantity of construction materials needed for a theoretical site.
It basically takes 2 numbers and increases them independently until the large number reaches 50,000. It then prints a list like this:
20000:6.40,21000:6.61,22000:6.82,23000:7... | Python basic maths | My friend wrote up this script for me to calculate the quantity of construction materials needed for a theoretical site.
It basically takes 2 numbers and increases them independently until the large number reaches 50,000. It then prints a list like this:
20000:6.40,21000:6.61,22000:6.82,23000:7.03,24000:7.24,25000:7.4... | [
"Replace the line:\nstring += str(getbingint) + \":\" + str(\"%.2f\") % getsmallint + \",\" \n\nwith\nstring += str(getbingint) + \":\" + str(\"%.2f\") % (getsmallint*1.225) + \",\" \n\n",
"You can replace string += str(getsmallint) with string += str(getsmallint*1.225)\n",
"here's another version\ngetbingint =... | [
2,
1,
1
] | [] | [] | [
"multiplication",
"python"
] | stackoverflow_0002019850_multiplication_python.txt |
Q:
Python's CSV reader and iteration
I have a CSV file that looks like this:
"Company, Inc.",,,,,,,,,,,,10/30/09
A/R Summary Aged Analysis Report,,,,,,,,,,,,10:35:01
All Clients,,,,,,,,,,,,USER
Client Account,Customer Name,15-Jan,16 - 30,31 - 60,61 - 90,91 - 120,120 - Over,Total,Status,Credit Limit
1000001111,CLIENT... | Python's CSV reader and iteration | I have a CSV file that looks like this:
"Company, Inc.",,,,,,,,,,,,10/30/09
A/R Summary Aged Analysis Report,,,,,,,,,,,,10:35:01
All Clients,,,,,,,,,,,,USER
Client Account,Customer Name,15-Jan,16 - 30,31 - 60,61 - 90,91 - 120,120 - Over,Total,Status,Credit Limit
1000001111,CLIENT A,0,0,"3,711.32",0,0,"18,629.64","22,3... | [
"Via generators. You can build all kinds of complexity from simple generator-filter functions. While considerably more complex than your filter, this is more extensible and can easily handle really complex spreadsheets. \ndef skip_blank( rdr ):\n for row in rdr:\n if len(row) == 0: continue\n if ... | [
12,
10,
6,
3
] | [] | [] | [
"csv",
"iteration",
"python"
] | stackoverflow_0002019573_csv_iteration_python.txt |
Q:
python json unicode - how do I eval using javascript
Really spent a lot of time searching for this. Please need some help.
I am trying to add multilingual feature to my web app framework. For this I am unable to send non ascii characters as JSON. Here is what I am doing
Here is what I get from the database
'\xe0\... | python json unicode - how do I eval using javascript | Really spent a lot of time searching for this. Please need some help.
I am trying to add multilingual feature to my web app framework. For this I am unable to send non ascii characters as JSON. Here is what I am doing
Here is what I get from the database
'\xe0\xa4\xa4\xe0\xa5\x87\xe0\xa4\xb8\xe0\xa5\x8d\xe0\xa4\xa4'
w... | [
"Is this your desired output (see ensure_ascii argument for json.dumps)?\nsys.stdout.write(json.dumps(response, ensure_ascii=False))\n{\"a\": \"तेस्त\"}\n\n"
] | [
4
] | [] | [] | [
"cgi",
"json",
"python",
"unicode"
] | stackoverflow_0002019966_cgi_json_python_unicode.txt |
Q:
Python inserting a short integer into a list of bytes
I have a list of bytes as follows
pkt_bytes = [ 0x02,0x07, 0xff,0xff ,0x00,0x03]
in the position 0xff,0xff I want to put a 16bit short integer
How do I do it
Regards
A:
You can use the struct module to pack values into appropriate formats:
>>> pkt_bytes = [0... | Python inserting a short integer into a list of bytes | I have a list of bytes as follows
pkt_bytes = [ 0x02,0x07, 0xff,0xff ,0x00,0x03]
in the position 0xff,0xff I want to put a 16bit short integer
How do I do it
Regards
| [
"You can use the struct module to pack values into appropriate formats:\n>>> pkt_bytes = [0x02, 0x07, 0xff, 0xff, 0x00, 0x03]\n>>> myint = 123\n>>> pkt_bytes[3:5] = [ord(b) for b in struct.pack(\"H\",myint)]\n>>> pkt_bytes\n[2, 7, 255, 123, 0, 3]\n\nBy default this will use the native byte order but you can overrid... | [
7,
0,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0002019929_list_python.txt |
Q:
cross module variable
from here I got an idea about how using variables from other modules. this all works fine with
import foo as bar
But I don't want to import my modules as "bar" I want to use it without any prefix like
from foo import *
Using this it´s impossible to modify variables from other modules. readi... | cross module variable | from here I got an idea about how using variables from other modules. this all works fine with
import foo as bar
But I don't want to import my modules as "bar" I want to use it without any prefix like
from foo import *
Using this it´s impossible to modify variables from other modules. reading will work! any idea? sug... | [
"Short answer: No, it's impossible, and you'll have to use a prefix. \nIt's important to understand that from foo import x, y is copying x to your namespace. It's equivallent to:\nimport foo\n# COPY TO YOUR NAMESPACE\nx = foo.x\ny = foo.y\n# `from foo import` does NOT leave `foo` in your namespace\ndef foo\n\nThi... | [
3,
2,
0,
0
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0002019877_import_module_python.txt |
Q:
Given a unicode error I don't understand
Here is my code, I'm sure it looks terrible but it all works as it should, only problem I'm having is with the last line...
import pyPdf
import os
import csv
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the gi... | Given a unicode error I don't understand | Here is my code, I'm sure it looks terrible but it all works as it should, only problem I'm having is with the last line...
import pyPdf
import os
import csv
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, ... | [
"Here's the code that answered that question. But now it only writes the last file. \n import pyPdf\nimport os\nimport csv\n\nclass UnicodeWriter:\n \"\"\"\n A CSV writer which will write rows to CSV file \"f\",\n which is encoded in the given encoding.\n \"\"\"\n\n def __init__(self, f, dialect=csv... | [
1
] | [
"as I Underestand you put a large number in a small varible and its throw an exception.\nI introduce you a C# tool that work very fine with unicode , you can find it at http://unicode.codeplex.com\nin your case I recommand to change the \n for i in range(0, pdf.getNumPages()): \n\npdf.getNumPages() is above than 12... | [
-1
] | [
"ascii",
"python",
"unicode"
] | stackoverflow_0002018058_ascii_python_unicode.txt |
Q:
how do i get the byte count of a variable in python just like wc -c gives in unix
i am facing some problem with files with huge data.
i need to skip doing some execution on those files.
i get the data of the file into a variable.
now i need to get the byte of the variable and if it is greater than 102400 , then pr... | how do i get the byte count of a variable in python just like wc -c gives in unix | i am facing some problem with files with huge data.
i need to skip doing some execution on those files.
i get the data of the file into a variable.
now i need to get the byte of the variable and if it is greater than 102400 , then print a message.
update : i cannot open the files , since it is present in a tar file.
... | [
"import os\nlength_in_bytes = os.stat('file.txt').st_size\nif length_in_bytes > 102400:\n print 'Its a big file!'\n\nUpdate to work on files in a tarfile\nimport tarfile\ntf = tarfile.TarFile('foo.tar')\nfor member in tarfile.getmembers():\n if member.size > 102400:\n print 'It's a big file in a tarfile... | [
6,
2,
2,
1,
0
] | [] | [] | [
"python",
"tar"
] | stackoverflow_0002020318_python_tar.txt |
Q:
PyQt4 Signalling between classes
I have a family of classes (based on the same parent class) that are data cells in a QTableWidget (so they are all derived from QItemDelegate).
I'm trying to create a signal that these classes can pass up to the controller to communicate data changes.
I can't find the right combi... | PyQt4 Signalling between classes | I have a family of classes (based on the same parent class) that are data cells in a QTableWidget (so they are all derived from QItemDelegate).
I'm trying to create a signal that these classes can pass up to the controller to communicate data changes.
I can't find the right combination (despite much experimentation a... | [
"I'm really embarrassed about this. Hopefully this will help somebody else. \nI didn't call the Qt initialization for the appropriate object:\nclass YesNo(Criteria):\n def __init__(self, name, ctype):\n Criteria.__init__(self) # <<<<----- This was missing before\n self.Name = name\n ... | [
1,
0
] | [] | [] | [
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0002004060_pyqt_pyqt4_python.txt |
Q:
Increment a VERSION ID by one and write to .mk file
I have code to read in the version number from a make file.
VERSION_ID=map(int,re.match("VERSION_ID\s*=\s*(\S+)",open("version.mk").read()).group(1).split("."))
This code takes VERSION_ID=0.0.2 and stores it as [0, 0, 2].
Is there any way I can increment this nu... | Increment a VERSION ID by one and write to .mk file | I have code to read in the version number from a make file.
VERSION_ID=map(int,re.match("VERSION_ID\s*=\s*(\S+)",open("version.mk").read()).group(1).split("."))
This code takes VERSION_ID=0.0.2 and stores it as [0, 0, 2].
Is there any way I can increment this number by one and write the new version number into the ver... | [
"perhpas something like this (you should also check for errors and that)\n#! /usr/bin/python\n\nimport re\n\nfn = \"version.mk\"\nomk = open(fn).readlines()\nnmk = open(fn, \"w\")\nr = re.compile(r'(VERSION_ID\\s*=\\s*)(\\S+)')\n\nfor l in omk:\n m1 = r.match(l)\n if m1:\n VERSION_ID=map(int,m1.group(2... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0002020180_python.txt |
Q:
python list that matches everything
I probably didn't ask correctly: I would like a list value that can match any list: the "inverse" of (None,)
but even with (None,) it will match item as None (which I don't want)
The point is I have a function working with: [x for x in my_list if x[field] not in filter_list]
and... | python list that matches everything | I probably didn't ask correctly: I would like a list value that can match any list: the "inverse" of (None,)
but even with (None,) it will match item as None (which I don't want)
The point is I have a function working with: [x for x in my_list if x[field] not in filter_list]
and I would like to filter everything or not... | [
"__contains__ is the magic method that checks if something is in a sequence:\nclass everything(object):\n def __contains__(self, _):\n return True \n\nfor x in (1,2,3):\n print x in everything()\n\n",
"The better syntax would be:\n[x for x in lst if x is None]\n[x for x in lst if x is not N... | [
5,
4,
3,
3,
0,
0,
0
] | [] | [] | [
"filtering",
"list_comprehension",
"python"
] | stackoverflow_0002019791_filtering_list_comprehension_python.txt |
Q:
Download file using urllib in Python with the wget -c feature
I am programming a software in Python to download HTTP PDF from a database.
Sometimes the download stop with this message :
retrieval incomplete: got only 3617232 out of 10689634 bytes
How can I ask the download to restart where it stops using the 206... | Download file using urllib in Python with the wget -c feature | I am programming a software in Python to download HTTP PDF from a database.
Sometimes the download stop with this message :
retrieval incomplete: got only 3617232 out of 10689634 bytes
How can I ask the download to restart where it stops using the 206 Partial Content HTTP feature ?
I can do it using wget -c and it wo... | [
"You can request a partial download by sending a GET with the Range header:\nimport urllib2\nreq = urllib2.Request('http://www.python.org/')\n#\n# Here we request that bytes 18000--19000 be downloaded.\n# The range is inclusive, and starts at 0.\n#\nreq.headers['Range'] = 'bytes=%s-%s' % (18000, 19000)\nf = urllib2... | [
7
] | [] | [] | [
"download",
"http",
"python",
"urllib",
"urllib2"
] | stackoverflow_0002021519_download_http_python_urllib_urllib2.txt |
Q:
Why does the Python gettext module require a compilation step (.po -> .mo)?
I don't see that the compilation step is adding any value.
A:
Reading just quickly about .mo files, it is clear that:
It is a machine-readable representation
It is a hash table
Given gettext's function, to lookup strings by keys at run... | Why does the Python gettext module require a compilation step (.po -> .mo)? | I don't see that the compilation step is adding any value.
| [
"Reading just quickly about .mo files, it is clear that:\n\nIt is a machine-readable representation\nIt is a hash table\n\nGiven gettext's function, to lookup strings by keys at runtime, it is reasonable for this lookup to be implemented efficiently.\nAlso, it is needed for gettext's performance impact to be neglig... | [
5,
1,
0
] | [] | [] | [
"gettext",
"python"
] | stackoverflow_0001407364_gettext_python.txt |
Q:
How do I execute (not import) a python script from a python prompt?
I need to execute a Python script from an already started Python session, as if it were launched from the command line. I'm thinking of similar to doing source in bash or sh.
A:
In Python 2, the builtin function execfile does this.
execfile(file... | How do I execute (not import) a python script from a python prompt? | I need to execute a Python script from an already started Python session, as if it were launched from the command line. I'm thinking of similar to doing source in bash or sh.
| [
"In Python 2, the builtin function execfile does this.\nexecfile(filename)\n\n",
"If you're running ipython (which I highly recommend for interactive python sessions), you can type:\n%run filename \n\nor\n%run filename.py\n\nto execute the module (rather than importing it). You'll get file-name completion, which ... | [
12,
3
] | [] | [] | [
"bash",
"import",
"module",
"python"
] | stackoverflow_0002021345_bash_import_module_python.txt |
Q:
how to update a record using DBSession in turbogears 2
Hi I'm trying to update a user row upon the user logging in. I simply want to increase the users login count by one. Here is the code in the post_login controller method:
@expose()
def post_login(self, came_from=url('/')):
"""
Redirect the user t... | how to update a record using DBSession in turbogears 2 | Hi I'm trying to update a user row upon the user logging in. I simply want to increase the users login count by one. Here is the code in the post_login controller method:
@expose()
def post_login(self, came_from=url('/')):
"""
Redirect the user to the initially requested page on successful
authentic... | [
"Sorry all, turns out the TG2 transaction manager was working after all. The error came because I was calling the post_login function outside of the transaction manager and so the record update was not getting flushed. I'm not sure why it wasn't letting me commit. But I moved the post_login controller and now the a... | [
2,
1
] | [] | [] | [
"python",
"sqlalchemy",
"turbogears2"
] | stackoverflow_0002018494_python_sqlalchemy_turbogears2.txt |
Q:
Python asyncore vs plain old C
i'm stress testing 2 different projects: one is proxsmtpd - smtp proxy written in C
And the other one, smtp_proxy.py, which i developed under 1 hour, with use of asyncore and smtpd python modules.
I stressed both projects under heavy load,
and found out that proxsmtpd is able to hold... | Python asyncore vs plain old C | i'm stress testing 2 different projects: one is proxsmtpd - smtp proxy written in C
And the other one, smtp_proxy.py, which i developed under 1 hour, with use of asyncore and smtpd python modules.
I stressed both projects under heavy load,
and found out that proxsmtpd is able to hold 400 smtp sessions / sec,
while my p... | [
"I think it's a fair assumption that given a good C version and a good Python version, the C version will be faster and more scalable but in your case, you might want to run a profiler and see why and where your program is not scaling up as much as the C version. Perhaps you can uncover the tight spots and optimise... | [
2
] | [] | [] | [
"asyncore",
"proxy",
"python",
"smtp",
"smtpd"
] | stackoverflow_0002022211_asyncore_proxy_python_smtp_smtpd.txt |
Q:
Database Design Inquiry
I'm making a trivia webapp that will feature both standalone questions, and 5+ question quizzes. I'm looking for suggestions for designing this model.
Should a quiz and its questions be stored in separate tables/objects, with a key to tie them together, or am I better off creating the quiz... | Database Design Inquiry | I'm making a trivia webapp that will feature both standalone questions, and 5+ question quizzes. I'm looking for suggestions for designing this model.
Should a quiz and its questions be stored in separate tables/objects, with a key to tie them together, or am I better off creating the quiz as a standalone entity, with... | [
"It's hard to say without more information, but having the following relations would be sensible, based on what you've said:\nQuiz (id, title)\nQuestion (id, question, answer)\nQuizQuestion (quiz_id, question_id)\n\nThat way questions can appear in multiple quizzes. \n",
"My first cut (I assumed the questions wer... | [
3,
1,
1,
0,
0
] | [] | [] | [
"database_design",
"google_app_engine",
"python",
"schema"
] | stackoverflow_0002017930_database_design_google_app_engine_python_schema.txt |
Q:
How to diff file and output stream "on-the-fly"?
I need to create a diff file using standard UNIX diff command with python subprocess module. The problem is that I must compare file and stream without creating tempopary file. I thought about using named pipes via os.mkfifo method, but didn't reach any good result.... | How to diff file and output stream "on-the-fly"? | I need to create a diff file using standard UNIX diff command with python subprocess module. The problem is that I must compare file and stream without creating tempopary file. I thought about using named pipes via os.mkfifo method, but didn't reach any good result. Please, can you write a simple example on how to solv... | [
"You can use \"-\" as an argument to diff to mean stdin.\n",
"You could perhaps consider using the difflib python module (I've linked to an example here) and create something that generates and prints the diff directly rather than relying on diff. The various function methods inside difflib can receive character ... | [
38,
8
] | [] | [] | [
"diff",
"pipe",
"python",
"subprocess"
] | stackoverflow_0002022492_diff_pipe_python_subprocess.txt |
Q:
Create a new Tuple with one element modified
(I am working interactively with a WordprocessingDocument object in IronPython using the OpenXML SDK, but this is really a general Python question that should be applicable across all implementations)
I am trying to scrape out some tables from a number of Word documents... | Create a new Tuple with one element modified | (I am working interactively with a WordprocessingDocument object in IronPython using the OpenXML SDK, but this is really a general Python question that should be applicable across all implementations)
I am trying to scrape out some tables from a number of Word documents. For each table,
I have an iterator that is givi... | [
"def item(i, v):\n if i != 1: return v\n return strangestuff(v)\n\nfor row in rows:\n t = tuple(item(i, c.InnerText)\n for i, c in enumerate(row.Descendants[TableCell]())\n )\n\n",
"I would do this:\ntemp_list = [c.InnerText for c in row.Descendants[TableCell]()]\ntemp_list[2] = \"Somethin... | [
6,
2,
1,
0
] | [] | [] | [
"generator",
"ironpython",
"iterator",
"python"
] | stackoverflow_0001784478_generator_ironpython_iterator_python.txt |
Q:
Beginner wondering if his code is 'Pythonic'
This is really the first thing that I have written in python. I come from Java background. I don't want to just learn how to program java code with Python syntax. I want to learn how to program in a pythonic paradigm.
Could you guys please comment on how I can make t... | Beginner wondering if his code is 'Pythonic' | This is really the first thing that I have written in python. I come from Java background. I don't want to just learn how to program java code with Python syntax. I want to learn how to program in a pythonic paradigm.
Could you guys please comment on how I can make the following code more pythonic?
from math import ... | [
"There is an excellent primer by David Goodger called \"Code Like a Pythonista\" here. A couple of things from that text re naming (quoting):\n\njoined_lower for functions, methods,\nattributes\njoined_lower or ALL_CAPS for\nconstants\nStudlyCaps for classes\ncamelCase only to conform to\npre-existing conventions\... | [
22,
21,
17,
8,
4,
4,
3,
3,
2,
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0000134834_python.txt |
Q:
cherrypy and wxpython
I'm trying to make a cherrypy application with a wxpython ui. The problem is both libraries use closed loop event handlers. Is there a way for this to work? If I have the wx ui start cherrypy is that going to lock up the ui?
A:
See my answer at CherryPy interferes with Twisted shutting down... | cherrypy and wxpython | I'm trying to make a cherrypy application with a wxpython ui. The problem is both libraries use closed loop event handlers. Is there a way for this to work? If I have the wx ui start cherrypy is that going to lock up the ui?
| [
"See my answer at CherryPy interferes with Twisted shutting down on Windows\nIn short, CherryPy handles the main loop by default, but it definitely doesn't need to. Stop using quickstart and call engine.start without engine.block, and CP will run in its own threads and leave the main thread for your other framework... | [
5,
1,
1,
1
] | [] | [] | [
"cherrypy",
"python",
"wxpython"
] | stackoverflow_0002022376_cherrypy_python_wxpython.txt |
Q:
Getting started w/ Python on the desktop
I'm interested in getting started w/ developing Python based applications for a desktop environment and have a few (seemingly simple) questions:
What is the best method for developing GUI applications? I've seen several frameworks but the indexes I've found are a bit convo... | Getting started w/ Python on the desktop | I'm interested in getting started w/ developing Python based applications for a desktop environment and have a few (seemingly simple) questions:
What is the best method for developing GUI applications? I've seen several frameworks but the indexes I've found are a bit convoluted and mix (what seem to be) legacy package... | [
"\nwxPython is the best GUI framework.\nThe official docs are the best resource. They helped me quite a bit.\n\n",
"Have you considered Iron Python as an option? It's basically the Python language on top of the .NET Framework. Having been fortunate enough to work with the .NET Framework in the past on desktop-app... | [
4,
1,
1,
1
] | [] | [] | [
"desktop_application",
"python"
] | stackoverflow_0002022967_desktop_application_python.txt |
Q:
Get list of open windows in Python
I am writing an app in Python that must be able to send keys or text to another app. For example, if I have Firefox open, I should be able to send it an URL to open it.
I already have the SendKeys module, and I have read about the win32 module too, but I do not know if there is a... | Get list of open windows in Python | I am writing an app in Python that must be able to send keys or text to another app. For example, if I have Firefox open, I should be able to send it an URL to open it.
I already have the SendKeys module, and I have read about the win32 module too, but I do not know if there is a way to filter out process without open ... | [
"Usually, for this sort of \"GUI automation\" pyWinAuto is a good way to go. We use it to allow automated testing of GUI applications, and it ought to let you \"type\" URLs into Firefox (not to mention finding its window) as well.\n",
"Even if you need to use automation for everything else your app is going to d... | [
5,
3,
3
] | [] | [] | [
"python",
"pywin32",
"windows"
] | stackoverflow_0002022219_python_pywin32_windows.txt |
Q:
Trying to get HTTP code. Can someone try this code for me in their Python interpretor and see why it doesn't work?
import httplib
def httpCode(theurl):
if theurl.startswith("http://"): theurl = theurl[7:]
head = theurl[:theurl.find('/')]
tail = theurl[theurl.find('/'):]
response_code = 0
conn =... | Trying to get HTTP code. Can someone try this code for me in their Python interpretor and see why it doesn't work? | import httplib
def httpCode(theurl):
if theurl.startswith("http://"): theurl = theurl[7:]
head = theurl[:theurl.find('/')]
tail = theurl[theurl.find('/'):]
response_code = 0
conn = httplib.HTTPConnection(head)
conn.request("HEAD",tail)
res = conn.getresponse()
response_code = int(res.sta... | [
"Your code worked for me, and for one other person who commented. This implies that the URL you're using is causing a problem with your parsing somehow. head and tail should both be examined in order to determine what it thinks the host is. For example:\nhead = theurl[:theurl.find('/')]\nprint head\ntail = theur... | [
2,
2
] | [] | [] | [
"exception",
"http",
"python",
"url"
] | stackoverflow_0002023312_exception_http_python_url.txt |
Q:
Socket module does not work in my Python
Very simple.
>>> import socket
>>> socket.gethostbyname('http://yahoo.com')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
socket.gaierror: [Errno -2] Name or service not known
A:
Very simple.
"http://yahoo.com" is not a host name. Try socket.get... | Socket module does not work in my Python | Very simple.
>>> import socket
>>> socket.gethostbyname('http://yahoo.com')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
socket.gaierror: [Errno -2] Name or service not known
| [
"Very simple.\n\"http://yahoo.com\" is not a host name. Try socket.gethostbyname('yahoo.com') :)\n",
"It is because, quite frankly, http://yahoo.com is in no way a domain name, which gethostbyname expects from you. http://yahoo.com is an URL.\n>>> import socket\n>>> socket.gethostbyname(\"yahoo.com\")\n'69.147.11... | [
11,
2
] | [] | [] | [
"http",
"python",
"sockets"
] | stackoverflow_0002023429_http_python_sockets.txt |
Q:
How do I turn a dictionary into a JSON object using simplejson, in Python?
It's something like this, but this example seems a little complicated.
import simplejson as json
json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
My dictionary is:
myfruits = {'fruit':4, 'color':11}
How can I turn this into a JS... | How do I turn a dictionary into a JSON object using simplejson, in Python? | It's something like this, but this example seems a little complicated.
import simplejson as json
json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
My dictionary is:
myfruits = {'fruit':4, 'color':11}
How can I turn this into a JSON, and then use render_to_response to shoot it to a template?
I'm using Dja... | [
"I think this is the easiest way to do it\nimport simplejson as json \nmyfruits = {'fruit':4, 'color':11}\njson.dumps(myfruits)\n\n",
"use json.dumps() (see doc here).\nimport simplejson\nsimplejson.dumps({'fruit':4, 'color':11})\n\n"
] | [
6,
1
] | [] | [] | [
"django",
"json",
"python"
] | stackoverflow_0002023491_django_json_python.txt |
Q:
C#, Pass Array As Function Parameters
In python the * allows me to pass a list as function parameters:
def add(a,b): return a+b
x = [1,2]
add(*x)
Can I replicate this behavior in C# with an array?
Thanks.
A:
The params keyword allows something similar
public int Add(params int[] numbers) {
int result = 0;
... | C#, Pass Array As Function Parameters | In python the * allows me to pass a list as function parameters:
def add(a,b): return a+b
x = [1,2]
add(*x)
Can I replicate this behavior in C# with an array?
Thanks.
| [
"The params keyword allows something similar\npublic int Add(params int[] numbers) {\n int result = 0;\n\n foreach (int i in numbers) {\n result += i;\n }\n\n return result;\n}\n\n// to call:\nint result = Add(1, 2, 3, 4);\n// you can also use an array directly\nint result = Add(new int[] { 1, 2,... | [
12,
9,
2,
1
] | [] | [] | [
"c#",
"python"
] | stackoverflow_0002023528_c#_python.txt |
Q:
buildbot: connect to IRC server using SSL
How can I use buildbot's IRC bot to connect to an IRC server that wants SSL connections?
A:
I just submitted a small patch to BuildBot which will allow the IRC bot to connect to SSL-enabled servers. Should be included in the next release (0.7.12?).
If you want to apply ... | buildbot: connect to IRC server using SSL | How can I use buildbot's IRC bot to connect to an IRC server that wants SSL connections?
| [
"I just submitted a small patch to BuildBot which will allow the IRC bot to connect to SSL-enabled servers. Should be included in the next release (0.7.12?).\nIf you want to apply it to your setup, it's a simple patch to backport.\n",
"You could fix the tunnel on the buildbots localhost with stunnel, for e.g.:\n... | [
3,
1
] | [] | [] | [
"buildbot",
"irc",
"python",
"ssl",
"twisted"
] | stackoverflow_0001995474_buildbot_irc_python_ssl_twisted.txt |
Q:
How to handle new files to process in cron job
How can I check files that I already processed in a script so I don't process those again? and/or
What is wrong with the way I am doing this now?
Hello,
I am running tshark with the ring buffer option to dump to files after 5MB or 1 hour. I wrote a python script to r... | How to handle new files to process in cron job | How can I check files that I already processed in a script so I don't process those again? and/or
What is wrong with the way I am doing this now?
Hello,
I am running tshark with the ring buffer option to dump to files after 5MB or 1 hour. I wrote a python script to read these files in XML and dump into a database, thi... | [
"A good way to handle/process files that are created at random times is to use\nincron rather than cron. (Note: since incron uses the Linux kernel's\ninotify syscalls, this solution only works with Linux.)\nWhereas cron runs a job based on dates and times, incron runs a job based on\nchanges in a monitored director... | [
6,
3,
0,
0,
0
] | [] | [] | [
"file_io",
"hash",
"mysql",
"python",
"sysadmin"
] | stackoverflow_0002022775_file_io_hash_mysql_python_sysadmin.txt |
Q:
dumb question alert: use *both* ruby on rails and python possible?
the front end and end-user data-collection we want to build in RoR since it's just some simple forms connected to a database.
The integration with other external api's such as twitter and facebook and parsing of the data entered by the users we wan... | dumb question alert: use *both* ruby on rails and python possible? | the front end and end-user data-collection we want to build in RoR since it's just some simple forms connected to a database.
The integration with other external api's such as twitter and facebook and parsing of the data entered by the users we want to do in python, mostly because the developer for that part knows pyth... | [
"It sounds like the only place the two parts will interact is the database: the RoR parts collect data from the user, the python parts collect data from Twitter and elsewhere.\nAs long as your database is supported by both languages, there's no a priori reason why this wouldn't work.\nEven if you end up needing the... | [
3,
0,
0
] | [] | [] | [
"python",
"ruby",
"ruby_on_rails"
] | stackoverflow_0002023458_python_ruby_ruby_on_rails.txt |
Q:
Django 1.1.1: How should I store an empty IP address using PostgreSQL?
I am writing a Django application that stores IP addresses with optional routing information. One of the fields for the IP model I have created is nexthop (for next-hop routes), which will usually be empty. Originally we intended to use MySQL... | Django 1.1.1: How should I store an empty IP address using PostgreSQL? | I am writing a Django application that stores IP addresses with optional routing information. One of the fields for the IP model I have created is nexthop (for next-hop routes), which will usually be empty. Originally we intended to use MySQL, but now project requirements have changed to use PostgreSQL.
Here is a str... | [
"If you can convince the devs to accept one of the patches, I'd say just run a patched copy of Django until the patched version lands. If not, then it might be less headache to just use a sentinel value, as you suggested, even though it is a hack. You might also just use a regular CharField instead of an IPAddressF... | [
2,
1,
0
] | [] | [] | [
"django",
"postgresql",
"python"
] | stackoverflow_0001862123_django_postgresql_python.txt |
Q:
Delayed execution in python for big data
I'm trying to think about how a Python API might look for large datastores like Cassandra. R, Matlab, and NumPy tend to use the "everything is a matrix" formulation and execute each operation separately. This model has proven itself effective for data that can fit in memo... | Delayed execution in python for big data | I'm trying to think about how a Python API might look for large datastores like Cassandra. R, Matlab, and NumPy tend to use the "everything is a matrix" formulation and execute each operation separately. This model has proven itself effective for data that can fit in memory. However, one of the benefits of SAS for b... | [
"I don't know anything about Cassandra/NumPy, but if you adapt your second approach (using NumPy) to process data in chunks of a reasonable size, you might benefit from the CPU and/or filesystem cache and therefore prevent any slowdown caused by looping over the data twice, without giving up the benefit of using op... | [
2,
1
] | [] | [] | [
"cassandra",
"python"
] | stackoverflow_0002009708_cassandra_python.txt |
Q:
2-dimensional interpolation
I want to find a value of z at y = 12 and x = 3.5, given the below example data. How can I do this in C++?
y = 10
x = [1,2, 3,4, 5,6]
z = [2.3, 3.4, 5.6, 7.8, 9.6, 11.2]
y = 20
x = [1,2, 3,4, 5,6]
z = [4.3, 5.4, 7.6, 9.8, 11.6, 13.2]
y = 30
x = [1,2, 3,4, 5,6]
z = [6.3, 7.4, 8.6, 10... | 2-dimensional interpolation | I want to find a value of z at y = 12 and x = 3.5, given the below example data. How can I do this in C++?
y = 10
x = [1,2, 3,4, 5,6]
z = [2.3, 3.4, 5.6, 7.8, 9.6, 11.2]
y = 20
x = [1,2, 3,4, 5,6]
z = [4.3, 5.4, 7.6, 9.8, 11.6, 13.2]
y = 30
x = [1,2, 3,4, 5,6]
z = [6.3, 7.4, 8.6, 10.8, 13.6, 15.2]
My current Pyth... | [
"Just do the interpolation twice. First interpolate with Y to select the two Z tables. Then interpolate with X to pick the Z value.\n",
"I would use Akima's Spline, which is very well-tested, very fast, and produces extremely good results.\nUnfortunately, it's in Fortran-66 (and messy at that), so you'll need to ... | [
1,
1
] | [] | [] | [
"c++",
"math",
"python"
] | stackoverflow_0002024274_c++_math_python.txt |
Q:
Python - automating MySQL query: passing parameter
The code in the sequence is working fine, but looking to improve the MySQL code to a more efficient format.
The first case is about a function that received a parameter and returns the customerID from MySQL db:
def clean_table(self,customerName):
getCustomerID... | Python - automating MySQL query: passing parameter | The code in the sequence is working fine, but looking to improve the MySQL code to a more efficient format.
The first case is about a function that received a parameter and returns the customerID from MySQL db:
def clean_table(self,customerName):
getCustomerIDMySQL="""SELECT customerID
FROM customer
WHERE c... | [
"For the first case (simple, but easy to get a KeyError when there is no row):\ncustomerID = self.cursorMySQL.fetchone()[0]\n\nMore correct is to implement a new method for the cursor class:\ndef autofetch_value(self, sql, args=None):\n \"\"\" return a single value from a single row or None if there is no row\n ... | [
3,
0
] | [] | [] | [
"automation",
"mysql",
"parameters",
"python"
] | stackoverflow_0002024535_automation_mysql_parameters_python.txt |
Q:
Using 'super' when subclassing python class that is not derived from `object`(old-style?)
I'm playing with subclassing OptionParser from the std library module optparser. (Python 2.5.2) When I attempt it I get the exception:
TypeError: super() argument 1 must be type, not classobj
Looking at OptionParser, it is ... | Using 'super' when subclassing python class that is not derived from `object`(old-style?) | I'm playing with subclassing OptionParser from the std library module optparser. (Python 2.5.2) When I attempt it I get the exception:
TypeError: super() argument 1 must be type, not classobj
Looking at OptionParser, it is not derived from object. So I added object as a parent class, (shown below) and super works pro... | [
"Yes I dont see why it would not work. You just need to add couple of spaces right before that super call - as it's written right now, it is not part of your custom init method. Also, a shortcut you might want to use is **kwargs - you can do kwargs key check in your method if thats what you desire to do:\nclass MyO... | [
5
] | [] | [] | [
"python"
] | stackoverflow_0002023940_python.txt |
Q:
What is the Python equivalent of PHP's set_time_limit()?
I have a python script which is freezing (I think it stalls waiting for socket data somewhere), but I am having trouble getting a backtrace because the only way to stop it is to kill the process in. There is a timeout on the socket also, but it doesn't seem ... | What is the Python equivalent of PHP's set_time_limit()? | I have a python script which is freezing (I think it stalls waiting for socket data somewhere), but I am having trouble getting a backtrace because the only way to stop it is to kill the process in. There is a timeout on the socket also, but it doesn't seem to work.
I am hoping that Python has a feature like PHP's set_... | [
"signal.alarm can help (on Unix platforms), but (depending on the platform) there may be uninterruptable system calls (and if I get the docs right, on Unix, PHP's set_time_limit does not count time spent in system calls, so a hanging system call would be a problem there too).\n",
"You could set a timeout on your ... | [
3,
1
] | [] | [] | [
"php",
"python"
] | stackoverflow_0002024644_php_python.txt |
Q:
setuptools "at least one of these" dependency specification
In some cases, there are various modules which each implement a common API (in my case, the old pure-python elementtree, cElementTree, lxml.etree, and the built-in xml.etree). I can write the module using ElementTree to try each of these options, and take... | setuptools "at least one of these" dependency specification | In some cases, there are various modules which each implement a common API (in my case, the old pure-python elementtree, cElementTree, lxml.etree, and the built-in xml.etree). I can write the module using ElementTree to try each of these options, and take the first one that exists according to my own preference order -... | [
"I don't think so, but, if you're using a reasonably recent Python, elementtree being part of the standard Python libraries, why do you worry it might be absent? (I do understand this would be a problem for other cases of several possible implementations of an API, I just wonder if you really need it for your spec... | [
0,
0
] | [] | [] | [
"dependencies",
"python",
"setuptools"
] | stackoverflow_0002023900_dependencies_python_setuptools.txt |
Q:
kwargs sent over pyAMF channel
I'm using cherrypy server to receive requests over a pyAMF channel from a python client. I started with the mock up below and it works fine:
Server:
import cherrypy
from pyamf.remoting.gateway.wsgi import WSGIGateway
def echo(*args, **kwargs):
return (args, kwargs)
class Root(o... | kwargs sent over pyAMF channel | I'm using cherrypy server to receive requests over a pyAMF channel from a python client. I started with the mock up below and it works fine:
Server:
import cherrypy
from pyamf.remoting.gateway.wsgi import WSGIGateway
def echo(*args, **kwargs):
return (args, kwargs)
class Root(object):
def index(self):
... | [
"Notice that with your first echo function, the only way to get the results you do is when it is called this way:\necho(u\"one=1, two=3\")\n# in words: one unicode string literal, as a positional arg\n\n# *very* different from:\necho(one=1, two=3) # which seems to be what you expect\n\nBecause of this, you must wri... | [
2,
1
] | [] | [] | [
"cherrypy",
"pyamf",
"python",
"syntax"
] | stackoverflow_0002024024_cherrypy_pyamf_python_syntax.txt |
Q:
What is the relationship between 'unicode' and 'encode'
print u'\xe4\xf6\xfc'.encode('utf-8')
print unicode(u'\xe4\xf6\xfc')
traceback:
盲枚眉
Traceback (most recent call last):
File "D:\zjm_code\a.py", line 6, in <module>
print unicode(u'\xe4\xf6\xfc')
UnicodeEncodeError: 'ascii' codec can't encode characters... | What is the relationship between 'unicode' and 'encode' | print u'\xe4\xf6\xfc'.encode('utf-8')
print unicode(u'\xe4\xf6\xfc')
traceback:
盲枚眉
Traceback (most recent call last):
File "D:\zjm_code\a.py", line 6, in <module>
print unicode(u'\xe4\xf6\xfc')
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
python shell
>>... | [
"In Python 2:\ncase a: (unicode object).encode(somecodec) -> string of bytes\ncase b: (string of bytes).decode(somecodec) -> unicode object\ncase c: unicode(string of bytes, somecodec) -> unicode object\nCases b and c are identical. In each of the three cases, you can omit the codec name: then it defaults to 'asci... | [
12,
7,
0
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0002025041_python_unicode.txt |
Q:
Lambda, calling itself into the lambda definition
I'm doing a complicated hack in Python, it's a problem when you mix for+lambda+*args (don't do this at home kids), the boring details can be omited, the unique solution I found to resolve the problem is to pass the lambda object into the self lambda in this way:
fo... | Lambda, calling itself into the lambda definition | I'm doing a complicated hack in Python, it's a problem when you mix for+lambda+*args (don't do this at home kids), the boring details can be omited, the unique solution I found to resolve the problem is to pass the lambda object into the self lambda in this way:
for ...
lambda x=x, *y: foo(x, y, <selflambda>)
It's... | [
"You are looking for a fixed-point combinator, like the Z combinator, for which Wikipedia gives this Python implementation:\nZ = lambda f: (lambda x: f(lambda *args: x(x)(*args)))(lambda x: f(lambda *args: x(x)(*args)))\n\nZ takes one argument, a function describing the function you want, and builds and returns tha... | [
8,
4,
0,
0,
0
] | [] | [] | [
"functional_programming",
"lambda",
"python"
] | stackoverflow_0002023992_functional_programming_lambda_python.txt |
Q:
mobile python 2.6 distribution/development environment?
I'm in an interesting situation. My current computer is going to go in for repairs, and in the meantime I want to get some work done on a friend's computer, but I can't and really don't want to have to set up my development environment on the new PC. Is there... | mobile python 2.6 distribution/development environment? | I'm in an interesting situation. My current computer is going to go in for repairs, and in the meantime I want to get some work done on a friend's computer, but I can't and really don't want to have to set up my development environment on the new PC. Is there a way I can carry around a working Python development enviro... | [
"Portable Python\n",
"you can get PortablePython as suggested, OR you can copy the whole installed Python directory, eg C:\\Python26 of your old PC into your flash drive. \nanother you can try is Movable Python\nand web2py\n",
"Another option is to set up a remote server on Slicehost or Rackspace cloud and SSH ... | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002025311_python.txt |
Q:
saving data in Bulk using Django
I have objects A witch has many to many relation ship to object b.
Is it possible to save objects A with it's B collection in a bulk ' I mean not to save B objects one by one then add them to A.
for b in b_objects :
A.b_objs.add(b)
A.save()
Thanks
A:
You could dump your mo... | saving data in Bulk using Django | I have objects A witch has many to many relation ship to object b.
Is it possible to save objects A with it's B collection in a bulk ' I mean not to save B objects one by one then add them to A.
for b in b_objects :
A.b_objs.add(b)
A.save()
Thanks
| [
"You could dump your model to json (from http://www.djangosnippets.org/snippets/125/):\nimport sys, os\n\nsys.path.append('/Path/To/Django/Projects/')\nos.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'\n\nfrom django.core.serializers import serialize\nfrom myproject.myapp import models\n\nmodel_names = []... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002019379_django_python.txt |
Q:
Replacing text in Python
I've been looking at the re documentation and at other questions but I keep running into trouble with regex.
I need to take what ever is in the [tag] off of the string.
string = "Article Name [Tag Name]"
#and I want to go to
string = "Article Name"
I'd really appreciate it if anyone coul... | Replacing text in Python | I've been looking at the re documentation and at other questions but I keep running into trouble with regex.
I need to take what ever is in the [tag] off of the string.
string = "Article Name [Tag Name]"
#and I want to go to
string = "Article Name"
I'd really appreciate it if anyone could help.
| [
"re.sub(\"\\s*\\[.*?\\]\", \"\", string)\n\n",
"If you are sure [Tag Name] is always come after Article Name, you could do this without regex.\n>>> string=\"Article Name [Tag Name]\"\n>>> string[:string.find(\" [\")]\n'Article Name'\n\nor with .partition\n>>> string.partition(\" [\")[0]\n'Article Name'\n\n",
"T... | [
2,
1,
1,
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002025513_python_regex.txt |
Q:
Popen always run, ignoring the if
I want that when I respond other thing diferent that yes, the subprocess don't run.
r = raw_input('\nDo you want play the video?\n\nY:Yes N:No\n\n')
if r == "Y" or "y" or "yes" or"yep" or"yeah":
message("Playing Video")
subprocess.Popen(playvid)
else:
pass
A:
cha... | Popen always run, ignoring the if | I want that when I respond other thing diferent that yes, the subprocess don't run.
r = raw_input('\nDo you want play the video?\n\nY:Yes N:No\n\n')
if r == "Y" or "y" or "yes" or"yep" or"yeah":
message("Playing Video")
subprocess.Popen(playvid)
else:
pass
| [
"change this\nif r == \"Y\" or \"y\" or \"yes\" or\"yep\" or\"yeah\":\n\nto \nif r in [\"Y\",\"y\",\"yes\",\"yep\",\"yeah\"] :\n\nor change your response to lower case\nr = raw_input('\\nDo you want play the video?\\n\\nY:Yes N:No\\n\\n').lower()\nif r in [\"y\",\"yes\",\"yep\",\"yeah\"] :\n\n",
"I'm not sure if... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0002025885_python.txt |
Q:
See What Line a Function Was Called From in Python Decorator
Given something like this:
@my_decorator
my_function(some, args)
Is it possible for my_decorator to discover the file and line number my_function was called from?
Thanks
A:
traceback.extract_stack() will allow you to examine the current stack frame.
| See What Line a Function Was Called From in Python Decorator | Given something like this:
@my_decorator
my_function(some, args)
Is it possible for my_decorator to discover the file and line number my_function was called from?
Thanks
| [
"traceback.extract_stack() will allow you to examine the current stack frame.\n"
] | [
4
] | [] | [] | [
"decorator",
"inspect",
"python"
] | stackoverflow_0002025941_decorator_inspect_python.txt |
Q:
Is it possible to tell a python script to stop at some point and give you the hand interactively, for example with ipython?
Suppose I have a script that does a lot of stuff, and doesn't work well somewhere near the end. I'd love to be able to add a start_ipython() function at that point, which would stop the scrip... | Is it possible to tell a python script to stop at some point and give you the hand interactively, for example with ipython? | Suppose I have a script that does a lot of stuff, and doesn't work well somewhere near the end. I'd love to be able to add a start_ipython() function at that point, which would stop the script at this point, and let me inspect variables and so on with ipython. How can I do this?
| [
"Note that this has changed in IPython-0.11. Instead of what is described below, simply use the following import:\nfrom IPython import embed as shell\n\nThe answer below works for IPython versions prior to 0.11.\n\nIn the region where you want to drop into ipython, define this\ndef start_ipython():\n from IPytho... | [
15,
7
] | [] | [] | [
"python"
] | stackoverflow_0002026447_python.txt |
Q:
Strategies or support for making parts of a Twisted application reloadable?
I've written a specialized JSON-RPC server and just started working my way up into the application logic and finding it is a tad annoying to constantly having to stop/restart the server to make certain changes.
Previously I had a handler t... | Strategies or support for making parts of a Twisted application reloadable? | I've written a specialized JSON-RPC server and just started working my way up into the application logic and finding it is a tad annoying to constantly having to stop/restart the server to make certain changes.
Previously I had a handler that ran in intervals to compare module modified time stamps with the past check t... | [
"Shipped with Twisted is the twisted.python.rebuild module, so that is probably a good place to start. \nAlso see this SO question: Checking for code changes in all imported python modules\n",
"You could write something similar to paster's reloader, that would work like this:\n\nstart your main function, and bef... | [
2,
1
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0002026091_python_twisted.txt |
Q:
Python multiple inheritance: Whats wrong doing it dynamically?
Based on this answer, of how __new__ and __init__ are supposed to work in Python,
I wrote this code to dynamically define and create a new class and object.
class A(object):
def __new__(cls):
class C(cls, B):
pass
self = C()
... | Python multiple inheritance: Whats wrong doing it dynamically? | Based on this answer, of how __new__ and __init__ are supposed to work in Python,
I wrote this code to dynamically define and create a new class and object.
class A(object):
def __new__(cls):
class C(cls, B):
pass
self = C()
return self
def foo(self):
print 'foo'
class B(obje... | [
"Since there is no actual question in the question, I am going to take it literally:\nWhats wrong doing it dynamically?\nWell, it is practically unreadable, extremely opaque and non-obvious to the user of your code (that includes you in a month :P).\nFrom my experience (quite limited, I must admit, unfortunately I ... | [
7,
7,
3
] | [] | [] | [
"multiple_inheritance",
"python"
] | stackoverflow_0002026572_multiple_inheritance_python.txt |
Q:
Python: Get importing module's details from within imported module
I'm writing a piece of reusable code to import where I need it, but it needs some info about what is importing it. I have a workaround that does what I want, but it's a bit ugly. Is there a better way?
Here is a simplified version of what I'm doing... | Python: Get importing module's details from within imported module | I'm writing a piece of reusable code to import where I need it, but it needs some info about what is importing it. I have a workaround that does what I want, but it's a bit ugly. Is there a better way?
Here is a simplified version of what I'm doing.
What I want: Import a method and use it, but look at f in mod2. It nee... | [
"That's a bad idea, because modules are cached.\nSo if another module, say, mod3.py, also imports mod2, it will get the same mod2 object of the first time. The module is not reimported.\nMaybe you imported some other module that imported mod2 before importing mod2 yourself, then you're not the one importing mod2 an... | [
6
] | [] | [] | [
"django",
"import",
"python",
"rest"
] | stackoverflow_0002026788_django_import_python_rest.txt |
Q:
How do you ask gstreamer if a file can be played?
I'm trying to write a simple command line audio player using the Python Gstreamer bindings.
Is there a function in the gstreamer API that determines in advance whether or not a particular file (URI) can be decoded and played by the currently installed set of codecs... | How do you ask gstreamer if a file can be played? | I'm trying to write a simple command line audio player using the Python Gstreamer bindings.
Is there a function in the gstreamer API that determines in advance whether or not a particular file (URI) can be decoded and played by the currently installed set of codecs?
| [
"I guess you can try to play it and see if that raises any error - in fact, there's no way to know the set of codecs necessary without opening the file. Some distributions even have hooks in place that ask the user to download the right codec when you start playing something.\n"
] | [
0
] | [] | [] | [
"codec",
"decode",
"gstreamer",
"python",
"uri"
] | stackoverflow_0002025964_codec_decode_gstreamer_python_uri.txt |
Q:
Packaging Python applications with configuration files
I'm using ConfigParser for configuring my application, and now I want to make it easily distributable, and at the same time preserve the configurability.
I'm thinking I need a directory with configuration file templates, and some way of generating the configu... | Packaging Python applications with configuration files | I'm using ConfigParser for configuring my application, and now I want to make it easily distributable, and at the same time preserve the configurability.
I'm thinking I need a directory with configuration file templates, and some way of generating the configuration to actually use from these. Then I need a place to st... | [
"you can use data_files option of distutils to install files wherever you want.\ndata_files specifies a sequence of (directory, files) pairs in the following way:\nsetup(...,\n data_files=[('/etc', ['cfg/config1.ini', 'cfg/config2.ini']),\n ('/etc/init.d', ['bin/initscript1'])],\n ....\n ... | [
13
] | [] | [] | [
"configuration_files",
"packaging",
"python"
] | stackoverflow_0002026876_configuration_files_packaging_python.txt |
Q:
Work with Postgres/PostGIS View in SQLAlchemy
Two questions:
i want to generate a View in my PostGIS-DB. How do i add this View to my geometry_columns Table?
What i have to do, to use a View with SQLAlchemy? Is there a difference between a Table and View to SQLAlchemy or could i use the same way to use a View as ... | Work with Postgres/PostGIS View in SQLAlchemy | Two questions:
i want to generate a View in my PostGIS-DB. How do i add this View to my geometry_columns Table?
What i have to do, to use a View with SQLAlchemy? Is there a difference between a Table and View to SQLAlchemy or could i use the same way to use a View as i do to use a Table?
sorry for my poor english.
If... | [
"Table objects in SQLAlchemy have two roles. They can be used to issue DDL commands to create the table in the database. But their main purpose is to describe the columns and types of tabular data that can be selected from and inserted to.\nIf you only want to select, then a view looks to SQLAlchemy exactly like a ... | [
4
] | [] | [] | [
"postgis",
"postgresql",
"python",
"sqlalchemy"
] | stackoverflow_0002026475_postgis_postgresql_python_sqlalchemy.txt |
Q:
+ and += operators are different?
>>> c = [1, 2, 3]
>>> print(c, id(c))
[1, 2, 3] 43955984
>>> c += c
>>> print(c, id(c))
[1, 2, 3, 1, 2, 3] 43955984
>>> del c
>>> c = [1, 2, 3]
>>> print(c, id(c))
[1, 2, 3] 44023976
>>> c = c + c
>>> print(c, id(c))
[1, 2, 3, 1, 2, 3] 26564048
What's the difference? are += and +... | + and += operators are different? | >>> c = [1, 2, 3]
>>> print(c, id(c))
[1, 2, 3] 43955984
>>> c += c
>>> print(c, id(c))
[1, 2, 3, 1, 2, 3] 43955984
>>> del c
>>> c = [1, 2, 3]
>>> print(c, id(c))
[1, 2, 3] 44023976
>>> c = c + c
>>> print(c, id(c))
[1, 2, 3, 1, 2, 3] 26564048
What's the difference? are += and + not supposed to be merely syntactic su... | [
"docs explain it very well, I think:\n\n__iadd__(), etc.\n These methods are called to implement the augmented arithmetic assignments (+=, -=, *=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not ... | [
13,
3,
2,
1
] | [] | [] | [
"list",
"operators",
"python"
] | stackoverflow_0002027284_list_operators_python.txt |
Q:
conditional skip in python if
i am trying for something like this
def scanthefile():
x = 11
if x > 5
""" i want to come out of if and go to end of scanfile """
print x
return info
update:
if have to check for the content size of a file. and if the content size is larger than a value ... | conditional skip in python if | i am trying for something like this
def scanthefile():
x = 11
if x > 5
""" i want to come out of if and go to end of scanfile """
print x
return info
update:
if have to check for the content size of a file. and if the content size is larger than a value say 500 , then i should go to the e... | [
"If I understand your question, and I'm really unsure I do, you can just de-indent:\nx = 11\nif x > 5:\n pass # Your code goes here.\nprint x\n\n",
"By \"go to the end of file\", do you mean \"seek to the end of file\"? Then:\nimport os\n\n ...\n\nif x > 5:\n thefile.seek(0, os.SEEK_END)\n\nIf you mean som... | [
2,
2,
2,
0
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0002025701_if_statement_python.txt |
Q:
How to put values of a list into a string
I am trying to place several values from a list into a string. The code I have is below:
ID = [0, 1, 2]
print 'ID {0}, {1}, and {2}.'.format(ID)
or
print (r'(ID\s*=\s*)(\S+)').format(ID)
This does not work. Does anyone know where I'm going wrong.
The code in the second... | How to put values of a list into a string | I am trying to place several values from a list into a string. The code I have is below:
ID = [0, 1, 2]
print 'ID {0}, {1}, and {2}.'.format(ID)
or
print (r'(ID\s*=\s*)(\S+)').format(ID)
This does not work. Does anyone know where I'm going wrong.
The code in the second line prints out the list:
[0, 1, 2]
the first... | [
"You have to unpack the list.\nID = [0, 1, 2]\nprint 'ID {0}, {1}, and {2}.'.format(*ID)\n\nSee the docs: Unpacking argument lists.\n",
">>> 'ID {0}, {1}, and {2}.'.format(*ID)\n'ID 0, 1, and 2.'\n\nYou need to unpack your list.\nYour second code doesn't make much sense.\n"
] | [
9,
4
] | [] | [] | [
"python",
"string_formatting"
] | stackoverflow_0002027391_python_string_formatting.txt |
Q:
Storing list variables as a string and storing it as a variable
I am trying to enter list items into a string. I then want to store the string as a variable and print it out in another function. The code I have got so far is:
def b():
ID = [0, 1, 2]
ID2 = 'ID={0}.{1}.{2}'.format(*ID)
return ID2
if... | Storing list variables as a string and storing it as a variable | I am trying to enter list items into a string. I then want to store the string as a variable and print it out in another function. The code I have got so far is:
def b():
ID = [0, 1, 2]
ID2 = 'ID={0}.{1}.{2}'.format(*ID)
return ID2
if __name__ == '__main__': ID2 = b()
def c(ID2):
print ID2
if... | [
"How about this:\n>>> ''.join([str(x) for x in [1, 2, 3]])\n'123'\n\n",
"If you want to change [0,1,2] to \"0.1.2\" (like version string in your previous questions), you could do like this.\n>>> '.'.join(map(str,[0, 1, 2]))\n'0.1.2'\n\n",
"\nYou should probably not have global variable names that match your fun... | [
3,
2,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0002027543_python.txt |
Q:
How to write an efficient hit counter for websites
I want to write a hit counter script to keep track of hits on images on a website and the originating IPs. Impressions are upwards of hundreds of thousands per day, so the counters will be incremented many times a second.
I'm looking for a simple, self-hosted met... | How to write an efficient hit counter for websites | I want to write a hit counter script to keep track of hits on images on a website and the originating IPs. Impressions are upwards of hundreds of thousands per day, so the counters will be incremented many times a second.
I'm looking for a simple, self-hosted method (php, python scripts, etc.). I was thinking of using... | [
"A fascinating subject. Incrementing a counter, simple as it may be, just has to be a transaction... meaning, it can lock out the whole DB for longer than makes sense!-) It can easily be the bottleneck for the whole system.\nIf you need rigorously exact counts but don't need them to be instantly up-to-date, my fa... | [
7,
4,
3,
2,
1,
0,
0,
0
] | [
"Well if you happen to go the PHP route you could use an SQLite database, however MySQL is a perfectly reasonable way to store that info and usually (at least from the ones I've seen) is how it is done.\nIf you didn't want to store IP address and any other info a simple number in a\ntext file could work.\n"
] | [
-1
] | [
"mysql",
"php",
"python",
"tracking"
] | stackoverflow_0001535261_mysql_php_python_tracking.txt |
Q:
Using Python simplejson to return pregenerated json
I have a GeoDjango model object that I want't to serialize to json. I do this in my view:
lat = float(request.GET.get('lat'))
lng = float(request.GET.get('lng'))
a = Authority.objects.get(area__contains=Point(lng, lat))
if a:
return HttpResponse(simplejson.du... | Using Python simplejson to return pregenerated json | I have a GeoDjango model object that I want't to serialize to json. I do this in my view:
lat = float(request.GET.get('lat'))
lng = float(request.GET.get('lng'))
a = Authority.objects.get(area__contains=Point(lng, lat))
if a:
return HttpResponse(simplejson.dumps({'name': a.name,
... | [
"I think the clean way to do this is by extending JSONEncoder, and creating an encoder that detects if the given object is already JSON. if it is - it just returns it. If its not, it uses the ordinary JSONEncoder to encode it.\nclass SkipJSONEncoder(simplejson.JSONEncoder):\n def default(self, obj):\n i... | [
5,
2
] | [] | [] | [
"django",
"geodjango",
"json",
"python",
"simplejson"
] | stackoverflow_0002027668_django_geodjango_json_python_simplejson.txt |
Q:
Why does not postgresql start returning rows immediately?
The following query returns data right away:
SELECT time, value from data order by time limit 100;
Without the limit clause, it takes a long time before the server starts returning rows:
SELECT time, value from data order by time;
I observe this both by u... | Why does not postgresql start returning rows immediately? | The following query returns data right away:
SELECT time, value from data order by time limit 100;
Without the limit clause, it takes a long time before the server starts returning rows:
SELECT time, value from data order by time;
I observe this both by using the query tool (psql) and when querying using an API.
Ques... | [
"The psycopg2 dbapi driver buffers the whole query result before returning any rows. You'll need to use server side cursor to incrementally fetch results. For SQLAlchemy see server_side_cursors in the docs and if you're using the ORM the Query.yield_per() method.\nSQLAlchemy currently doesn't have an option to set ... | [
4,
0
] | [] | [] | [
"postgresql",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0002027645_postgresql_python_sql_sqlalchemy.txt |
Q:
Sorting a tuple of dicts
I am new to Python and am curious if I am doing this correctly. I have a tuple of dicts (from a database call):
companies = ( { 'companyid': 1, 'companyname': 'Company C' },
{ 'companyid': 2, 'companyname': 'Company A' },
{ 'companyid': 3, 'companyname': 'Compa... | Sorting a tuple of dicts | I am new to Python and am curious if I am doing this correctly. I have a tuple of dicts (from a database call):
companies = ( { 'companyid': 1, 'companyname': 'Company C' },
{ 'companyid': 2, 'companyname': 'Company A' },
{ 'companyid': 3, 'companyname': 'Company B' } )
I want to sort this... | [
"You could do something like:\nimport operator\n...\nsortcompanies.sort(key=operator.itemgetter(\"companyname\"))\n\nI think that's a matter of taste.\nEDIT\nI got companyid in stead of companyname. Corrected that error.\n",
">>> companies = ( { 'companyid': 1, 'companyname': 'Company C' },\n { 'comp... | [
7,
3,
2
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0002028375_python_sorting.txt |
Q:
Python: Downloading a large file to a local path and setting custom http headers
I am looking to download a file from a http url to a local file. The file is large enough that I want to download it and save it chunks rather than read() and write() the whole file as a single giant string.
The interface of urllib.ur... | Python: Downloading a large file to a local path and setting custom http headers | I am looking to download a file from a http url to a local file. The file is large enough that I want to download it and save it chunks rather than read() and write() the whole file as a single giant string.
The interface of urllib.urlretrieve is essentially what I want. However, I cannot see a way to set request heade... | [
"What is the harm in writing your own function using urllib2?\nimport os\nimport sys\nimport urllib2\n\ndef urlretrieve(urlfile, fpath):\n chunk = 4096\n f = open(fpath, \"w\")\n while 1:\n data = urlfile.read(chunk)\n if not data:\n print \"done.\"\n break\n f.wr... | [
3,
2
] | [] | [] | [
"download",
"http",
"python",
"urllib",
"urllib2"
] | stackoverflow_0000728118_download_http_python_urllib_urllib2.txt |
Q:
Can not remove french letters in a string returned by Python glob
I would like to rename files with french letters. I am using glob to browse the files and a function I've found on the Internet to remove the french letters. The supprime_accent seems to work ok. However, it doesn't rename files returned by the glob... | Can not remove french letters in a string returned by Python glob | I would like to rename files with french letters. I am using glob to browse the files and a function I've found on the Internet to remove the french letters. The supprime_accent seems to work ok. However, it doesn't rename files returned by the glob function.
Does anybody knows what can be the reason? Is it related wi... | [
"I see two potential problems here.\nFirst, you need to use unicode strings in your source code, and you need to tell Python what encoding the source code is in. Unfortunately doing it right doubles the number of vowels in your table... :-\\\n# -*- coding: UTF-8 -*-\n...\naccents = { u'a': [u'à', u'ã', u'á', u'â'],... | [
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0002028503_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.