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:
in mechanize, is there anyway of rewriting the url to POST to in a form?
I'm running a python script and I'm using mechanize. The form i'm trying to submit normally uses javascript to rewrite the url to POST to, so to correctly submit the form i need to manually do the same. is there anyway of doing this?
A:
Mec... | in mechanize, is there anyway of rewriting the url to POST to in a form? | I'm running a python script and I'm using mechanize. The form i'm trying to submit normally uses javascript to rewrite the url to POST to, so to correctly submit the form i need to manually do the same. is there anyway of doing this?
| [
"Mechanize doesn't process Javascript. The best way usually is to use browser to process Javascript - if you prefer do it in Python use PythonExt.\nAlso you can try Selenium - seleniumhq.org. It's used for web-site testing but can send forms too.\n",
"you may test zope http://pypi.python.org/pypi?:action=display&... | [
1,
1
] | [] | [] | [
"mechanize",
"python"
] | stackoverflow_0003656117_mechanize_python.txt |
Q:
Mac OS X python 'import vigra' error
I want to use vigra under Mac OS X 10.6.4. So I installed all dependencies with Macpotrs.
Everything compiled and I could install vigra too. But when I try to import vigra, then I get a 'Segmentation fault'. Do someone know how to solve this problem?
Here the Mac OS X error re... | Mac OS X python 'import vigra' error | I want to use vigra under Mac OS X 10.6.4. So I installed all dependencies with Macpotrs.
Everything compiled and I could install vigra too. But when I try to import vigra, then I get a 'Segmentation fault'. Do someone know how to solve this problem?
Here the Mac OS X error report:
Process: Python [784] Path:... | [
"Does your numpy work well? Did you run its tests? Its installation notes remind of ABI mismatches and right compiler choice; probably a wrong choice might lead to a segfault. The crash happens near init_module_vigranumpycore; maybe it's not vigra yet.\n"
] | [
0
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0003845702_macos_python.txt |
Q:
Encoding problem downloading HTML using mechanize and Python 2.6
browser = mechanize.Browser()
page = browser.open(url)
html = page.get_data()
print html
It shows some strange characters. I suppose that it is UTF-8 string but Python doesn't know that and cannot show it properly.
How can I convert this string to ... | Encoding problem downloading HTML using mechanize and Python 2.6 | browser = mechanize.Browser()
page = browser.open(url)
html = page.get_data()
print html
It shows some strange characters. I suppose that it is UTF-8 string but Python doesn't know that and cannot show it properly.
How can I convert this string to unicode string like
u = u'test'
| [
"It was gzipped\ndef ungzipResponse(r,b):\n headers = r.info()\n if headers['Content-Encoding']=='gzip':\n import gzip\n gz = gzip.GzipFile(fileobj=r, mode='rb')\n html = gz.read()\n gz.close()\n headers[\"Content-type\"] = \"text/html; charset=utf-8\"\n r.set_data( h... | [
4,
1,
1
] | [] | [] | [
"encoding",
"mechanize",
"python",
"unicode",
"utf_8"
] | stackoverflow_0003804572_encoding_mechanize_python_unicode_utf_8.txt |
Q:
How to call a static method of a class using method name and class name
Starting with a class like this:
class FooClass(object):
@staticmethod
def static_method(x):
print x
normally, I would call the static method of the class with:
FooClass.static_method('bar')
Is it possible to invoke this stat... | How to call a static method of a class using method name and class name | Starting with a class like this:
class FooClass(object):
@staticmethod
def static_method(x):
print x
normally, I would call the static method of the class with:
FooClass.static_method('bar')
Is it possible to invoke this static method having just the class name and the method name?
class_name = 'FooC... | [
"You shouldn't mess with locals() as suggested in other answers. If you have your classname as a string and need to resolve it, use registry of some sort. A dictionary will work fine. E.g.\nclass FooClass(object):\n @staticmethod\n def static_method(x):\n print x\n\nregistry = {'FooClass':FooClass}\n\n... | [
9,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003849576_python.txt |
Q:
itertools or hand-written generator - what is preferable?
I have a number of Python generators, which I want to combine into a new generator. I can easily do this by a hand-written generator using a bunch of yield statements.
On the other hand, the itertools module is made for things like this and to me it seems a... | itertools or hand-written generator - what is preferable? | I have a number of Python generators, which I want to combine into a new generator. I can easily do this by a hand-written generator using a bunch of yield statements.
On the other hand, the itertools module is made for things like this and to me it seems as if the pythonic way to create the generator I need is to plug... | [
"I did some profiling and the regular generator function is way faster than either your second generator or my implementation. \n$ python -mtimeit -s'import gen; a, b = gen.make_test_case()' 'list(gen.generator1(a, b))'\n10 loops, best of 3: 169 msec per loop\n\n$ python -mtimeit -s'import gen; a, b = gen.make_test... | [
7
] | [] | [] | [
"generator",
"iterator",
"python"
] | stackoverflow_0003849702_generator_iterator_python.txt |
Q:
Python mechanize, following link by url and what is the nr parameter?
I'm sorry to have to ask something like this but python's mechanize documentation seems to really be lacking and I can't figure this out.. they only give one example that I can find for following a link:
response1 = br.follow_link(text_regex=r"c... | Python mechanize, following link by url and what is the nr parameter? | I'm sorry to have to ask something like this but python's mechanize documentation seems to really be lacking and I can't figure this out.. they only give one example that I can find for following a link:
response1 = br.follow_link(text_regex=r"cheese\s*shop", nr=1)
But I don't want to use a regex, I just want to follo... | [
"br.follow_link takes either a Link object or a keyword arg (such as nr=0). \nbr.links() lists all the links.\nbr.links(url_regex='...') lists all the links whose urls matches the regex.\nbr.links(text_regex='...') lists all the links whose link text matches the regex.\nbr.follow_link(nr=num) follows the numth link... | [
50,
16,
2,
2
] | [] | [] | [
"mechanize",
"python"
] | stackoverflow_0003569622_mechanize_python.txt |
Q:
Python - The request headers for mechanize
I am looking for a way to view the request (not response) headers, specifically what browser mechanize claims to be. Also how would I go about manipulating them, eg setting another browser?
Example:
import mechanize
browser = mechanize.Browser()
# Now I want to make a req... | Python - The request headers for mechanize | I am looking for a way to view the request (not response) headers, specifically what browser mechanize claims to be. Also how would I go about manipulating them, eg setting another browser?
Example:
import mechanize
browser = mechanize.Browser()
# Now I want to make a request to eg example.com with custom headers using... | [
"browser.addheaders = [('User-Agent', 'Mozilla/5.0 blahblah')]\n\n",
"You've got an answer on how to change the headers, but if you want to see the exact headers that are being used try using a proxy that displays the traffic. e.g. Fiddler2 on windows or see this question for some Linux altenatives.\n",
"you ca... | [
8,
2,
2
] | [] | [] | [
"mechanize",
"python"
] | stackoverflow_0003325052_mechanize_python.txt |
Q:
python mechanize proxy question
I've got mechanize setup and working with python. I am adding support for using a proxy, but how do I check that I am actually using the proxy?
Here is some code I am using:
ip = 'some proxy ip address'
br.set_proxies({"http://": ip} )
I started to wonder if it was working becau... | python mechanize proxy question | I've got mechanize setup and working with python. I am adding support for using a proxy, but how do I check that I am actually using the proxy?
Here is some code I am using:
ip = 'some proxy ip address'
br.set_proxies({"http://": ip} )
I started to wonder if it was working because just to do some testing I typed in... | [
"maybe like this ?\nbr = mechanize.Browser()\nbr.set_proxies({\"http\": '127.0.0.1:80'})\n\nyou need to debug for more information\nbr.set_debug_http(True)\nbr.set_debug_redirects(True)\n\n",
"I am not sure how to handle this issue with mechanize, but you could read the next link that explains how to do it withou... | [
2,
0
] | [] | [] | [
"django",
"mechanize",
"proxy",
"python"
] | stackoverflow_0002227117_django_mechanize_proxy_python.txt |
Q:
using unicode characters with wxPython
i have a problem with wxpython and his rich text control, when I try to insert unicode characters... \xb2 prints an apex '2', '\u2074' should print an apex '4'...
edit: I use windows vista... and I tried 'coding cp1252 ' and 'utf-8' but with the same result...
2edit:
on vista... | using unicode characters with wxPython | i have a problem with wxpython and his rich text control, when I try to insert unicode characters... \xb2 prints an apex '2', '\u2074' should print an apex '4'...
edit: I use windows vista... and I tried 'coding cp1252 ' and 'utf-8' but with the same result...
2edit:
on vista it crashs, on xp it shows a strange square ... | [
"If you want Unicode support then you should be using the unicode version of wxpython.\n\nThere are two versions of wxPython for\n each of the supported Python versions\n on Win32. They are nearly identical,\n except one of them has been compiled\n with support for the Unicode version\n of the platform APIs. U... | [
2,
0
] | [] | [] | [
"character",
"python",
"unicode",
"wxpython"
] | stackoverflow_0003849817_character_python_unicode_wxpython.txt |
Q:
Using Python and Mechanize with ASP Forms
I'm trying to submit a form on an .asp page but Mechanize does not recognize the name of the control. The form code is:
<form id="form1" name="frmSearchQuick" method="post">
....
<input type="button" name="btSearchTop" value="SEARCH" class="buttonctl" onClick="uf_Browse('... | Using Python and Mechanize with ASP Forms | I'm trying to submit a form on an .asp page but Mechanize does not recognize the name of the control. The form code is:
<form id="form1" name="frmSearchQuick" method="post">
....
<input type="button" name="btSearchTop" value="SEARCH" class="buttonctl" onClick="uf_Browse('dledir_search_quick.asp');" >
My code is as fo... | [
"The button doesn't submit the form - it calls some javascript function.\nMechanize can't run javascript, so you can't use it to click that button.\nThe easy way out is to read that function yourself, and see what it does - if it just submits the form, then maybe you can get around it by submitting the form without... | [
5,
0
] | [] | [] | [
"asp_classic",
"mechanize",
"python"
] | stackoverflow_0002679595_asp_classic_mechanize_python.txt |
Q:
Filling textarea with Python mechanize module
Is there a way to fill out textarea that is part of form using mechanize module for Python?
A:
The forms reference has a couple of examples of filling text controls in response objects.
A relevant quote:
# The kind argument can also take values "multilist", "singleli... | Filling textarea with Python mechanize module | Is there a way to fill out textarea that is part of form using mechanize module for Python?
| [
"The forms reference has a couple of examples of filling text controls in response objects.\nA relevant quote:\n# The kind argument can also take values \"multilist\", \"singlelist\", \"text\",\n# \"clickable\" and \"file\":\n# find first control that will accept text, and scribble in it\nform.set_value(\"rhubarb ... | [
6,
6,
1
] | [] | [] | [
"mechanize",
"python",
"textarea"
] | stackoverflow_0002881121_mechanize_python_textarea.txt |
Q:
Convert gzipped data fetched by urllib2 to HTML
I currently use mechanize to read gzipped web page as below:
br = mechanize.Browser()
br.set_handle_gzip(True)
response = br.open(url)
data = response.read()
I wonder how to decompress gzipped data fetched by urllib2 to HTML text?
req = urllib2.Request(url)
opener =... | Convert gzipped data fetched by urllib2 to HTML | I currently use mechanize to read gzipped web page as below:
br = mechanize.Browser()
br.set_handle_gzip(True)
response = br.open(url)
data = response.read()
I wonder how to decompress gzipped data fetched by urllib2 to HTML text?
req = urllib2.Request(url)
opener = urllib2.build_opener()
response = opener.open(req)
d... | [
"Try this:\nimport StringIO\ndata = StringIO.StringIO(data)\nimport gzip\ngzipper = gzip.GzipFile(fileobj=data)\nhtml = gzipper.read()\n\nhtml should now hold the HTML (Print it to see). See here for more info.\n"
] | [
14
] | [
"def ungzip(r,b):\n headers = r.info()\n if ('Content-Encoding' in headers.keys() and headers['Content-Encoding']=='gzip') or \\\n ('content-encoding' in headers.keys() and headers['content-encoding']=='gzip'):\n import gzip\n gz = gzip.GzipFile(fileobj=r, mode='rb')\n html = gz.rea... | [
-2
] | [
"gzip",
"python",
"urllib2"
] | stackoverflow_0001704754_gzip_python_urllib2.txt |
Q:
Handling errors in Python scripts
Using pyblog.py, I got the following error, which I then tried to more gracefully handle:
Traceback (most recent call last):
File "C:\Python26\Lib\SITE-P~1\PYTHON~1\pywin\framework\scriptutils.py", line 325, in RunScript
exec codeObject in __main__.__dict__
File "C:\Docume... | Handling errors in Python scripts | Using pyblog.py, I got the following error, which I then tried to more gracefully handle:
Traceback (most recent call last):
File "C:\Python26\Lib\SITE-P~1\PYTHON~1\pywin\framework\scriptutils.py", line 325, in RunScript
exec codeObject in __main__.__dict__
File "C:\Documents and Settings\mmorisy\Desktop\My Dro... | [
"Yes, it is using BlogError, but you have not imported BlogError into your namespace to reference. You instead want to be using pyblog.BlogError:\nfor blog in bloglist:\n try:\n blogurl = pyblog.WordPress('http://example.com' + blog + 'xmlrpc.php', 'admin', 'laxbro24')\n date = blogurl.get_recent_p... | [
5,
2,
2
] | [] | [] | [
"python",
"wordpress",
"xml"
] | stackoverflow_0003850077_python_wordpress_xml.txt |
Q:
Jython - attempting to call functions from JFrame, receiving 'NoneType' error
So I'm playing around with Jython, trying to slap together a generic GUI. Nothing beyond what they have on the Jython Wiki for swing examples. So I declare a JFrame, and then try to add a panel, some text fields, all that good stuff. I g... | Jython - attempting to call functions from JFrame, receiving 'NoneType' error | So I'm playing around with Jython, trying to slap together a generic GUI. Nothing beyond what they have on the Jython Wiki for swing examples. So I declare a JFrame, and then try to add a panel, some text fields, all that good stuff. I get this error when I run it, however. "'NoneType' object has no attribute 'add'"
He... | [
"In this line:\nframe = JFrame('E-mail Gathering', defaultCloseOperation = JFrame.EXIT_ON_CLOSE, size =(600,400), locationRelativeTo = None).setVisible(True)\n\nyou are creating a JFrame, calling its setVisible method, and assigning the return value of setVisible to frame. setVisible doesn't return a value, so fram... | [
1
] | [] | [] | [
"jython",
"python",
"swing"
] | stackoverflow_0003850144_jython_python_swing.txt |
Q:
Why won't the len() function output anything in python 3.1.2?
I installed the 3.1.2 IDLE python console, then I entered this code:
>>> a = ['a', 'b', 'c', 'd']
>>> len(a)
4
Directly from the python official docs http://docs.python.org/py3k/tutorial/introduction.html#lists
But it does not work in the interpreter a... | Why won't the len() function output anything in python 3.1.2? | I installed the 3.1.2 IDLE python console, then I entered this code:
>>> a = ['a', 'b', 'c', 'd']
>>> len(a)
4
Directly from the python official docs http://docs.python.org/py3k/tutorial/introduction.html#lists
But it does not work in the interpreter as it should, it does not return 4.
What am I doing wrong? Are the o... | [
"There is no bug; you have misunderstood what should happen.\nPython can be called interactively (by running python.exe at the prompt). This mode automatically prints the result of a line when it is finished, for ease of reading/debugging. However, it's not very useful for writing any serious amount of code.\nThe w... | [
6
] | [] | [] | [
"list",
"python"
] | stackoverflow_0003850098_list_python.txt |
Q:
Google App Engine counters
For all my data in the GAE Datastore I have a model for keeping track of counters/total number of records (since we can't use traditional SUM queries). I want to know the most efficient way of incrementing these global count values whenever I insert/delete a record. This is what I'm curr... | Google App Engine counters | For all my data in the GAE Datastore I have a model for keeping track of counters/total number of records (since we can't use traditional SUM queries). I want to know the most efficient way of incrementing these global count values whenever I insert/delete a record. This is what I'm currently doing:
counter = DBCounter... | [
"There are a few issues with your approach:\n\nIt may under-count since you don't use a transaction to atomically update the counter.\nIt is inefficient: \n\n\nContention may become a problem if you need to update this counter frequently. Since you only have one counter, it won't scale well. Datastore entities ca... | [
5,
4
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python",
"transactions"
] | stackoverflow_0003850180_google_app_engine_google_cloud_datastore_python_transactions.txt |
Q:
Replacing a single color in PIL?
I have an Image, I'd like to replace all the pixels of one color with those in a different color, what is the simplest way to go about that?
More or less I have an image in tkinter, and when a button is pressed I want the color to change.
A:
try this.
#!/usr/bin/python
from PI... | Replacing a single color in PIL? | I have an Image, I'd like to replace all the pixels of one color with those in a different color, what is the simplest way to go about that?
More or less I have an image in tkinter, and when a button is pressed I want the color to change.
| [
"try this.\n#!/usr/bin/python\nfrom PIL import Image\nimport sys\n\nimg = Image.open(sys.argv[1])\nimg = img.convert(\"RGBA\")\n\npixdata = img.load()\n\n# Clean the background noise, if color != white, then set to black.\n\nfor y in xrange(img.size[1]):\n for x in xrange(img.size[0]):\n if pixdata[x, y] ... | [
4,
3
] | [] | [] | [
"python",
"python_imaging_library",
"tkinter"
] | stackoverflow_0003169384_python_python_imaging_library_tkinter.txt |
Q:
python string is default global
I have a question about global variable in Python.
The code is following. If I do not use global M in function test,
It would issue error.
But Why it does not show error for string s. I do not declare it as global.
global M
M = []
s = "abc"
def test():
### global M
print ... | python string is default global | I have a question about global variable in Python.
The code is following. If I do not use global M in function test,
It would issue error.
But Why it does not show error for string s. I do not declare it as global.
global M
M = []
s = "abc"
def test():
### global M
print M
M.append(s)
print M
UnboundLo... | [
"\nIf I do not use global M in function\n test, It would issue error.\n\nThis statement of yours is simply not true!!!\n>>> M = []\n>>> s = \"abc\"\n>>> \n>>> def test():\n... M.append(s)\n... \n>>> M\n[]\n>>> test()\n>>> M\n['abc']\n\nI think you're confusing two utterly and completely different concepts:\n\n... | [
6,
3,
0
] | [] | [] | [
"global",
"python",
"scope",
"string"
] | stackoverflow_0003840349_global_python_scope_string.txt |
Q:
Where do you get Python SOAPPy forwindows?
I can't seem to install it, computer doesn't know what to open it with, is there something wrong? Do you know a website where I can install it?
A:
SOAPPy is now part of Python Web Services. You can get it from the Python Web Services page at sourceforge.
| Where do you get Python SOAPPy forwindows? | I can't seem to install it, computer doesn't know what to open it with, is there something wrong? Do you know a website where I can install it?
| [
"SOAPPy is now part of Python Web Services. You can get it from the Python Web Services page at sourceforge. \n"
] | [
0
] | [] | [] | [
"python",
"soappy"
] | stackoverflow_0003850545_python_soappy.txt |
Q:
Encrypting a Sqlite db file that will be bundled in a pyexe file
I have been working on developing this analytical tool to help interpret and analyze a database that is bundled within the package. It is very important for us to secure the database in a way that can only be accessed with our software. What is the b... | Encrypting a Sqlite db file that will be bundled in a pyexe file | I have been working on developing this analytical tool to help interpret and analyze a database that is bundled within the package. It is very important for us to secure the database in a way that can only be accessed with our software. What is the best way of achieving it in Python?
I am aware that there may not be a... | [
"Someone has gotten Python and SQLCipher working together by rebuilding SQLCipher as a DLL and replacing Python's sqlite3.dll here.\n",
"This question comes up on the SQLite users mailing list about once a month.\nNo matter how much encryption etc you do, if the database is on the client machine then the key to d... | [
5,
3
] | [] | [] | [
"database",
"encryption",
"python",
"sqlite"
] | stackoverflow_0003848658_database_encryption_python_sqlite.txt |
Q:
Multiple visualizations in one page
I am using python-visualization library for computing the datasource.
I tried to put more than one visualization in a single page. Both are line charts and data comes from a seperate URLs for each visualizations.
<script type="text/javascript" src="http://www.google.com/jsapi"><... | Multiple visualizations in one page | I am using python-visualization library for computing the datasource.
I tried to put more than one visualization in a single page. Both are line charts and data comes from a seperate URLs for each visualizations.
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" s... | [
"You can try something like \nfunction Charts(){\n var self = this;\n self.chart = [];\n self.settings = { width: 650, height: 250 };\n self.add = function(type, element, dataTable, options){\n self.chart.push({\n o: new google.visualization[type]($(element)[0]),\n data: dat... | [
0,
0
] | [] | [] | [
"django",
"google_visualization",
"javascript",
"jquery",
"python"
] | stackoverflow_0001448638_django_google_visualization_javascript_jquery_python.txt |
Q:
Google Chart API: trouble with rendering a XYLine graph
I'm trying to make an XYLine with the Google Chart API via the not-so-well-documented GChartWrapper libraries.
Here's a portion of the code that is supposed to generate the graph:
data = []
traffic_max = 0
date_minmax = []
#I have a number of timestamped rea... | Google Chart API: trouble with rendering a XYLine graph | I'm trying to make an XYLine with the Google Chart API via the not-so-well-documented GChartWrapper libraries.
Here's a portion of the code that is supposed to generate the graph:
data = []
traffic_max = 0
date_minmax = []
#I have a number of timestamped readings in two series
for site in sites:
site_data = get_data... | [
"The problem was here:\nchart.scale(date_minmax[0], date_minmax[1], 0, traffic_max)\n\nThe Google API allows you to define a different scale per each series. Thus, you need to specify the scaling for each series, whereas the above only affected the first series.\nChanging that line to:\nchart.scale(*[date_minmax[0]... | [
0
] | [] | [] | [
"google_visualization",
"python"
] | stackoverflow_0003850561_google_visualization_python.txt |
Q:
Editing values in a xml file with Python
Hey. I want to have a config.xml file for settings in a Python web app.
I made car.xml manually. It looks like this:
<car>
<lights>
<blinkers>off</blinkers>
</lights>
</car>
Now I want to see whether the blinkers are on or off, using xml.etree.ElementTree.
... | Editing values in a xml file with Python | Hey. I want to have a config.xml file for settings in a Python web app.
I made car.xml manually. It looks like this:
<car>
<lights>
<blinkers>off</blinkers>
</lights>
</car>
Now I want to see whether the blinkers are on or off, using xml.etree.ElementTree.
import xml.etree.ElementTree as ET
tree = ET.p... | [
"You can remove nodes by calling the parent node's remove method,\nand insert nodes by calling ET.SubElement:\nimport xml.etree.ElementTree as ET\n\ndef flip_lights(tree):\n lights = tree.find('lights')\n state=get_blinker(tree)\n blinkers = tree.find('lights/blinkers')\n lights.remove(blinkers)\n ne... | [
2,
2,
1,
0,
0
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0003849976_elementtree_python_xml.txt |
Q:
Python multiprocessing
I have a "master" process that needs to spawn some child processes.
How can I manage these child processes? (for example, restart if the process is dead)
Thanks!
A:
Have a look at celery.
A:
If you use the multiprocessing package, every child process has is_alive method you can check. So... | Python multiprocessing | I have a "master" process that needs to spawn some child processes.
How can I manage these child processes? (for example, restart if the process is dead)
Thanks!
| [
"Have a look at celery.\n",
"If you use the multiprocessing package, every child process has is_alive method you can check. So one option to to hold a list of all running processes and periodically check is_alive and re-spawn dead processes.\nIf you're on POSIX system, you can also catch SIGCHLD (using signal) an... | [
4,
3,
1
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0003850708_multiprocessing_python.txt |
Q:
Python style: for-in syntax, checking for empty lists and dictionaries
I'm new to python and haven't yet read a lot of code to verify which styles are considered 'pythonic'.
As I've started to code, I've been using this pattern alot.
listThatMightBeEmpty = []
for items in listThatMightBeEmpty:
print "this may ... | Python style: for-in syntax, checking for empty lists and dictionaries | I'm new to python and haven't yet read a lot of code to verify which styles are considered 'pythonic'.
As I've started to code, I've been using this pattern alot.
listThatMightBeEmpty = []
for items in listThatMightBeEmpty:
print "this may or may not print but the loop won't cause any errors"
I assume that it woul... | [
"Yes you are right. There are no gotchas here. You can use it on an empty list. \n\nOld but still holds good : http://effbot.org/zone/python-list.htm\n\n",
"To check whether a list is empty, you can do this:\n>>> x = []\n>>> if not x:\n # do something\n\nIf the list is empty, # do something will run and y... | [
2,
1,
1
] | [] | [] | [
"idioms",
"list",
"python"
] | stackoverflow_0003850791_idioms_list_python.txt |
Q:
Rotate dictionary keys in python
I have a dictionary with several values that I want to keep constant, but I need to rotate them throughout the different keys. Is there a built in function or external library that would be able to do this or would I be better off just writing the entire thing myself?
Example of wh... | Rotate dictionary keys in python | I have a dictionary with several values that I want to keep constant, but I need to rotate them throughout the different keys. Is there a built in function or external library that would be able to do this or would I be better off just writing the entire thing myself?
Example of what I am trying to do:
>>> firstdict = ... | [
">>> from itertools import izip\n>>> def rotateItems(dictionary):\n... if dictionary:\n... keys = dictionary.iterkeys()\n... values = dictionary.itervalues()\n... firstkey = next(keys)\n... dictionary = dict(izip(keys, values))\n... dictionary[firstkey] = next(values)\n... return dictionary\... | [
7
] | [] | [] | [
"dictionary",
"key",
"python",
"rotation"
] | stackoverflow_0003850786_dictionary_key_python_rotation.txt |
Q:
Why is this division not performed correctly?
I've a strange issue in Python: the division is not performed correctly:
print pointB[1]
print pointA[1]
print pointB[0]
print pointA[0]
print (pointB[1]-pointA[1]) / (pointB[0]-pointA[0])
These are the results:
100
50
100
40
0
thanks
A:
The above behavior is tru... | Why is this division not performed correctly? | I've a strange issue in Python: the division is not performed correctly:
print pointB[1]
print pointA[1]
print pointB[0]
print pointA[0]
print (pointB[1]-pointA[1]) / (pointB[0]-pointA[0])
These are the results:
100
50
100
40
0
thanks
| [
"The above behavior is true for Python 2. The behavior of / was fixed in Python 3. In Python 2 you can use:\nfrom __future__ import division\n\nand then use / to get the result you desire.\n>>> 5 / 2\n2\n>>> from __future__ import division\n>>> 5 / 2\n2.5\n\nSince you are dividing two integers, you get the result a... | [
18,
9,
3
] | [] | [] | [
"division",
"python",
"python_2.x"
] | stackoverflow_0003851002_division_python_python_2.x.txt |
Q:
Running matplotlib in tkinter
I have this beautiful sphere I made in matplotlib. How would I go about putting it in a tkinter frame widget? It'd be nice to be able to integrate it into an existing tkinter GUI. Also is it possible to rid of the menu bar below the display? I have no need to save the output or zoom, ... | Running matplotlib in tkinter | I have this beautiful sphere I made in matplotlib. How would I go about putting it in a tkinter frame widget? It'd be nice to be able to integrate it into an existing tkinter GUI. Also is it possible to rid of the menu bar below the display? I have no need to save the output or zoom, so it's useless to me.
from mpl_to... | [
"Have a look at the examples for embedding plots in a tk GUI, it should be enough to get you started in the right direction.\nuser_interfaces example code: embedding_in_tk.py\nuser_interfaces example code: embedding_in_tk2.py\nAs for removing the toolbar, it's a case of not adding it when you are embedding plots in... | [
22
] | [] | [] | [
"matplotlib",
"python",
"tkinter"
] | stackoverflow_0003845407_matplotlib_python_tkinter.txt |
Q:
Embedding Matplotlib in Tkinter, display problems
I'm currently trying to graph a sphere in a tkinter window using matplotlib. How do I go about making the display square? I'd like the sphere to have as little distortion as possible.
My code:
#!/usr/bin/env python
import matplotlib
matplotlib.use('TkAgg')
from mp... | Embedding Matplotlib in Tkinter, display problems | I'm currently trying to graph a sphere in a tkinter window using matplotlib. How do I go about making the display square? I'd like the sphere to have as little distortion as possible.
My code:
#!/usr/bin/env python
import matplotlib
matplotlib.use('TkAgg')
from mpl_toolkits.mplot3d import axes3d,Axes3D
import matplot... | [
"You can make use of pyplot.figure()'s figsize paramater to set the figure size.\ne.g. \nself.fig = plt.figure(figsize=(5,5)) \n",
"Did you try to set the figure size attributes?\nfig.set_figwidth and fig.set_figheigh\nt\n"
] | [
3,
1
] | [] | [] | [
"matplotlib",
"python",
"tkinter"
] | stackoverflow_0003847242_matplotlib_python_tkinter.txt |
Q:
Refactoring long statement in Python
I have a very long conditional statement for deciding what action to take for a pair of variables a and b.
action = 0 if (a==0) else 1 if (a>1 and b==1) else 2 if (a==1 and b>1) else 3 if (a>1 and b>1) else -1
While it is nice with the compactness (in lines;) ) of this stateme... | Refactoring long statement in Python | I have a very long conditional statement for deciding what action to take for a pair of variables a and b.
action = 0 if (a==0) else 1 if (a>1 and b==1) else 2 if (a==1 and b>1) else 3 if (a>1 and b>1) else -1
While it is nice with the compactness (in lines;) ) of this statement, it must exist a more elegant way to do... | [
"if a==0:\n action = 0\nelif a>1 and b==1:\n action = 1\nelif a==1 and b>1:\n action = 2\nelif a>1 and b>1:\n action = 3\nelse:\n action = -1\n\nFrom the Zen of Python (excerpts):\nSimple is better than complex.\nFlat is better than nested.\nReadability counts.\n\n",
"If a and b both have known, small, ... | [
9,
2
] | [] | [] | [
"conditional",
"if_statement",
"python",
"refactoring"
] | stackoverflow_0003851094_conditional_if_statement_python_refactoring.txt |
Q:
Why do I get inconsistent exceptions on Python?
I encountered a very strange behavior in Python, a behavior that is not consistent.
...
except IOError as msg:
sys.exit("###ERROR IOError: %s" % (msg))
Usually this would get me a message like:
###ERROR IOError: [Errno 13] Permission denied: 'filename'
In same ... | Why do I get inconsistent exceptions on Python? | I encountered a very strange behavior in Python, a behavior that is not consistent.
...
except IOError as msg:
sys.exit("###ERROR IOError: %s" % (msg))
Usually this would get me a message like:
###ERROR IOError: [Errno 13] Permission denied: 'filename'
In same cases the above code is giving me a tuple instead of ... | [
"First, when reraising an exception, never do except Exc as e: raise e. It is always just plain raise with no arguments. This will preserve the traceback.\nNo, this has nothing to do with sys.exit and everything to do with how the exception was instantiated. You are always getting an exception; just sometimes its s... | [
5,
1,
0
] | [] | [] | [
"exception_handling",
"ioerror",
"python"
] | stackoverflow_0003638656_exception_handling_ioerror_python.txt |
Q:
Urllib raising invalid argument URLError in Python 3, urllib.request.urlopen
New to Python, but I'm trying to...retrieve data from a site:
import urllib.request
response = urllib.request.urlopen("http://www.python.org")
This is the same code I've seen from the Python 3.1 docs. And a lot of sites.
However, I get:
... | Urllib raising invalid argument URLError in Python 3, urllib.request.urlopen | New to Python, but I'm trying to...retrieve data from a site:
import urllib.request
response = urllib.request.urlopen("http://www.python.org")
This is the same code I've seen from the Python 3.1 docs. And a lot of sites.
However, I get:
Message File Name Line Position
Traceback
<module... | [
"Maybe try turning off the firewall? Since you are on Windows, that might be the problem.\n"
] | [
2
] | [] | [] | [
"python",
"python_3.x",
"urllib",
"urlopen"
] | stackoverflow_0003851224_python_python_3.x_urllib_urlopen.txt |
Q:
Why does my GtkTreeView sort func receive a row with None in it?
I've set up a gtk.TreeView with a gtk.TreeStore. One column contains formatted dollar amounts, and I've set up sorting by that column as follows:
def sortmon(model, i1, i2):
v1 = model[i1][COL_MONEY]
v2 = model[i2][COL_MONEY]
... | Why does my GtkTreeView sort func receive a row with None in it? | I've set up a gtk.TreeView with a gtk.TreeStore. One column contains formatted dollar amounts, and I've set up sorting by that column as follows:
def sortmon(model, i1, i2):
v1 = model[i1][COL_MONEY]
v2 = model[i2][COL_MONEY]
return cmp(float(v1.replace("$","").replace(",","")),
... | [
"If you append a row to a sorted model, GTK+ automatically searches for a proper position for it and thus your sort function is called if it's on that column. You should either handle None specially, or specify initial values in append() call, like:\nmodel.append (parent, [x, y, z])\n\nThe latter of course only so... | [
1
] | [] | [] | [
"gtk",
"gtktreeview",
"pygtk",
"python"
] | stackoverflow_0003842609_gtk_gtktreeview_pygtk_python.txt |
Q:
Web page scraping: press javascript button
I am trying to scrape a web page and to recieve the data i need to press a button. This is the source code for the button:
"a class="press-me_btn" href="javascript:void( NewPage['DemoPage'].startDemo() );" id="js_press-me_btn">PRESS ME
Is it possible to "press" the butto... | Web page scraping: press javascript button | I am trying to scrape a web page and to recieve the data i need to press a button. This is the source code for the button:
"a class="press-me_btn" href="javascript:void( NewPage['DemoPage'].startDemo() );" id="js_press-me_btn">PRESS ME
Is it possible to "press" the button somehow without using a browser? either by usi... | [
"In this case these is not a button, it is an anchor element, i think that you will need to run the js code, that is in the href attribute:\njavascript:void( NewPage['DemoPage'].startDemo() );\n\n"
] | [
1
] | [] | [] | [
"python",
"screen_scraping",
"wget"
] | stackoverflow_0003851413_python_screen_scraping_wget.txt |
Q:
Trying to group values?
I have some data like this:
1 2
3 4
5 9
2 6
3 7
and am looking for an output like this (group-id and the members of that group):
1: 1 2 6
2: 3 4 7
3: 5 9
First row because 1 is "connected" to 2 and 2 is connected to 6.
Second row because 3 is connected to 4 and 3 is connected to 7
This lo... | Trying to group values? | I have some data like this:
1 2
3 4
5 9
2 6
3 7
and am looking for an output like this (group-id and the members of that group):
1: 1 2 6
2: 3 4 7
3: 5 9
First row because 1 is "connected" to 2 and 2 is connected to 6.
Second row because 3 is connected to 4 and 3 is connected to 7
This looked to me like a graph trave... | [
"I've managed O(n log n).\nHere is a (somewhat intense) C++ implementation:\n#include <boost/pending/disjoint_sets.hpp>\n#include <boost/property_map/property_map.hpp>\n\n#include <map>\n#include <set>\n#include <iostream>\n\n\ntypedef std::map<int, int> rank_t;\ntypedef std::map<int, int> parent_t;\n\ntypedef boos... | [
4,
1,
1,
1,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"algorithm",
"c++",
"graph",
"php",
"python"
] | stackoverflow_0003848239_algorithm_c++_graph_php_python.txt |
Q:
Easiest way to send emails via Python
Possible Duplicate:
Receive and send emails in python
I've been looking into sending mail with python and found a few different options (setting up my own mailserver, using gmail's smtp, etc) but was wondering if there was some simple way to do it. I am running the python sc... | Easiest way to send emails via Python |
Possible Duplicate:
Receive and send emails in python
I've been looking into sending mail with python and found a few different options (setting up my own mailserver, using gmail's smtp, etc) but was wondering if there was some simple way to do it. I am running the python script via wsgi on apache2 on an ubuntu box.... | [
"There's a great example here. As you seem to know, you'll just need an smtp server to do the actual sending. That particular step is not dependent on python.\nIf g-mails smtp server let's you send mail, I'd go that route. When I last set this up (for an svn backup script), I luckily got to use my company's smtp se... | [
1
] | [] | [] | [
"email",
"python",
"smtp",
"ubuntu"
] | stackoverflow_0003851633_email_python_smtp_ubuntu.txt |
Q:
Compare folders recursively using python
I'm going to implement recursive folder comparison on python. What do you think would best algorithm for this?
Get two lists of the files for the folders
Sort both lists
Compare using filecmp module for a file
Repeat for every folder recursively
In result I need to get on... | Compare folders recursively using python | I'm going to implement recursive folder comparison on python. What do you think would best algorithm for this?
Get two lists of the files for the folders
Sort both lists
Compare using filecmp module for a file
Repeat for every folder recursively
In result I need to get only the list of the files that are different (c... | [
"Make recursive search over directory and for each file store md5 or sha checksum of file in dictionary as key and path/name as value. Make this dictionary for both directories. Then you can remove pairs from each directory and result is missing/different files.\nThis will make simple O(n) algorhitm, where n is vo... | [
2,
1
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0003851884_algorithm_python.txt |
Q:
Python: Rare problem generating .gif with ffmpeg
I have a problem when I generate an animated gif from a movie.avi using ffmpeg from python in Win7.
If I open a cmd window and execute this line:
"C:\ffmpeg\ffmpeg.exe" -i "C:\ffmpeg\video.avi" -pix_fmt rgb24 -r 10.0 -loop_output 0 -ss 5 -t 10 -s 352x288 -f gif "C:\... | Python: Rare problem generating .gif with ffmpeg | I have a problem when I generate an animated gif from a movie.avi using ffmpeg from python in Win7.
If I open a cmd window and execute this line:
"C:\ffmpeg\ffmpeg.exe" -i "C:\ffmpeg\video.avi" -pix_fmt rgb24 -r 10.0 -loop_output 0 -ss 5 -t 10 -s 352x288 -f gif "C:\ffmpeg\video.gif"
ffmpeg.exe generates a gif perfectl... | [
"Your arglist for spawnv needs to start with \"C:\\\\ffmpeg\\\\ffmpeg.exe\". Try that and see how it goes.\nargList = [\"C:\\\\ffmpeg\\\\ffmpeg.exe\", \"-i\", \"C:\\\\ffmpeg\\\\video.avi\", \"-pix_fmt\", \"rgb24\", \"-r\", \"10.0\", \"-loop_output\", \"0\", \"-ss\", \"5\", \"-t\", \"10\", \"-s\", \"352x288\", \"-f\... | [
1,
0
] | [] | [] | [
"cmd",
"gif",
"python",
"thumbnails"
] | stackoverflow_0003851966_cmd_gif_python_thumbnails.txt |
Q:
Reactor stopping earlier than I would have expected?
I am trying to teach myself some rudimentary Twisted programming thanks to this tutorial and many others. I have come to this current example which I Can't figure out why it's doing what it is doing.
Short summary: I have instantiated three reactors that count d... | Reactor stopping earlier than I would have expected? | I am trying to teach myself some rudimentary Twisted programming thanks to this tutorial and many others. I have come to this current example which I Can't figure out why it's doing what it is doing.
Short summary: I have instantiated three reactors that count down from 5 to 1 with different delays in their counting. ... | [
"I am unfamiliar with twisted, but from skimming google results it looks like reactor is an event loop. You only have one of them, so the first counter to hit reactor.stop() stops the loop.\nTo do what you want you need to remove the reactor.stop() calls and structure things so that when the last timer hits the end... | [
1,
0
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0003851899_python_twisted.txt |
Q:
Justadistraction: tokenizing English without whitespaces. Murakami SheepMan
I wondered how you would go about tokenizing strings in English (or other western languages) if whitespaces were removed?
The inspiration for the question is the Sheep Man character in the Murakami novel 'Dance Dance Dance'
In the novel, t... | Justadistraction: tokenizing English without whitespaces. Murakami SheepMan | I wondered how you would go about tokenizing strings in English (or other western languages) if whitespaces were removed?
The inspiration for the question is the Sheep Man character in the Murakami novel 'Dance Dance Dance'
In the novel, the Sheep Man is translated as saying things like:
"likewesaid, we'lldowhatwecan.... | [
"I actually did something like this for work about eight months ago. I just used a dictionary of English words in a hashtable (for O(1) lookup times). I'd go letter by letter matching whole words. It works well, but there are numerous ambiguities. (asshit can be ass hit or as shit). To resolve those ambiguities wou... | [
4,
2,
1,
1
] | [] | [] | [
"linguistics",
"nlp",
"python"
] | stackoverflow_0003851723_linguistics_nlp_python.txt |
Q:
Python: obtain the url?
Whats the simpliest way to obtain the URL of the webpage you are currently on?
For example if i have a python function and i call it from within a webpage, whats the best way to obtain the URL. What maybe an easier question how is how do you obtain the variables passed within the URL i.e. a... | Python: obtain the url? | Whats the simpliest way to obtain the URL of the webpage you are currently on?
For example if i have a python function and i call it from within a webpage, whats the best way to obtain the URL. What maybe an easier question how is how do you obtain the variables passed within the URL i.e. after the "?"
I've tried calli... | [
"Try using\ndef return_query(self):\n return self.request.URL\n\nPython is case-sensitive. \nNote that I have not tried this myself, but after looking at the documentation, I would hazard a guess that your only problem is the case of URL - make sure it is all capitals and you should be fine.\n",
"Is this a Zo... | [
1,
1
] | [] | [] | [
"python",
"zope"
] | stackoverflow_0003252010_python_zope.txt |
Q:
Sending email from gmail using Python
I'm trying to teaching myself how to program by building programs/scrips that will be useful to me. I'm trying to retool a script I found online to send an email through gmail using a python script (Source).
This example has a portion of code to attach files, which I don't wan... | Sending email from gmail using Python | I'm trying to teaching myself how to program by building programs/scrips that will be useful to me. I'm trying to retool a script I found online to send an email through gmail using a python script (Source).
This example has a portion of code to attach files, which I don't want/need. I have tweaked the code so that I d... | [
"The sample code you're using creates a multi-part MIME message. Everything is an attachment, including the message body. If you just want to send a plain old single-part plain text or HTML message, you don't need any of the MIME stuff. It just adds complexity. See that bit in your sample's sendmail() call where it... | [
5,
1
] | [] | [] | [
"gmail",
"python"
] | stackoverflow_0003852193_gmail_python.txt |
Q:
python re problem
i test re on some pythonwebshelll, all of them are encounter issue
if i use
a=re.findall(r"""<ul>[\s\S]*?<li><a href="(?P<link>[\s\S]*?)"[\s\S]*?<img src="(?P<img>[\s\S]*?)"[\s\S]*?<br/>[\s\S]*?</li>[\s\S]*?</li>[\s\S]*?</li>[\s\S]*?</ul>""",html)
print a
it's ok
but if i use
a=re.findall(r"""<... | python re problem | i test re on some pythonwebshelll, all of them are encounter issue
if i use
a=re.findall(r"""<ul>[\s\S]*?<li><a href="(?P<link>[\s\S]*?)"[\s\S]*?<img src="(?P<img>[\s\S]*?)"[\s\S]*?<br/>[\s\S]*?</li>[\s\S]*?</li>[\s\S]*?</li>[\s\S]*?</ul>""",html)
print a
it's ok
but if i use
a=re.findall(r"""<ul>[\s\S]*?<li><a href=... | [
"The expression [\\s\\S]*? can match any amount of anything. This can potentially cause an enormous amount of backtracking in the case that the match fails. If you are more specific about what you can and can't match then it will allow the match to fail faster.\nAlso, I'd advise you to use an HTML parser instead of... | [
7,
4
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003852009_python_regex.txt |
Q:
Howto do reference to ints by name in Python
I want to have a a reference that reads as "whatever variable of name 'x' is pointing to" with ints so that it behaves as:
>>> a = 1
>>> b = 2
>>> c = (a, b)
>>> c
(1, 2)
>>> a = 3
>>> c
(3, 2)
I know I could do something similar with lists by doing:
>>> a = [1]
>>> b ... | Howto do reference to ints by name in Python | I want to have a a reference that reads as "whatever variable of name 'x' is pointing to" with ints so that it behaves as:
>>> a = 1
>>> b = 2
>>> c = (a, b)
>>> c
(1, 2)
>>> a = 3
>>> c
(3, 2)
I know I could do something similar with lists by doing:
>>> a = [1]
>>> b = [2]
>>> c = (a, b)
>>> c
([1], [2])
>>> a[0] = 3... | [
"No, there isn't a direct way to do this in Python. The reason is that both scalar values (numbers) and tuples are immutable. Once you have established a binding from a name to an immutable value (such as the name c with the tuple (1, 2)), nothing you do except reassigning c can change the value it's bound to.\nNot... | [
4,
2,
2,
1,
1,
0
] | [] | [] | [
"pass_by_reference",
"python",
"standard_library"
] | stackoverflow_0003851829_pass_by_reference_python_standard_library.txt |
Q:
Syntax error with IF statement in Python 3.0
I am teaching myself some Python and I have come across a problem which is probably plainly obvious, except that I can't see it and I need another pair of eyes.
I am making a small game I made into a gui program.
I have this section of code, which when run gives me
"... | Syntax error with IF statement in Python 3.0 | I am teaching myself some Python and I have come across a problem which is probably plainly obvious, except that I can't see it and I need another pair of eyes.
I am making a small game I made into a gui program.
I have this section of code, which when run gives me
"Traceback (most recent call last):
File "", line... | [
"The line:\nW = Label(main, text = \"No, It's \"+str(states[state])\n\nDoesn't have a closing parentheses for the Label() class/function.\nTherefore, the if statement is interpreted as being inside parentheses, which doesn't work.\n"
] | [
3
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0003852722_python_syntax.txt |
Q:
Uploading multiple files in Django without using django.forms
So I've created a form that includes the following item
<input type="file" name="form_file" multiple/>
This tells the browser to allow the user to select multiple files while browsing. The problem I am having is is that when reading / writing the files... | Uploading multiple files in Django without using django.forms | So I've created a form that includes the following item
<input type="file" name="form_file" multiple/>
This tells the browser to allow the user to select multiple files while browsing. The problem I am having is is that when reading / writing the files that are being uploaded, I can only see the last of the files, not... | [
"Based on your file element form_file, the value in request.FILES['form_file'] should be a list of files. So you can do something like: \nfor upfile in request.FILES.getlist('form_file'):\n filename = upfile.name\n # instead of \"filename\" specify the full path and filename of your choice here\n fd = op... | [
6
] | [] | [] | [
"django",
"file_upload",
"python"
] | stackoverflow_0003852744_django_file_upload_python.txt |
Q:
error with django model query
I encountered an error when doing the following retrieval:
class status(models.Model):
pid = models.IntegerField()
phase = models.TextField()
rejected = models.IntegerField()
accepted = models.IntegerField()
type = models.IntegerField(default=1)
date = models.D... | error with django model query | I encountered an error when doing the following retrieval:
class status(models.Model):
pid = models.IntegerField()
phase = models.TextField()
rejected = models.IntegerField()
accepted = models.IntegerField()
type = models.IntegerField(default=1)
date = models.DateTimeField(primary_key = True)
... | [
"Django stats a database transaction for your view. So when you catch the exception, it means the transaction is in a failed state and you can't run any more SQls. You should really try to figure what the actual problem is when it fails either in your post.save or blogContent.save methods. If you really don't ca... | [
2
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003852813_django_django_models_python.txt |
Q:
Django authentication from an automated source
I have a set of URL's in my django application that trigger certain actions or processes. This would be similar to cron jobs. I have a script that polls one or more of these URLS at some regular inverval and I'm interested in adding a layer of security.
I'd like to ... | Django authentication from an automated source | I have a set of URL's in my django application that trigger certain actions or processes. This would be similar to cron jobs. I have a script that polls one or more of these URLS at some regular inverval and I'm interested in adding a layer of security.
I'd like to set up an account for the script and require authent... | [
"\nI have a script that polls one or more of these URLS at some regular inverval and I'm interested in adding a layer of security.\n\nHave you considered using Celery? Celery works seamlessly with Django. This will let you periodically run jobs using the same authentication mechanism as the rest of the project. You... | [
1
] | [] | [] | [
"django",
"django_authentication",
"python",
"urllib2"
] | stackoverflow_0003852933_django_django_authentication_python_urllib2.txt |
Q:
Run a python script and a compiled c code without terminal or dock item in Mac OS X
For great help from stackoverflow, the development for the Mac version of my program is done.
Now I need to deploy my program, and I was wondering if there is any way to "hide" my running Python code (it also runs .so library and ... | Run a python script and a compiled c code without terminal or dock item in Mac OS X | For great help from stackoverflow, the development for the Mac version of my program is done.
Now I need to deploy my program, and I was wondering if there is any way to "hide" my running Python code (it also runs .so library and it seems it makes a dock item to appear).
The program is supposed to be running in the ba... | [
"Are you using py2app and distributing a package? If so, you can set LSBackgroundOnly in info.plist. \nright-click on your package\nchoose *Show Package Contents*\ndouble click on info.plist in Contents to open the property list editor\nAdd Child \"Application is background only\"\n\n(That makes the application inv... | [
1,
0
] | [] | [] | [
"command_line",
"macos",
"python"
] | stackoverflow_0003853038_command_line_macos_python.txt |
Q:
Running cx_Oracle under jython on tomcat
I'm trying to load cx_Oracle using tomcat.
Loading from python works fine, but for jython I'm getting "module not found". My system.path includes site-packages that contains cx_Oracle.so.
I'm new to jython and I've not had time to familiarize myself with all the variables b... | Running cx_Oracle under jython on tomcat | I'm trying to load cx_Oracle using tomcat.
Loading from python works fine, but for jython I'm getting "module not found". My system.path includes site-packages that contains cx_Oracle.so.
I'm new to jython and I've not had time to familiarize myself with all the variables but I believe I have all the necessary environm... | [
"Ben, not all modules that work with Python in CPython implementation will work on other implementations. If such module use system specific calls, or binds to some .dll/.so file it will not work on other Python implementation. cx_Oracle is one os such modules: it binds to Oracle client (there are cx_Oracle version... | [
4
] | [] | [] | [
"cx_oracle",
"jython",
"python"
] | stackoverflow_0003820593_cx_oracle_jython_python.txt |
Q:
Creating and rendering structure with years and months in django
In my blogging app I need a structure (created as a variable in context processor) that will store months number and corresponding year of 5 consecutive months till current one. So if current month is december, we will have year: 2010 and months: 12,... | Creating and rendering structure with years and months in django | In my blogging app I need a structure (created as a variable in context processor) that will store months number and corresponding year of 5 consecutive months till current one. So if current month is december, we will have year: 2010 and months: 12,11,10,9,8. If month will be january we will have years 2010: months: 1... | [
"\nHow to create it and what structure should I use ?\n\nI'd go with a list of year-month tuples. Here is a sample implementation. You'll need the handy python-dateutil library to make this work. \nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\n\ndef get_5_previous_year_months(a_da... | [
2
] | [] | [] | [
"django",
"django_templates",
"python",
"python_datetime"
] | stackoverflow_0003852255_django_django_templates_python_python_datetime.txt |
Q:
My python code won't run outside of my IDE
The following code runs fine in my IDE (PyScripter), however it won't run outside of it. When I go into computer then python26 and double click the file (a .pyw in this case) it fails to run. I have no idea why it's doing this, can anyone please shed some light?
This... | My python code won't run outside of my IDE | The following code runs fine in my IDE (PyScripter), however it won't run outside of it. When I go into computer then python26 and double click the file (a .pyw in this case) it fails to run. I have no idea why it's doing this, can anyone please shed some light?
This is in windows 7 BTW.
My code:
#!/usr/bin/env ... | [
"unless you've been messing around with your standard library, it seems that you have a file named threading.py somewhere on your python path that is replacing the standard one. Try:\n>>>import threading\n>>>print threading.__file__\n\nand make sure that it's the one in your python lib directory (it should beC:\\py... | [
5,
1,
1
] | [] | [] | [
"matplotlib",
"python",
"windows_7"
] | stackoverflow_0003853136_matplotlib_python_windows_7.txt |
Q:
Using cython .pxd files to Augment pure python files
Following the example here, "Augementing .pxd", I'm trying to use ".pxd" files to augment a pure python file. (Add type definitions external to the pure python file).
python file:
class A(object):
def foo(self, i=3, x=None):
print "Big" if i > 1000 e... | Using cython .pxd files to Augment pure python files | Following the example here, "Augementing .pxd", I'm trying to use ".pxd" files to augment a pure python file. (Add type definitions external to the pure python file).
python file:
class A(object):
def foo(self, i=3, x=None):
print "Big" if i > 1000 else "Small"
pxd file:
cdef class A:
cpdef foo(self, i... | [
"Optional arguments in cpdef functions are declared differently from cdef functions which essentially is same as python functions.\nYour .pxd file should be modified to be written as\ncdef class A:\n cpdef foo(self, int i=*, x=*)\n\n"
] | [
14
] | [] | [] | [
"cython",
"python"
] | stackoverflow_0003852742_cython_python.txt |
Q:
Success unit testing pyinotify?
I'm using pyinotify to mirror files from a source directory to a destination directory. My code seems to be working when I execute it manually, but I'm having trouble getting accurate unit test results. I think the problem boils down to this:
I have to use ThreadedNotifier
in my t... | Success unit testing pyinotify? | I'm using pyinotify to mirror files from a source directory to a destination directory. My code seems to be working when I execute it manually, but I'm having trouble getting accurate unit test results. I think the problem boils down to this:
I have to use ThreadedNotifier
in my tests, otherwise they will
just hang, ... | [
"When unit testing, things like threads and the file system should normally be factored out. Do you have a reason to unit test with the actual file system, user input, etc.?\nPython makes it very easy to monkey patch; you could for example, replace the entire os/sys module with a mock object (such as Python Mock) s... | [
5
] | [] | [] | [
"pyinotify",
"python",
"synchronization",
"unit_testing"
] | stackoverflow_0003852935_pyinotify_python_synchronization_unit_testing.txt |
Q:
Google App Engine Python - sort by density in ListProperty
Is that possible to return a db result which sort by density matching in ListProperty
For example, I have a db.ListProperty(basestring) with below value:
list_A = ['a1','a2','a3','a4','a5']
list_B = ['b1','b2','b3','b4','b5']
list_C = ['a1','a2','b1','b2',... | Google App Engine Python - sort by density in ListProperty | Is that possible to return a db result which sort by density matching in ListProperty
For example, I have a db.ListProperty(basestring) with below value:
list_A = ['a1','a2','a3','a4','a5']
list_B = ['b1','b2','b3','b4','b5']
list_C = ['a1','a2','b1','b2','b3']
giving to_be_match_list = ['a1','b1','b2'] and return res... | [
"No, you can't do that in BigTable (GQL).\nIf you grabbed all of the results, however, and wanted to sort them, you could do something like this:\nsome_lists = [list_A, list_B, list_C]\nsome_lists.sort(key=lambda x: len(set(to_be_match_list) & set(x)), reverse=True)\n\n"
] | [
4
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003853598_google_app_engine_python.txt |
Q:
How to access a data structure from a currently running Python process on Linux?
I have a long-running Python process that is generating more data than I planned for. My results are stored in a list that will be serialized (pickled) and written to disk when the program completes -- if it gets that far. But at this... | How to access a data structure from a currently running Python process on Linux? | I have a long-running Python process that is generating more data than I planned for. My results are stored in a list that will be serialized (pickled) and written to disk when the program completes -- if it gets that far. But at this rate, it's more likely that the list will exhaust all 1+ GB free RAM and the process ... | [
"There is not much you can do for a running program. The only thing I can think of is to attach the gdb debugger, stop the process and examine the memory. Alternatively make sure that your system is set up to save core dumps then kill the process with kill --sigsegv <pid>. You should then be able to open the cor... | [
3,
1,
0,
0
] | [] | [] | [
"disk",
"fedora",
"linux",
"memory",
"python"
] | stackoverflow_0003852857_disk_fedora_linux_memory_python.txt |
Q:
Get process ID with python
How to get the current process id with python on windows?
there are this function os.geteuid() but its only works with linux/unix could someone tell
what it the pythonic way to get the current process id on windows.
A:
Do you really want the process ID? Then the answer is this:
>>> im... | Get process ID with python | How to get the current process id with python on windows?
there are this function os.geteuid() but its only works with linux/unix could someone tell
what it the pythonic way to get the current process id on windows.
| [
"Do you really want the process ID? Then the answer is this:\n>>> import os\n>>> os.getpid()\n5328\n\non either Windows or Unix (documentation of os.getpid).\nos.geteuid() doesn't get the process ID, which makes me wonder whether you're really asking a different question...?\n"
] | [
48
] | [] | [] | [
"python",
"winapi",
"windows"
] | stackoverflow_0003853703_python_winapi_windows.txt |
Q:
Manipulating the DateTime object in Google app engine
I am making a blog and store the publishing date of a blog post in the datastore. It looks like this:
post.date = datetime.datetime.now()
It now displays like: 2010-10-04 07:30:15.204352 But I want the datetime to be displayed differently. How (and where) can ... | Manipulating the DateTime object in Google app engine | I am making a blog and store the publishing date of a blog post in the datastore. It looks like this:
post.date = datetime.datetime.now()
It now displays like: 2010-10-04 07:30:15.204352 But I want the datetime to be displayed differently. How (and where) can I set that how the date is displayed? I'd like to set the d... | [
"I think strftime is the method you're looking for.\nFrom the link:\n>>> d.strftime(\"%d/%m/%y\")\n'11/03/02'\n\nIf you pass in the result of the strftime in your 'template_values' or similar (the dictionary you use to pass parameters to the template) instead of the actual date it will be displayed instead.\n",
"... | [
5,
2
] | [] | [] | [
"datetime",
"google_app_engine",
"python"
] | stackoverflow_0003853877_datetime_google_app_engine_python.txt |
Q:
Python doctest example failure
This is probably a silly question.
I am experimenting with python doctest, and I try to run this example
ending with
if __name__ == "__main__":
import doctest
doctest.testfile("example.txt")
I have put "example.txt" in the same folder as the source file containing the exampl... | Python doctest example failure | This is probably a silly question.
I am experimenting with python doctest, and I try to run this example
ending with
if __name__ == "__main__":
import doctest
doctest.testfile("example.txt")
I have put "example.txt" in the same folder as the source file containing the example code, but I get the following erro... | [
"Doctest searches relative to the calling module's directory by default (but you can override this).\nQuoting the docs for doctest.testfile:\n\nOptional argument module_relative specifies how the filename should be interpreted:\n\nIf module_relative is True (the default), then filename specifies an OS-independent m... | [
3
] | [] | [] | [
"doctest",
"python"
] | stackoverflow_0003853980_doctest_python.txt |
Q:
Can I unit test an inner function in python?
Is there any way to write unittests or doctests for innerfunc?
def outerfunc():
def innerfunc():
do_something()
return innerfunc()
A:
Only if you provide a way to extract the inner function object itself, e.g.
def outerfunc(calltheinner=True):
def ... | Can I unit test an inner function in python? | Is there any way to write unittests or doctests for innerfunc?
def outerfunc():
def innerfunc():
do_something()
return innerfunc()
| [
"Only if you provide a way to extract the inner function object itself, e.g.\ndef outerfunc(calltheinner=True):\n def innerfunc():\n do_something()\n if calltheinner:\n return innerfunc()\n else:\n return innerfunc\n\nIf your outer function insists on hiding the inner one entirely insi... | [
8,
4
] | [] | [] | [
"doctest",
"python",
"unit_testing"
] | stackoverflow_0002136910_doctest_python_unit_testing.txt |
Q:
approximate comparison in python
I want to make '==' operator use approximate comparison in my program: float values x and y are equal (==) if
abs(x-y)/(0.5(x+y)) < 0.001
What's a good way to do that? Given that float is a built-in type, I don't think I can redefine the == operator, can I?
Note that I would like ... | approximate comparison in python | I want to make '==' operator use approximate comparison in my program: float values x and y are equal (==) if
abs(x-y)/(0.5(x+y)) < 0.001
What's a good way to do that? Given that float is a built-in type, I don't think I can redefine the == operator, can I?
Note that I would like to use other features of float, the on... | [
"You can create a new class deriving from the builtin float type, and then overwrite the necessary operators:\nclass InexactFloat(float):\n def __eq__(self, other):\n try:\n return abs(self.real - other) / (0.5 * (abs(self.real) + abs(other))) < 0.001\n except ZeroDivisionError:\n ... | [
18,
8,
3
] | [] | [] | [
"comparison",
"python"
] | stackoverflow_0003854047_comparison_python.txt |
Q:
Python asyncore with very low timeout
I have written a program that communicates with many servers at once using the asyncore module. For the most part I am just responding to data received from the servers, but occasionally I need to send some data "out-of-sync". With the default timeout of 30 seconds there is an... | Python asyncore with very low timeout | I have written a program that communicates with many servers at once using the asyncore module. For the most part I am just responding to data received from the servers, but occasionally I need to send some data "out-of-sync". With the default timeout of 30 seconds there is an obvious delay before the packet gets sent,... | [
"To answer my own question: \nFor this type of polling application it is necessary to have a small timeout value. The timeout specifies how long the internal select function blocks waiting for a socket to become active. If you are sending data frequently you need to set the timeout to a small value, so that select ... | [
1
] | [] | [] | [
"asyncore",
"python",
"sockets"
] | stackoverflow_0003789220_asyncore_python_sockets.txt |
Q:
How to distinguish between a sequence and a mapping
I would like to perform an operation on an argument based on the fact that it might be a map-like object or a sequence-like object. I understand that no strategy is going to be 100% reliable for type-like checking, but I'm looking for a robust solution.
Based on ... | How to distinguish between a sequence and a mapping | I would like to perform an operation on an argument based on the fact that it might be a map-like object or a sequence-like object. I understand that no strategy is going to be 100% reliable for type-like checking, but I'm looking for a robust solution.
Based on this answer, I know how to determine whether something is... | [
">>> from collections import Mapping, Sequence\n>>> isinstance('ac', Sequence)\nTrue\n>>> isinstance('ac', Mapping)\nFalse\n>>> isinstance({3:42}, Mapping)\nTrue\n>>> isinstance({3:42}, Sequence)\nFalse\n\ncollections abstract base classes (ABCs)\n",
"Sequences have an __add__ method that implements the + operato... | [
9,
3
] | [] | [] | [
"dictionary",
"python",
"sequence"
] | stackoverflow_0003854470_dictionary_python_sequence.txt |
Q:
Python: Replacing an element in a list of lists (#2)
A previous question with the same title as mine has been posted, with (I think) the same question, but had other problems in the code. I was not able to determine if that case was identical to mine or not.
Anyway, I want to replace an element within a list in a ... | Python: Replacing an element in a list of lists (#2) | A previous question with the same title as mine has been posted, with (I think) the same question, but had other problems in the code. I was not able to determine if that case was identical to mine or not.
Anyway, I want to replace an element within a list in a list.
Code:
myNestedList = [[0,0]]*4 # [[0, 0], [0, 0], [0... | [
"You are having four references to same object by * 4, use instead list comprehension with range for counting:\nmy_nested_list = [[0,0] for count in range(4)]\nmy_nested_list[1][1] = 5\nprint(my_nested_list)\n\nTo explain little more concretely the problem:\nyourNestedList = [[0,0]]*4\nyourNestedList[1][1] = 5\npri... | [
22
] | [] | [] | [
"list",
"mutable",
"python"
] | stackoverflow_0003854870_list_mutable_python.txt |
Q:
What is for Python what 'explode' is for PHP?
I had a string which is stored in a variable myvar = "Rajasekar SP". I want to split it with delimiter like we do using explode in PHP.
What is the equivalent in Python?
A:
Choose one you need:
>>> s = "Rajasekar SP def"
>>> s.split(' ')
['Rajasekar', 'SP', '', 'def... | What is for Python what 'explode' is for PHP? | I had a string which is stored in a variable myvar = "Rajasekar SP". I want to split it with delimiter like we do using explode in PHP.
What is the equivalent in Python?
| [
"Choose one you need:\n>>> s = \"Rajasekar SP def\"\n>>> s.split(' ')\n['Rajasekar', 'SP', '', 'def']\n>>> s.split()\n['Rajasekar', 'SP', 'def']\n>>> s.partition(' ')\n('Rajasekar', ' ', 'SP def')\n\nstr.split and str.partition\n",
"The alternative for explode in php is split.\nThe first parameter is the delimi... | [
200,
17
] | [] | [] | [
"php",
"python",
"string"
] | stackoverflow_0003854867_php_python_string.txt |
Q:
Django 1.2 : strange logging behavior
I have a really strange problem with the standard logging module used in django views. Sometimes it works perfectly and sometimes it does not log messages.
Here is the structure of my code :
/mysite/ (Django root)
my_logging.py (logging configuration)
settings.py
v... | Django 1.2 : strange logging behavior | I have a really strange problem with the standard logging module used in django views. Sometimes it works perfectly and sometimes it does not log messages.
Here is the structure of my code :
/mysite/ (Django root)
my_logging.py (logging configuration)
settings.py
views.py (global views)
data_objects.py ... | [
"Instead of using the logging.info('My statement') syntax, I suggest you use something like the following:\nimport logging\nlogger = logging.getLogger('MySite')\nlogger.info('My statement')\n\nThat is, call your log statements against a logger object, instead of the logging module directly. Likewise, you'll have to... | [
1
] | [] | [] | [
"django",
"logging",
"python"
] | stackoverflow_0003853480_django_logging_python.txt |
Q:
What's wrong in my python code?
Can anyone tell me what's wrong in this code:
#!/usr/local/bin/python
import os
import string, sys
a='sys.argv[1]'
b='sys.argv[2]'
os.system("scp a:/export/home/sample/backup.sql b:/home/rushi/abc.sql")
it's giving the following error:
ssh: a: node name or service name not known... | What's wrong in my python code? | Can anyone tell me what's wrong in this code:
#!/usr/local/bin/python
import os
import string, sys
a='sys.argv[1]'
b='sys.argv[2]'
os.system("scp a:/export/home/sample/backup.sql b:/home/rushi/abc.sql")
it's giving the following error:
ssh: a: node name or service name not known
| [
"What is wrong:\n\na and b don't have second and third values of sys.argv as you might've intended\na and b are not related to the os.system call\nyou're using os.system\nyou're importing module that you're not using\n\nHow to fix:\n\nuse a = sys.argv[1] without the quotes, same for b.\nuse .format method or simila... | [
5,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003854957_python.txt |
Q:
I have a Python list of the prime factors of a number. How do I (pythonically) find all the factors?
I'm working on a Project Euler problem which requires factorization of an integer. I can come up with a list of all of the primes that are the factor of a given number. The Fundamental Theorem of Arithmetic implies... | I have a Python list of the prime factors of a number. How do I (pythonically) find all the factors? | I'm working on a Project Euler problem which requires factorization of an integer. I can come up with a list of all of the primes that are the factor of a given number. The Fundamental Theorem of Arithmetic implies that I can use this list to derive every factor of the number.
My current plan is to take each number in ... | [
"Instead of a list of exponents, consider simply repeating each prime factor by the number of times it is a factor. After that, working on the resulting primefactors list-with-repetitions, itertools.combinations does just what you need -- you'll just require the combinations of length 2 to len(primefactors) - 1 it... | [
11,
6,
3,
2,
1,
1
] | [] | [] | [
"algorithm",
"factorization",
"python"
] | stackoverflow_0003643725_algorithm_factorization_python.txt |
Q:
Runtime model generation using django
I have an application that needs to generate its models on runtime.
This will be done according to the current database scheme.
How can it be done?
How can I create classes on runtime in python?
Should I create a json representation and save it in a database and then unseriali... | Runtime model generation using django | I have an application that needs to generate its models on runtime.
This will be done according to the current database scheme.
How can it be done?
How can I create classes on runtime in python?
Should I create a json representation and save it in a database and then unserialize it into a python object?
| [
"You can try to read this http://code.djangoproject.com/wiki/DynamicModels\nHere is example how to create python model class:\nPerson = type('Person', (models.Model,), {\n 'first_name': models.CharField(max_length=255),\n 'last_name': models.CharField(max_length=255),\n})\n\nYou can also read about python met... | [
8,
2,
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003854159_django_django_models_python.txt |
Q:
error when exec'ing scp from python
this code is giving following error:
os.system("scp %s:/export/home/sample/backup.sql %s:/home/rushi/abc.sql" % (a, b))
Permission denied (publickey,keyboard-interactive).
lost connection
a and b are the command line arguments which accept user name and machine name as argume... | error when exec'ing scp from python | this code is giving following error:
os.system("scp %s:/export/home/sample/backup.sql %s:/home/rushi/abc.sql" % (a, b))
Permission denied (publickey,keyboard-interactive).
lost connection
a and b are the command line arguments which accept user name and machine name as arguments:
eg: root@10.88.77.77 .
| [
"This has nothing to do with Python and everything to do with SSH.\n\nPermission denied (publickey,keyboard-interactive).\n\nIt's telling you you have failed to log in. I suggest you either sort your key-based auth out or pass it a password.\nSee: http://unixhelp.ed.ac.uk/CGI/man-cgi?ssh+1\nOr instead of trying to ... | [
9,
0
] | [] | [] | [
"python",
"scp",
"ssh"
] | stackoverflow_0003855250_python_scp_ssh.txt |
Q:
WX.Python and multiprocessing
I have a wx.python application that takes some files and processes them when a button is clicked. I need to process them in parallel.
I use this code inside the bound button function:
my_pool = multiprocessing.Pool(POOLSIZE)
results=[digest_pool.apply_async(self.fun, [args]) for ... | WX.Python and multiprocessing | I have a wx.python application that takes some files and processes them when a button is clicked. I need to process them in parallel.
I use this code inside the bound button function:
my_pool = multiprocessing.Pool(POOLSIZE)
results=[digest_pool.apply_async(self.fun, [args]) for file in list_files() ]
my_pool.c... | [
"It looks like you're running up against a pretty common problem encountered by people attempting to use threading with GUI toolkits. The core of the issue is that you must never block the main GUI thread in your code. The graphical toolkit needs to be able to constantly respond to events. When you do the my_pool.j... | [
1
] | [] | [] | [
"multithreading",
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0003854414_multithreading_python_wxpython_wxwidgets.txt |
Q:
How to pickle and unpickle instances of a class that inherits from defaultdict?
I have a class that inherits from defaultdict like this:
class listdict(defaultdict):
def __init__(self):
defaultdict.__init__(self, list)
I can pickle it, but when I unpickle it, this happens:
('__init__() takes exactly 1... | How to pickle and unpickle instances of a class that inherits from defaultdict? | I have a class that inherits from defaultdict like this:
class listdict(defaultdict):
def __init__(self):
defaultdict.__init__(self, list)
I can pickle it, but when I unpickle it, this happens:
('__init__() takes exactly 1 argument (2 given)', <class 'listdict'>, (<type 'list'>,))
The class does not defin... | [
"Types define how instances of it get pickled by defining one or more of a (fairly large) set of methods. Each has its own subtle behaviour. See the docs on the pickle protocol. In the case of collections.defaultdict, it uses the __reduce__ method:\n>>> l = collections.defaultdict(list)\n>>> l.__reduce__()\n(<type ... | [
8
] | [
"That error indicates that your 'listdict' class was expected to take one argument (the implicit self), but got two arguments.\nYour class inherits from defaultdict, and defines an initializer. This initializer calls defaultdict's initializer and passes 'list' to it, which in this case may be either a function or a... | [
-1
] | [
"pickle",
"python"
] | stackoverflow_0003855428_pickle_python.txt |
Q:
Longest distinct consecutive list in Python
I have a list:
a = [2, 3, 5, 6, 6, 7, 10, 11, 13, 14, 15, 16, 16, 17, 18, 20, 21]
Is it possible to make a function that shows the longest list of distinct, consecutive elements?
Please, show how to do it
In this case the answer should be:
13, 14, 15, 16, 17, 18
A:
A... | Longest distinct consecutive list in Python | I have a list:
a = [2, 3, 5, 6, 6, 7, 10, 11, 13, 14, 15, 16, 16, 17, 18, 20, 21]
Is it possible to make a function that shows the longest list of distinct, consecutive elements?
Please, show how to do it
In this case the answer should be:
13, 14, 15, 16, 17, 18
| [
"Assuming your list is sorted:\n>>> from itertools import groupby\n>>> z = zip(a, a[1:])\n>>> tmp = [list(j) for i, j in groupby(z, key=lambda x: (x[1] - x[0]) <= 1)]\n>>> max(tmp, key=len)\n[(13, 14), (14, 15), (15, 16), (16, 16), (16, 17), (17, 18)]\n>>> list(range(_[0][0], _[-1][-1]+1))\n[13, 14, 15, 16, 17, 18]... | [
7,
2,
0
] | [] | [] | [
"iteration",
"list",
"python"
] | stackoverflow_0003856016_iteration_list_python.txt |
Q:
How to make a Python string out of non-ascii "bytes"
I need to create a Python string consisting of non-ascii bytes to be used as a command buffer in a C module.
I can do that if I write the string by hand:
mybuffer = "\x00\x00\x10"
But I cannot figure out how to create the string on the fly if I have a set of in... | How to make a Python string out of non-ascii "bytes" | I need to create a Python string consisting of non-ascii bytes to be used as a command buffer in a C module.
I can do that if I write the string by hand:
mybuffer = "\x00\x00\x10"
But I cannot figure out how to create the string on the fly if I have a set of integers which will become the bytes in the string. Concaten... | [
"u''.join(map(unichr, myintegers)) will do what you want nicely.\n",
"Python 2.X\n''.join(chr(i) for i in myintegers)\n\nPython 3.X\nbytes(myintegers)\n\n",
"In [28]: import struct\n\nIn [29]: struct.pack('{0}B'.format(len(myintegers)),*myintegers)\nOut[29]: '\\x01\\x02\\x03\\n'\n\nNote that \nIn [47]: '\\x01\\... | [
4,
3,
0
] | [] | [] | [
"byte",
"python",
"string"
] | stackoverflow_0003855093_byte_python_string.txt |
Q:
In Python, how can I access the namespace of the main module from an imported module?
Specifically, I need to get at some objects and globals from the main module in an imported module. I know how to find those things when the parent module wants some particular thing from a child module, but I can't figure out ho... | In Python, how can I access the namespace of the main module from an imported module? | Specifically, I need to get at some objects and globals from the main module in an imported module. I know how to find those things when the parent module wants some particular thing from a child module, but I can't figure out how to go in the other direction.
| [
"import __main__\n\nBut don't do this.\n",
"The answer you're looking for is:\nimport __main__\n\nmain_global1= __main__.global1\n\nHowever, whenever a module module1 needs stuff from the __main__ module, then:\n\neither the __main__ module should provide all necessary data as parameters to a module1 function/cla... | [
15,
11,
2,
1
] | [] | [] | [
"module",
"namespaces",
"python"
] | stackoverflow_0003648339_module_namespaces_python.txt |
Q:
How to draw polygons with Point2D in wxPython?
I have input values of x, y, z coordinates in the following format:
[-11.235865 5.866001 -4.604924]
[-11.262565 5.414276 -4.842384]
[-11.291885 5.418229 -4.849229]
[-11.235865 5.866001 -4.604924]
I want to draw polygons and succeeded with making a list of wx.point obj... | How to draw polygons with Point2D in wxPython? | I have input values of x, y, z coordinates in the following format:
[-11.235865 5.866001 -4.604924]
[-11.262565 5.414276 -4.842384]
[-11.291885 5.418229 -4.849229]
[-11.235865 5.866001 -4.604924]
I want to draw polygons and succeeded with making a list of wx.point objects. But I need to plot floating point coordinates ... | [
"You just have to pass a list of XY tuples. In wxPython you don't have to explicitly use Point2D objects.\npoints = [\n (-11.235865, 5.866001),\n (-11.262565, 5.414276),\n (-11.291885, 5.418229),\n (-11.235865, 5.866001),\n]\n\ndc.DrawPolygon(points)\n\n",
"DC's only use integers. Try using Cairo or ... | [
0,
0,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003852146_python_wxpython.txt |
Q:
django project directory structure and the python path
I am trying to get the best possible set up for developing my django project from the start and I'm having trouble getting everything to play nicely in the directory structure. I have set up virtualenv's (env in this example) so that I can deploy a clean empty... | django project directory structure and the python path | I am trying to get the best possible set up for developing my django project from the start and I'm having trouble getting everything to play nicely in the directory structure. I have set up virtualenv's (env in this example) so that I can deploy a clean empty python environment for every django project.
The basic stru... | [
"You can put the following in your settings.py to add your appsfolder to your PYTHONPATH:\nimport os\nimport sys\n\nPROJECT_ROOT = os.path.dirname(__file__)\nsys.path.insert(0, os.path.join(PROJECT_ROOT, 'appsfolder'))\n\n"
] | [
16
] | [] | [] | [
"django",
"django_models",
"python",
"pythonpath"
] | stackoverflow_0003856891_django_django_models_python_pythonpath.txt |
Q:
UnicodeEncodeError when reading pdf with pyPdf
Guys i had posted a question earlier pypdf python tool .dont mark this as duplicate as i get this error indicated below
import sys
import pyPdf
def convertPdf2String(path):
content = ""
# load PDF file
pdf = pyPdf.PdfFileReader(file(path, "rb... | UnicodeEncodeError when reading pdf with pyPdf | Guys i had posted a question earlier pypdf python tool .dont mark this as duplicate as i get this error indicated below
import sys
import pyPdf
def convertPdf2String(path):
content = ""
# load PDF file
pdf = pyPdf.PdfFileReader(file(path, "rb"))
# iterate pages
for i in range(0, pd... | [
"I tried it myself and got the same result. Ignore my comment, I hadn't seen that you're writing the output to a file as well. This is the problem:\nf.write(convertPdf2String(sys.argv[1]))\n\nAs convertPdf2String returns a Unicode string, but file.write can only write bytes, the call to f.write tries to automatical... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003856246_python.txt |
Q:
Python IDLE freezes when invoking File > New Window
I am running Mac OS X Snow Leopard ( version 10.6.4 )
with Python Version 2.6.1
Tk Version 8.5
IDLE Version 2.6.1
If I launch IDLE and enter Python statements in the initial window that is presented, all seems fine.
However, if, in the ... | Python IDLE freezes when invoking File > New Window | I am running Mac OS X Snow Leopard ( version 10.6.4 )
with Python Version 2.6.1
Tk Version 8.5
IDLE Version 2.6.1
If I launch IDLE and enter Python statements in the initial window that is presented, all seems fine.
However, if, in the IDLE session, I invoke the menu item File > New Window
a ... | [
"It's a bug (also reported here). \n"
] | [
1
] | [] | [] | [
"python",
"python_idle"
] | stackoverflow_0003857039_python_python_idle.txt |
Q:
URL Builder for CherryPy
After using werkzeug as a web framework (which is great and simple, but doesnt support some features), i'm now trying cherrypy.
Now what I miss in cherrypy is werkzeug's elegant way of building urls (e.g. for links in templates) using the name of a decorated function like this:
@expose('/a... | URL Builder for CherryPy | After using werkzeug as a web framework (which is great and simple, but doesnt support some features), i'm now trying cherrypy.
Now what I miss in cherrypy is werkzeug's elegant way of building urls (e.g. for links in templates) using the name of a decorated function like this:
@expose('/archive/<int:year>/<int:month>'... | [
"You didn't miss it. CherryPy doesn't have that sort of approach built into the 'expose' decorator. You can, however, use the builtin Routes dispatcher with your application, which has a similar URL template syntax. If you'd like to try to wrap that up into a decorator like werkzeug's, we'd love to see the code pas... | [
3
] | [] | [] | [
"cherrypy",
"python",
"werkzeug"
] | stackoverflow_0003848071_cherrypy_python_werkzeug.txt |
Q:
Does WSGI override `Content-Length` header?
HTTP HEAD requests should contain the Content-Length header as if they were GET requests. But if I set a Content-Length header it gets overridden by the WSGI environment (discussion related to mod_wsgi).
Take a look at the following example:
from wsgiref.simple_server im... | Does WSGI override `Content-Length` header? | HTTP HEAD requests should contain the Content-Length header as if they were GET requests. But if I set a Content-Length header it gets overridden by the WSGI environment (discussion related to mod_wsgi).
Take a look at the following example:
from wsgiref.simple_server import make_server
def application(environ, start_... | [
"There is no such configuration setting. You have to override or modify wsgiref/handlers.py, like this:\nfrom wsgiref.simple_server import make_server\nfrom wsgiref.simple_server import ServerHandler\ndef finish_content(self):\n \"\"\"Ensure headers and content have both been sent\"\"\"\n if not self.headers_... | [
0
] | [] | [] | [
"http",
"http_headers",
"python",
"wsgi"
] | stackoverflow_0003857029_http_http_headers_python_wsgi.txt |
Q:
How to access lowlevel API for storing data in Google App Engine for python
What is the alternative for Entity.java in python version?
I do not want any data model. I want my entities without a predefined structure. I just want them to be key and value pairs as the above Entity.java is.
Can I do it in Python versi... | How to access lowlevel API for storing data in Google App Engine for python | What is the alternative for Entity.java in python version?
I do not want any data model. I want my entities without a predefined structure. I just want them to be key and value pairs as the above Entity.java is.
Can I do it in Python version?
| [
"The 'low level' API is in google.appengine.api.datastore. There's no public documentation for it, but the module itself has fairly complete docstrings.\n",
"Try the Expando class.\nclass MyModel(db.Expando)\n pass\n\nYou can then add properties by simply setting the value. And they can be removed too.\nedit:\... | [
6,
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003857140_google_app_engine_google_cloud_datastore_python.txt |
Q:
Python Asymmetric Encryption: Using pre-generated prv/pub keys
Ok first off yes I have searched google and stackoverflow and done some reading (over 4 hours JUST in this sitting) have not found what I need for these reasons:
Many of them suggest just launching an exe like gpg.exe (http://stackoverflow.com/questio... | Python Asymmetric Encryption: Using pre-generated prv/pub keys | Ok first off yes I have searched google and stackoverflow and done some reading (over 4 hours JUST in this sitting) have not found what I need for these reasons:
Many of them suggest just launching an exe like gpg.exe (http://stackoverflow.com/questions/1020320)
Some suggested using PyCrypto or other libraries and loo... | [
"Ok I found how to load it\nfrom twisted.conch.ssh import keys as Keys\nimport base64\n\npublic_key = \"\"\"\\\n---- BEGIN SSH2 PUBLIC KEY ----\nComment: \"rsa-key-20101003\"\nAAAAB3NzaC1yc2EAAAABJQAAAgEAi+91fFsxZ7k1UuudSe5gZoavwARUyZScCtdf\nWQ0ROoJC+XIqW5vVJfgmr+A1jLS5m4wNsrCqeyoX2B22T6iEwqVXrXt3QcbccKMu\nWkLKFK1h... | [
2,
0
] | [] | [] | [
"cryptography",
"encryption_asymmetric",
"python"
] | stackoverflow_0003852190_cryptography_encryption_asymmetric_python.txt |
Q:
Decoding if it's not unicode
I want my function to take an argument that could be an unicode object or a utf-8 encoded string. Inside my function, I want to convert the argument to unicode. I have something like this:
def myfunction(text):
if not isinstance(text, unicode):
text = unicode(text, 'utf-8')... | Decoding if it's not unicode | I want my function to take an argument that could be an unicode object or a utf-8 encoded string. Inside my function, I want to convert the argument to unicode. I have something like this:
def myfunction(text):
if not isinstance(text, unicode):
text = unicode(text, 'utf-8')
...
Is it possible to avoid... | [
"You could just try decoding it with the 'utf-8' codec, and if that does not work, then return the object.\ndef myfunction(text):\n try:\n text = unicode(text, 'utf-8')\n except TypeError:\n return text\n\nprint(myfunction(u'cer\\xf3n'))\n# cerón\n\nWhen you take a unicode object and call its de... | [
20,
0
] | [] | [] | [
"encoding",
"python",
"unicode",
"utf_8"
] | stackoverflow_0003857763_encoding_python_unicode_utf_8.txt |
Q:
Reversing dictionary by key doesn't work
I have a following dictionary :
{2009: [12, 11, 10, 9], 2010: [1]}
I'm trying to reverse-sort it, so that 2010 comes first. Here's the code :
def dictSort(dict):
items = dict.items()
items.sort(reverse=True)
dict = {}
for item in items:
dict[item[0]]... | Reversing dictionary by key doesn't work | I have a following dictionary :
{2009: [12, 11, 10, 9], 2010: [1]}
I'm trying to reverse-sort it, so that 2010 comes first. Here's the code :
def dictSort(dict):
items = dict.items()
items.sort(reverse=True)
dict = {}
for item in items:
dict[item[0]] = item[1]
return dict
But in return I ge... | [
"A dictionary is unordered, whatever you put into it isn't stored in the order you add to it.\nIf you want to do something to it in sorted order, you can do:\nitems = dict.items.sort(reverse=True)\nfor item in items:\n doSomething(item,mydict[item])\n\nor\nfor key,value in iter(sorted(mydict.iteritems(),reverse=... | [
2,
2,
0,
0
] | [] | [] | [
"dictionary",
"python",
"sorting"
] | stackoverflow_0003857880_dictionary_python_sorting.txt |
Q:
pywin32: how do I get a pyDEVMODE object?
How can I create a PyDEVMODE object without just having it as a return from a function call like win32api.EnumDisplaySettingsEx(name, 0)?
A:
It's defined in pywintypes.
>>> import pywintypes
>>> pywintypes.DEVMODEType()
<PyDEVMODE object at 0x00F38E90>
I'm curious as to... | pywin32: how do I get a pyDEVMODE object? | How can I create a PyDEVMODE object without just having it as a return from a function call like win32api.EnumDisplaySettingsEx(name, 0)?
| [
"It's defined in pywintypes.\n>>> import pywintypes\n>>> pywintypes.DEVMODEType()\n<PyDEVMODE object at 0x00F38E90>\n\nI'm curious as to what you are going to use it for?\n"
] | [
1
] | [] | [] | [
"python",
"pywin32",
"winapi"
] | stackoverflow_0003857884_python_pywin32_winapi.txt |
Q:
Handled signal in Python causes FTP connection to interrupt
This scripts checks an FTP and download files at scheduled intervals.
Sending to it the right signal (SIGUSR1) should make it close gracefully, waiting checkAll to complete, if running.
class ScheduledFtpCheck(FtpCheck, Scheduler):
def __init__(self):... | Handled signal in Python causes FTP connection to interrupt | This scripts checks an FTP and download files at scheduled intervals.
Sending to it the right signal (SIGUSR1) should make it close gracefully, waiting checkAll to complete, if running.
class ScheduledFtpCheck(FtpCheck, Scheduler):
def __init__(self):
...
self.aborted, self.checking = False, False... | [
"I found myself the solution:\nrunning ftp process in a separate thread isolated it from main process signals\nthreading.Thread(target=self.checkAll).start()\n\n"
] | [
0
] | [] | [] | [
"python",
"signals"
] | stackoverflow_0003857167_python_signals.txt |
Q:
Python: search playlists on youtube
Is there any way to search playlists on youtube using gdata-python-client? As for documentation it is impossible, but may be there are some workarounds...
A:
The you tube python API seems to have a way of searching the playlists matching specific term.
As per the documentation... | Python: search playlists on youtube | Is there any way to search playlists on youtube using gdata-python-client? As for documentation it is impossible, but may be there are some workarounds...
| [
"The you tube python API seems to have a way of searching the playlists matching specific term.\nAs per the documentation, API has the capability to retrieve a list of playlists matching a user-specified search term.\n\nhttp://code.google.com/apis/youtube/2.0/developers_guide_protocol_playlist_search.html\n\n[Edit ... | [
1
] | [] | [] | [
"gdata_python_client",
"python"
] | stackoverflow_0003857917_gdata_python_client_python.txt |
Q:
Python - Way to distinguish between item index in a list and item's contents in a FOR loop?
For instance, if I wanted to cycle through a list and perform some operation on all but the final list entry, I could do this:
z = [1,2,3,4,2]
for item in z:
if item != z[-1]:
print z.index(item)
But in... | Python - Way to distinguish between item index in a list and item's contents in a FOR loop? | For instance, if I wanted to cycle through a list and perform some operation on all but the final list entry, I could do this:
z = [1,2,3,4,2]
for item in z:
if item != z[-1]:
print z.index(item)
But instead of getting the output "...0 1 2 3," I'd get
"...0 2 3."
Is there a way to perform an operat... | [
"Use a slice:\nfor item in z[:-1]:\n # do something\n\n",
"you could use:\nfor index, item in enumerate(z):\n if index != len(z)-1:\n print index\n\n",
"for index, item in enumerate(your_list):\n do_something\n\n",
"[z.foo() for z in z[:-1]\n",
"def all_but_last(iterable):\n iterable= ite... | [
10,
4,
1,
1,
0
] | [] | [] | [
"duplicates",
"for_loop",
"list",
"loops",
"python"
] | stackoverflow_0003653454_duplicates_for_loop_list_loops_python.txt |
Q:
AppEngine no host given exception
I've got a Python app, that uses urllib.urlopen. It works fine on dev_appserver.py, but throws [Errno http error] no host given error on my GAE production server. The code is exactly the same, the url, it connects to, is hardcoded. I'm out of ideas, what could be wrong.
UPD: the c... | AppEngine no host given exception | I've got a Python app, that uses urllib.urlopen. It works fine on dev_appserver.py, but throws [Errno http error] no host given error on my GAE production server. The code is exactly the same, the url, it connects to, is hardcoded. I'm out of ideas, what could be wrong.
UPD: the code:
def getPic(url):
sock = urllib... | [
"Have you tried reviewing the URL Fetch documentation? Can you show us the URL?\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"python",
"urlopen"
] | stackoverflow_0003858876_google_app_engine_python_urlopen.txt |
Q:
How to add http headers in WSGI middleware?
How can http headers be added within a WSGI middleware?
A:
I've found a nice example from the pylons book.
class Middleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
def custom_start_response... | How to add http headers in WSGI middleware? | How can http headers be added within a WSGI middleware?
| [
"I've found a nice example from the pylons book.\nclass Middleware(object):\n def __init__(self, app):\n self.app = app\n\n def __call__(self, environ, start_response):\n\n def custom_start_response(status, headers, exc_info=None):\n headers.append(('Set-Cookie', \"name=value\"))\n ... | [
21
] | [] | [] | [
"python",
"wsgi"
] | stackoverflow_0003859097_python_wsgi.txt |
Q:
create 2d array in python?
this is the code i am trying to create the 2d matrix
m=4
tagProb=[[]]*(m+1)
count=0
index=0
for line in lines:
print(line)
if(count < m+1):
tagProb[index].append(line.split('@@')[2].strip())
count+=1
if(count == m+1): // this check to goto next index
co... | create 2d array in python? | this is the code i am trying to create the 2d matrix
m=4
tagProb=[[]]*(m+1)
count=0
index=0
for line in lines:
print(line)
if(count < m+1):
tagProb[index].append(line.split('@@')[2].strip())
count+=1
if(count == m+1): // this check to goto next index
count = 0
index+=1
print(t... | [
"You are using * on lists, which has a gotcha -- it will make a list of lots of references to the same object. This is fine for immutables like ints or tuples, but not for mutables like list, because changing one of the objects will change all of them. See:\n>>> foo = [[]]*10\n>>> foo[0].append(1)\n>>> foo\n[[1], [... | [
10,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003859301_python.txt |
Q:
Preventing window overlap in GTK
I've got a Python/Linux application that displays bits of info I need in a GTK window. For the purposes of this discussion, it should behave exactly like a dock - exists on all virtual desktops, and maximized windows do not overlap it.
The first point is pretty easy, but I have ... | Preventing window overlap in GTK | I've got a Python/Linux application that displays bits of info I need in a GTK window. For the purposes of this discussion, it should behave exactly like a dock - exists on all virtual desktops, and maximized windows do not overlap it.
The first point is pretty easy, but I have spent days bashing my head against my ... | [
"Use _NET_WM_STRUT and _NET_WM_STRUT_PARTIAL (for backwards compatibility) properties to reserve space at the edge of X Window System desktop.\nWith PyGtk you can set these properties like so, assuming self.window is an instance of gtk.Window:\nself.window.get_toplevel().show() # must call show() before property_ch... | [
12
] | [] | [] | [
"dock",
"ewmh",
"gtk",
"python",
"x11"
] | stackoverflow_0003859045_dock_ewmh_gtk_python_x11.txt |
Q:
Flask - how do I combine Flask-WTF and Flask-SQLAlchemy to edit db models?
I'm trying to create an edit page for an existing model (already saved to db). The form object expects a multidict instance to populate its fields. This is what I have:
# the model - assumes Flask-SQLAlchemy
from flask.ext.sqlalchemy import... | Flask - how do I combine Flask-WTF and Flask-SQLAlchemy to edit db models? | I'm trying to create an edit page for an existing model (already saved to db). The form object expects a multidict instance to populate its fields. This is what I have:
# the model - assumes Flask-SQLAlchemy
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
class Person(db.Model):
id = db.Column(db... | [
"Please refer to the wtforms documentation:\nhttp://wtforms.simplecodes.com/docs/0.6/forms.html#wtforms.form.Form\nYou pass in the \"obj\" as argument. This will bind the model properties to the form fields to provide the default values:\n@app.route('/person/edit/<id>/', methods=['GET', 'POST'])\ndef edit_person(id... | [
29
] | [] | [] | [
"flask",
"forms",
"python",
"sqlalchemy"
] | stackoverflow_0003850742_flask_forms_python_sqlalchemy.txt |
Q:
decompress name
what is the easiest way to decompress a data name?
For example, change compressed form:
abc[3:0]
into decompressed form:
abc[3]
abc[2]
abc[1]
abc[0]
preferable 1 liner :)
A:
In Perl:
#!perl -w
use strict;
use 5.010;
my @abc = qw/ a b c d /;
say join( " ", reverse @abc[0..3] );
Or if you want... | decompress name | what is the easiest way to decompress a data name?
For example, change compressed form:
abc[3:0]
into decompressed form:
abc[3]
abc[2]
abc[1]
abc[0]
preferable 1 liner :)
| [
"In Perl:\n#!perl -w\n\nuse strict;\nuse 5.010;\n\nmy @abc = qw/ a b c d /;\nsay join( \" \", reverse @abc[0..3] );\n\nOr if you wanted them into separate variables:\nmy( $abc3, $abc2, $abc1, $abc0 ) = reverse @abc[0..3];\n\nEdit: Per your clarification:\nmy $str = \"abc[3:0]\";\n$str =~ /(abc)\\[(\\d+):(\\d+)\\]/;... | [
2,
1
] | [] | [] | [
"awk",
"perl",
"python"
] | stackoverflow_0003858130_awk_perl_python.txt |
Q:
Tips, Tricks, Shortcuts for using EnigmaCurry's Emacs configuration
I just stated using emacs and wanted to find a good configuration for python programming.
I choose the EnigmaCurry emacs configuration which is very extensive. There are a lot of ".el" files.
The problem with this configuration is the lack of docu... | Tips, Tricks, Shortcuts for using EnigmaCurry's Emacs configuration | I just stated using emacs and wanted to find a good configuration for python programming.
I choose the EnigmaCurry emacs configuration which is very extensive. There are a lot of ".el" files.
The problem with this configuration is the lack of documentation on how to use the various tools. Without knowledge of emacs-lis... | [
"People generally don't document their personal configuration that much, especially because they are generally aware what is what. The Emacs Starter Kit is targeting newbie Emacs users and has better documentation than average. \nIt might seem a bit self-promoting, but I encourage you to take a look at my personal ... | [
4,
4
] | [] | [] | [
"emacs",
"emacs23",
"python"
] | stackoverflow_0003851067_emacs_emacs23_python.txt |
Q:
Better way to execute ruby file using Python and How to get ruby console output when ruby file is run from python?
I am building a standalone using python.
This standaloone should execute a ruby file.
I have read this article - http://www.decalage.info/python/ruby_bridge
I have used os.system() which works well.
B... | Better way to execute ruby file using Python and How to get ruby console output when ruby file is run from python? | I am building a standalone using python.
This standaloone should execute a ruby file.
I have read this article - http://www.decalage.info/python/ruby_bridge
I have used os.system() which works well.
But I have an issue here.
If a ruby file has some error, file simply terminates without error.
Can you please let me know... | [
"you can use subprocess module\ncmd=\"ruby myrubyscript.rb\" \np=subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) \noutput, errors = p.communicate() \n\nthen use the output variable\... | [
5
] | [] | [] | [
"python",
"ruby"
] | stackoverflow_0003859864_python_ruby.txt |
Q:
checking when all data is sent using non-blocking open
If I open a a file as os.open( '/dev/ttyS2', O_RDWR | O_NDELAY ), is there any way that I can check when my 'write()' commands have finished? Or, can I open a file for non-blocking read but blocking write?
A:
You have a misunderstanding of what non-blocking ... | checking when all data is sent using non-blocking open | If I open a a file as os.open( '/dev/ttyS2', O_RDWR | O_NDELAY ), is there any way that I can check when my 'write()' commands have finished? Or, can I open a file for non-blocking read but blocking write?
| [
"You have a misunderstanding of what non-blocking means. It does not imply asynchronous operation - you can have any combination of asynchronous/synchronous and blocking/non-blocking.\nA write() just hands data off to the kernel to take care of. When write() returns successfully, the kernel has now taken care of ... | [
4,
3,
1,
0,
0,
0
] | [] | [] | [
"blocking",
"c",
"io",
"linux",
"python"
] | stackoverflow_0003858238_blocking_c_io_linux_python.txt |
Q:
custom comparison for built-in containers
In my code there's numerous comparisons for equality of various containers (list, dict, etc.). The keys and values of the containers are of types float, bool, int, and str. The built-in == and != worked perfectly fine.
I just learned that the floats used in the values of t... | custom comparison for built-in containers | In my code there's numerous comparisons for equality of various containers (list, dict, etc.). The keys and values of the containers are of types float, bool, int, and str. The built-in == and != worked perfectly fine.
I just learned that the floats used in the values of the containers must be compared using a custom c... | [
"The only route to altering the way built-in containers check equality is to make them contain as values, instead of the \"originals\", wrapped values (wrapped in a class that overrides __eq__ and __ne__). This is if you need to alter the way the containers themselves use equality checking, e.g. for the purpose of... | [
9
] | [] | [] | [
"comparison",
"python"
] | stackoverflow_0003860009_comparison_python.txt |
Q:
is all the available swig+python+mingw compile information outdated?
I'm trying to build a C++ extension for python using swig. I've followed the instructions below and the others to a T and can't seem to get my extension to load.
I ran across this article on the MinGW site under "How do I create Python extension... | is all the available swig+python+mingw compile information outdated? | I'm trying to build a C++ extension for python using swig. I've followed the instructions below and the others to a T and can't seem to get my extension to load.
I ran across this article on the MinGW site under "How do I create Python extensions?"
http://www.mingw.org/wiki/FAQ
I also found these tutorials:
http://boo... | [
"Two things to verify:\n\nCheck the C runtime library DLL bound to your python and to your extension DLL with dependency walker to make sure that they are using the same CRT. This is a common source of trouble when building extensions for other languages. (I see it often with Lua, for instance) and can cause intere... | [
2
] | [] | [] | [
"c++",
"python",
"swig"
] | stackoverflow_0003860109_c++_python_swig.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.